Map messages encrypted content to ASN.1 objects.

@param ec The encryptedContent object of the message.

@return ASN.1 representation of the encryptedContent object (SEQUENCE).
180321
function _encryptedContentToAsn1(ec) {
  return [
    // ContentType, always Data for the moment
    asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
      asn1.oidToDer(forge.pki.oids.data).getBytes()),
    // ContentEncryptionAlgorithmIdentifier
    asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
      // Algorithm
      asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
        asn1.oidToDer(ec.algorithm).getBytes()),
      // Parameters (IV)
      asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
        ec.parameter.getBytes())
    ]),
    // [0] EncryptedContent
    asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
      asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
        ec.content.getBytes())
    ])
  ];
}
713632
public function encrypt($m, $e, $n, $s = 3)
    {
        $coded = '';
        $max = strlen($m);
        $packets = ceil($max / $s);
        for ($i = 0; $i < $packets; $i++) {
            $packet = substr($m, $i * $s, $s);
            $code = '0';
            for ($j = 0; $j < $s; $j++) {
                $code = bcadd($code, bcmul(ord($packet[$j]), bcpow('256', $j)));
            }
            $code = bcpowmod($code, $e, $n);
            $coded .= $code . ' ';
        }

        return trim($coded);
    }
707283
public CMSSignedData encode(final PkiMessage<?> message)
            throws MessageEncodingException {
        LOGGER.debug("Encoding pkiMessage");
        LOGGER.debug("Encoding message: {}", message);

        CMSTypedData content = getContent(message);
        LOGGER.debug(
                "Signing pkiMessage using key belonging to [dn={}; serial={}]",
                signerId.getSubjectDN(), signerId.getSerialNumber());
        try {
            CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
            generator.addSignerInfoGenerator(getSignerInfo(message));
            generator.addCertificates(getCertificates());
            LOGGER.debug("Signing {} content", content);
            CMSSignedData pkiMessage = generator.generate(content, true);
            LOGGER.debug("Finished encoding pkiMessage");

            return pkiMessage;
        } catch (CMSException e) {
            throw new MessageEncodingException(e);
        } catch (Exception e) {
            throw new MessageEncodingException(e);
        }
    }
41105
def message_to_chunks m, encrypted=false, sibling_types=[]
    if m.multipart?
      chunks =
        case m.header.content_type.downcase
        when "multipart/signed"
          multipart_signed_to_chunks m
        when "multipart/encrypted"
          multipart_encrypted_to_chunks m
        end

      unless chunks
        sibling_types = m.body.map { |p| p.header.content_type }
        chunks = m.body.map { |p| message_to_chunks p, encrypted, sibling_types }.flatten.compact
      end

      chunks
    elsif m.header.content_type && m.header.content_type.downcase == "message/rfc822"
      encoding = m.header["Content-Transfer-Encoding"]
      if m.body
        body =
        case encoding
        when "base64"
          m.body.unpack("m")[0]
        when "quoted-printable"
          m.body.unpack("M")[0]
        when "7bit", "8bit", nil
          m.body
        else
          raise RMail::EncodingUnsupportedError, encoding.inspect
        end
        body = body.normalize_whitespace
        payload = RMail::Parser.read(body)
        from = payload.header.from.first ? payload.header.from.first.format : ""
        to = payload.header.to.map { |p| p.format }.join(", ")
        cc = payload.header.cc.map { |p| p.format }.join(", ")
        subj = decode_header_field(payload.header.subject) || DEFAULT_SUBJECT
        subj = Message.normalize_subj(subj.gsub(/\s+/, " ").gsub(/\s+$/, ""))
        msgdate = payload.header.date
        from_person = from ? Person.from_address(decode_header_field(from)) : nil
        to_people = to ? Person.from_address_list(decode_header_field(to)) : nil
        cc_people = cc ? Person.from_address_list(decode_header_field(cc)) : nil
        [Chunk::EnclosedMessage.new(from_person, to_people, cc_people, msgdate, subj)] + message_to_chunks(payload, encrypted)
      else
        debug "no body for message/rfc822 enclosure; skipping"
        []
      end
    elsif m.header.content_type && m.header.content_type.downcase == "application/pgp" && m.body
      ## apparently some versions of Thunderbird generate encryped email that
      ## does not follow RFC3156, e.g. messages with X-Enigmail-Version: 0.95.0
      ## they have no MIME multipart and just set the body content type to
      ## application/pgp. this handles that.
      ##
      ## TODO 1: unduplicate code between here and
      ##         multipart_encrypted_to_chunks
      ## TODO 2: this only tries to decrypt. it cannot handle inline PGP
      notice, sig, decryptedm = CryptoManager.decrypt m.body
      if decryptedm # managed to decrypt
        children = message_to_chunks decryptedm, true
        [notice, sig].compact + children
      else
        ## try inline pgp signed
      	chunks = inline_gpg_to_chunks m.body, $encoding, (m.charset || $encoding)
        if chunks
          chunks
        else
          [notice]
        end
      end
    else
      filename =
        ## first, paw through the headers looking for a filename.
        ## RFC 2183 (Content-Disposition) specifies that disposition-parms are
        ## separated by ";". So, we match everything up to " and ; (if present).
        if m.header["Content-Disposition"] && m.header["Content-Disposition"] =~ /filename="?(.*?[^\\])("|;|\z)/m
          $1
        elsif m.header["Content-Type"] && m.header["Content-Type"] =~ /name="?(.*?[^\\])("|;|\z)/im
          $1

        ## haven't found one, but it's a non-text message. fake
        ## it.
        ##
        ## TODO: make this less lame.
        elsif m.header["Content-Type"] && m.header["Content-Type"] !~ /^text\/plain/i
          extension =
            case m.header["Content-Type"]
            when /text\/html/ then "html"
            when /image\/(.*)/ then $1
            end

          ["sup-attachment-#{Time.now.to_i}-#{rand 10000}", extension].join(".")
        end

      ## if there's a filename, we'll treat it as an attachment.
      if filename
        ## filename could be 2047 encoded
        filename = Rfc2047.decode_to $encoding, filename
        # add this to the attachments list if its not a generated html
        # attachment (should we allow images with generated names?).
        # Lowercase the filename because searches are easier that way
        @attachments.push filename.downcase unless filename =~ /^sup-attachment-/
        add_label :attachment unless filename =~ /^sup-attachment-/
        content_type = (m.header.content_type || "application/unknown").downcase # sometimes RubyMail gives us nil
        [Chunk::Attachment.new(content_type, filename, m, sibling_types)]

      ## otherwise, it's body text
      else
        ## Decode the body, charset conversion will follow either in
        ## inline_gpg_to_chunks (for inline GPG signed messages) or
        ## a few lines below (messages without inline GPG)
        body = m.body ? m.decode : ""

        ## Check for inline-PGP
        chunks = inline_gpg_to_chunks body, $encoding, (m.charset || $encoding)
        return chunks if chunks

        if m.body
          ## if there's no charset, use the current encoding as the charset.
          ## this ensures that the body is normalized to avoid non-displayable
          ## characters
          body = m.decode.transcode($encoding, m.charset)
        else
          body = ""
        end

        text_to_chunks(body.normalize_whitespace.split("\n"), encrypted)
      end
    end
  end
674296
def encrypt(self, message):
        

        if not isinstance(message, (bytes, str)):
            raise TypeError
        
        return hashlib.sha1(message.encode('utf-8')).hexdigest()
1341835
ContentCryptoScheme encryptionSchemeOf(Map<String,String> instructionFile) {
        if (instructionFile != null) {
            String cekAlgo = instructionFile.get(Headers.CRYPTO_CEK_ALGORITHM);
            return ContentCryptoScheme.fromCEKAlgo(cekAlgo);
        }
        ObjectMetadata meta = s3obj.getObjectMetadata();
        Map<String, String> userMeta = meta.getUserMetadata();
        String cekAlgo = userMeta.get(Headers.CRYPTO_CEK_ALGORITHM);
        return ContentCryptoScheme.fromCEKAlgo(cekAlgo);
    }
149441
public DERObject toASN1Object()
   {
      ASN1EncodableVector av = new ASN1EncodableVector();
      av.add (organization);
      av.add (noticeNumbers);
      return new DERSequence (av);
   }
112026
public SignalServiceContent decrypt(SignalServiceEnvelope envelope)
      throws InvalidMetadataMessageException, InvalidMetadataVersionException,
      ProtocolInvalidKeyIdException, ProtocolLegacyMessageException,
      ProtocolUntrustedIdentityException, ProtocolNoSessionException,
      ProtocolInvalidVersionException, ProtocolInvalidMessageException,
      ProtocolInvalidKeyException, ProtocolDuplicateMessageException,
      SelfSendException

  {
    try {
      if (envelope.hasLegacyMessage()) {
        Plaintext plaintext = decrypt(envelope, envelope.getLegacyMessage());
        DataMessage message = DataMessage.parseFrom(plaintext.getData());
        return new SignalServiceContent(createSignalServiceMessage(plaintext.getMetadata(), message),
                                        plaintext.getMetadata().getSender(),
                                        plaintext.getMetadata().getSenderDevice(),
                                        plaintext.getMetadata().getTimestamp(),
                                        plaintext.getMetadata().isNeedsReceipt());
      } else if (envelope.hasContent()) {
        Plaintext plaintext = decrypt(envelope, envelope.getContent());
        Content   message   = Content.parseFrom(plaintext.getData());

        if (message.hasDataMessage()) {
          return new SignalServiceContent(createSignalServiceMessage(plaintext.getMetadata(), message.getDataMessage()),
                                          plaintext.getMetadata().getSender(),
                                          plaintext.getMetadata().getSenderDevice(),
                                          plaintext.getMetadata().getTimestamp(),
                                          plaintext.getMetadata().isNeedsReceipt());
        } else if (message.hasSyncMessage() && localAddress.getNumber().equals(plaintext.getMetadata().getSender())) {
          return new SignalServiceContent(createSynchronizeMessage(plaintext.getMetadata(), message.getSyncMessage()),
                                          plaintext.getMetadata().getSender(),
                                          plaintext.getMetadata().getSenderDevice(),
                                          plaintext.getMetadata().getTimestamp(),
                                          plaintext.getMetadata().isNeedsReceipt());
        } else if (message.hasCallMessage()) {
          return new SignalServiceContent(createCallMessage(message.getCallMessage()),
                                          plaintext.getMetadata().getSender(),
                                          plaintext.getMetadata().getSenderDevice(),
                                          plaintext.getMetadata().getTimestamp(),
                                          plaintext.getMetadata().isNeedsReceipt());
        } else if (message.hasReceiptMessage()) {
          return new SignalServiceContent(createReceiptMessage(plaintext.getMetadata(), message.getReceiptMessage()),
                                          plaintext.getMetadata().getSender(),
                                          plaintext.getMetadata().getSenderDevice(),
                                          plaintext.getMetadata().getTimestamp(),
                                          plaintext.getMetadata().isNeedsReceipt());
        } else if (message.hasTypingMessage()) {
          return new SignalServiceContent(createTypingMessage(plaintext.getMetadata(), message.getTypingMessage()),
                                          plaintext.getMetadata().getSender(),
                                          plaintext.getMetadata().getSenderDevice(),
                                          plaintext.getMetadata().getTimestamp(),
                                          false);
        }
      }

      return null;
    } catch (InvalidProtocolBufferException e) {
      throw new InvalidMetadataMessageException(e);
    }
  }
147159
private ContentCryptoMaterial newContentCryptoMaterial(
            EncryptionMaterialsProvider kekMaterialProvider,
            Map<String, String> materialsDescription, Provider provider,
            AmazonWebServiceRequest req) {
        EncryptionMaterials kekMaterials =
            kekMaterialProvider.getEncryptionMaterials(materialsDescription);
        if (kekMaterials == null) {
            return null;
        }
        return buildContentCryptoMaterial(kekMaterials, provider, req);
    }
933212
public static byte[] encrypt(byte[] plainText) {
		try {
//			plainText = fixText(plainText);
//			plainText = paddArray(plainText, 16);
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING", "SunJCE");
			SecretKeySpec key = new SecretKeySpec(ENCRYPTION_KEY.getBytes("UTF-8"), "AES");
			JK.fixMe();
			cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
//			return toString(cipher.doFinal(plainText.getBytes("UTF-8")));
			return cipher.doFinal(plainText);
		} catch (Exception e) {
			throw new JKSecurityException(e);
		}
	}
600597
function contentEncryptCbc(aad, cek, cekEnc, plain, bits) {
  let iv = crypto.randomBytes(16);
  let bytes = bits >> 3;
  let cipher = crypto.createCipheriv(`AES-${bits}-CBC`, cek.slice(bytes), iv);
  let enc = Buffer.concat([cipher.update(plain), cipher.final()]);
  let len = aad.length << 3;
  let al = Buffer.from(`000000000000000${len.toString(16)}`.slice(-16), 'hex');
  let hmac = crypto.createHmac(`SHA${bits << 1}`, cek.slice(0, bytes));
  hmac.update(Buffer.from(aad)).update(iv).update(enc).update(al);
  let tag = buf2b64url(hmac.digest().slice(0, bytes));
  return `${aad}.${cekEnc}.${buf2b64url(iv)}.${buf2b64url(enc)}.${tag}`;
}
708776
public static ContentCryptoMaterial wrap(
            SecretKey cek, byte[] iv,
            ContentCryptoScheme contentCryptoScheme,
            Provider provider,
            SecuredCEK cekSecured) {
        return new ContentCryptoMaterial(
                cekSecured.getMaterialDescription(),
                cekSecured.getEncrypted(),
                cekSecured.getKeyWrapAlgorithm(),
                contentCryptoScheme.createCipherLite
                    (cek, iv, Cipher.ENCRYPT_MODE, provider));
    }
35256
def decode(self, message, ecc, k=None, enable_erasures=False, erasures_char="\x00", only_erasures=False):
        ''''''
        if not k: k = self.k

        # Optimization, use bytearray
        if isinstance(message, _str):
            message = bytearray([ord(x) for x in message])
            ecc = bytearray([ord(x) for x in ecc])

        # Detect erasures positions and replace with null bytes (replacing erasures with null bytes is necessary for correct syndrome computation)
        # Note that this must be done before padding, else we risk counting the padded null bytes as erasures!
        erasures_pos = None
        if enable_erasures:
            # Concatenate to find erasures in the whole codeword
            mesecc = message + ecc
            # Convert char to a int (because we use a bytearray)
            if isinstance(erasures_char, _str): erasures_char = ord(erasures_char)
            # Find the positions of the erased characters
            erasures_pos = [i for i in xrange(len(mesecc)) if mesecc[i] == erasures_char]
            # Failing case: no erasures could be found and we want to only correct erasures, then we return the message as-is
            if only_erasures and not erasures_pos: return message, ecc

        # Pad with null bytes if necessary
        message, pad = self.pad(message, k=k)
        ecc, _ = self.rpad(ecc, k=k) # fill ecc with null bytes if too small (maybe the field delimiters were misdetected and this truncated the ecc? But we maybe still can correct if the truncation is less than the resilience rate)

        # If the message was left padded, then we need to update the positions of the erasures
        if erasures_pos and pad:
            len_pad = len(pad)
            erasures_pos = [x+len_pad for x in erasures_pos]

        # Decoding
        if self.algo == 1:
            msg_repaired, ecc_repaired = self.ecc_manager.decode(message + ecc, nostrip=True, k=k, erasures_pos=erasures_pos, only_erasures=only_erasures) # Avoid automatic stripping because we are working with binary streams, thus we should manually strip padding only when we know we padded
        elif self.algo == 2:
            msg_repaired, ecc_repaired = self.ecc_manager.decode_fast(message + ecc, nostrip=True, k=k, erasures_pos=erasures_pos, only_erasures=only_erasures)
        elif self.algo == 3:
            #msg_repaired, ecc_repaired = self.ecc_manager.decode_fast(message + ecc, nostrip=True, k=k, erasures_pos=erasures_pos, only_erasures=only_erasures)
            msg_repaired, ecc_repaired = reedsolo.rs_correct_msg_nofsynd(bytearray(message + ecc), self.n-k, fcr=self.fcr, generator=self.gen_nb, erase_pos=erasures_pos, only_erasures=only_erasures)
            msg_repaired = bytearray(msg_repaired)
            ecc_repaired = bytearray(ecc_repaired)
        elif self.algo == 4:
            msg_repaired, ecc_repaired = reedsolo.rs_correct_msg(bytearray(message + ecc), self.n-k, fcr=self.fcr, generator=self.gen_nb, erase_pos=erasures_pos, only_erasures=only_erasures)
            msg_repaired = bytearray(msg_repaired)
            ecc_repaired = bytearray(ecc_repaired)

        if pad: # Strip the null bytes if we padded the message before decoding
            msg_repaired = msg_repaired[len(pad):len(msg_repaired)]
        return msg_repaired, ecc_repaired
1004941
public static byte[] aesEncrypt(byte[] input, byte[] key, byte[] iv) {
		return aes(input, key, iv, Cipher.ENCRYPT_MODE);
	}
1226895
public byte[] encrypt(byte[] message, byte[] aad, byte[] iv) throws GeneralSecurityException {
		Cipher cipher = getCipher(true);
		if(iv == null && generateIV && ivLength > 0) {
			iv = generateIV();
		}
		if(iv != null) {
			cipher.init(Cipher.ENCRYPT_MODE, getKey(), getAlgorithmParameterSpec(iv));
		} else {
			cipher.init(Cipher.ENCRYPT_MODE, getKey());
			iv = cipher.getIV();
		}
		ivThreadLocal.set(iv);
		if(aad != null) {
			cipher.updateAAD(aad);
		}
		byte[] encrypted;
		if(prependIV && iv != null) {
			int outputSize = cipher.getOutputSize(message.length);
			encrypted = new byte[iv.length + outputSize];
			System.arraycopy(iv, 0, encrypted, 0, iv.length);
			try {
				int nBytes = cipher.doFinal(message, 0, message.length, encrypted, iv.length);
				if(nBytes < outputSize) {
					int excessBytes = outputSize - nBytes;
					byte[] resized = new byte[encrypted.length - excessBytes];
					System.arraycopy(encrypted, 0, resized, 0, resized.length);
					encrypted = resized;
				}
			} catch (ShortBufferException e) {
				throw new RuntimeException(e);
			}
		} else {
			encrypted = cipher.doFinal(message);
		}
		return encrypted;
	}
945158
public static BitSet decode(String enc) {
        byte[] fp = base64Decode(enc);
        if (fp.length < 4) {
            throw new IllegalArgumentException("Input is not a proper PubChem base64 encoded fingerprint");
        }

        int len = (fp[0] << 24) | (fp[1] << 16) | (fp[2] << 8) | (fp[3] & 0xff);
        if (len != FP_SIZE) {
            throw new IllegalArgumentException("Input is not a proper PubChem base64 encoded fingerprint");
        }

        // note the IChemObjectBuilder is passed as null because the SMARTSQueryTool
        // isn't needed when decoding
        PubchemFingerprinter pc = new PubchemFingerprinter(null);
        for (int i = 0; i < pc.m_bits.length; ++i) {
            pc.m_bits[i] = fp[i + 4];
        }

        BitSet ret = new BitSet(FP_SIZE);
        for (int i = 0; i < FP_SIZE; i++) {
            if (pc.isBitOn(i)) ret.set(i);
        }
        return ret;
    }
901196
private static ASN1Primitive getIssuer(byte[] enc) {
        try {
            ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc));
            ASN1Sequence seq = (ASN1Sequence)in.readObject();
            return (ASN1Primitive)seq.getObjectAt(seq.getObjectAt(0) instanceof DERTaggedObject ? 3 : 2);
        }
        catch (IOException e) {
            throw new ExceptionConverter(e);
        }
    }