Takes two arguments, the encryption type and the base payload
554372
def send(self, enc, load, tries=1, timeout=60):
        '''
        
        '''
        payload = {'enc': enc}
        payload['load'] = load
        pkg = self.serial.dumps(payload)
        self.socket.send(pkg)
        self.poller.register(self.socket, zmq.POLLIN)
        tried = 0
        while True:
            polled = self.poller.poll(timeout * 1000)
            tried += 1
            if polled:
                break
            if tries > 1:
                log.info(
                    'SaltReqTimeoutError: after %s seconds. (Try %s of %s)',
                    timeout, tried, tries
                )
            if tried >= tries:
                self.clear_socket()
                raise SaltReqTimeoutError(
                    'SaltReqTimeoutError: after {0} seconds, ran {1} '
                    'tries'.format(timeout * tried, tried)
                )
        return self.serial.loads(self.socket.recv())
1321653
def encrypt(receiver_pubhex: str, msg: bytes) -> bytes:
    
    disposable_key = generate_key()
    receiver_pubkey = hex2pub(receiver_pubhex)
    aes_key = derive(disposable_key, receiver_pubkey)
    cipher_text = aes_encrypt(aes_key, msg)
    return disposable_key.public_key.format(False) + cipher_text
643463
def get_json_payload_magic_envelope(self, payload):
        """"""
        private_key = self._get_user_key()
        return EncryptedPayload.decrypt(payload=payload, private_key=private_key)
330204
public static void main(String[] args) throws Exception {
        EncryptionUtil util = new EncryptionUtil();

        System.out.println("Enter text to encrypt: ");
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String input = reader.readLine();
        if (null != input && !"".equals(input)) {
            System.out.println("'" + util.encrypt(input) + "'");
        }
    }
689853
def crypt(self, data, crypt_type):
        """"""

        # Error check the data
        if not data:
            return ''
        if len(data) % self.block_size != 0:
            if crypt_type == des.DECRYPT: # Decryption must work on 8 byte blocks
                raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n" + data + ".")
            if not self.getPadding():
                raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n. Try setting the optional padding character")
            else:
                data += (self.block_size - (len(data) % self.block_size)) * self.getPadding()
            # print "Len of data: %f" % (len(data) / self.block_size)

        if self.getMode() == CBC:
            if self.getIV():
                iv = self.__String_to_BitList(self.getIV())
            else:
                raise ValueError("For CBC mode, you must supply the Initial Value (IV) for ciphering")

        # Split the data into blocks, crypting each one seperately
        i = 0
        result = []
        while i < len(data):
            block = self.__String_to_BitList(data[i:i+8])

            # Xor with IV if using CBC mode
            if self.getMode() == CBC:
                if crypt_type == des.ENCRYPT:
                    block = list(map(lambda x, y: x ^ y, block, iv))

                processed_block = self.__des_crypt(block, crypt_type)

                if crypt_type == des.DECRYPT:
                    processed_block = list(map(lambda x, y: x ^ y, processed_block, iv))
                    iv = block
                else:
                    iv = processed_block
            else:
                processed_block = self.__des_crypt(block, crypt_type)


            # Add the resulting crypted block to our list
            result.append(self.__BitList_to_String(processed_block))
            i += 8

        # Return the full crypted string
        if _pythonMajorVersion < 3:
            return ''.join(result)
        else:
            return bytes.fromhex('').join(result)
316525
String encrypt(String property) throws GeneralSecurityException,
			UnsupportedEncodingException {
		SecretKeyFactory keyFactory = SecretKeyFactory
				.getInstance("PBEWithMD5AndDES");
		SecretKey key = keyFactory.generateSecret(new PBEKeySpec(cypher));
		Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
		pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, 20));
		return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));
	}
762463
async function encryptPBES1(binKey, passphrase, algorithm, iterationCount){
  // pbkdf1
  const pBuffer = jseu.encoder.stringToArrayBuffer(passphrase);
  const salt = await jscrandom.getRandomBytes(8); // defined as 8 octet
  const hash = params.passwordBasedEncryptionSchemes[algorithm].hash;
  const keyIv = await pbkdf.pbkdf1(pBuffer, salt, iterationCount, 16, hash);
  const key = keyIv.slice(0, 8);
  const iv = keyIv.slice(8, 16);

  // decryption
  const encrypt = params.passwordBasedEncryptionSchemes[algorithm].encrypt;
  let out;
  // TODO: Other Encryption Scheme
  if(encrypt === 'DES-CBC') {
    const CBC = des.CBC.instantiate(des.DES);
    const ct = CBC.create({type: 'encrypt', key, iv});
    out = Buffer.from(ct.update(binKey).concat(ct.final()));
  }
  else throw new Error('UnsupportedEncryptionAlgorithm');

  return {
    encryptionAlgorithm: {
      algorithm,
      parameters: {
        salt: Buffer.from(salt),
        iterationCount: new BN(iterationCount)
      }
    },
    encryptedData: out
  };
}
255410
function OlmEncryption(params) {
    base.EncryptionAlgorithm.call(this, params);
    this._sessionPrepared = false;
    this._prepPromise = null;
}
1289075
def encryption_key(self, alg, **kwargs):
        
        if not self.key:
            self.deserialize()

        try:
            tsize = ALG2KEYLEN[alg]
        except KeyError:
            raise UnsupportedAlgorithm(alg)

        if tsize <= 32:
            # SHA256
            _enc_key = sha256_digest(self.key)[:tsize]
        elif tsize <= 48:
            # SHA384
            _enc_key = sha384_digest(self.key)[:tsize]
        elif tsize <= 64:
            # SHA512
            _enc_key = sha512_digest(self.key)[:tsize]
        else:
            raise JWKException("No support for symmetric keys > 512 bits")

        logger.debug('Symmetric encryption key: {}'.format(
            as_unicode(b64e(_enc_key))))

        return _enc_key
428409
private SimpleEntry<String, String> parseEncryptionData(String jsonEncryptionData)
  throws SnowflakeSQLException
  {
    ObjectMapper mapper = ObjectMapperFactory.getObjectMapper();
    JsonFactory factory = mapper.getJsonFactory();
    try
    {
      JsonParser parser = factory.createJsonParser(jsonEncryptionData);
      JsonNode encryptionDataNode = mapper.readTree(parser);

      String iv = encryptionDataNode.get("ContentEncryptionIV").asText();
      String key = encryptionDataNode.get("WrappedContentKey").get("EncryptedKey").asText();

      return new SimpleEntry<String, String>(key, iv);
    }
    catch (Exception ex)
    {
      throw new SnowflakeSQLException(ex, SqlState.SYSTEM_ERROR,
                                      ErrorCode.IO_ERROR.getMessageCode(),
                                      "Error parsing encryption data as json" + ": " +
                                      ex.getMessage());
    }
  }
10020
function passphraseToKey(type, passphrase, salt)
  {
  debug('passphraseToKey', type, passphrase, salt);
  var nkey = keyBytes[type];

  if (!nkey)
    {
    var allowed = Object.keys(keyBytes);
    throw new TypeError('Unsupported type. Allowed: ' + allowed);
    }

  var niv = salt.length;
  var saltLen = 8;
  if (salt.length !== saltLen)
    salt = salt.slice(0, saltLen);
  var mds = 16;
  var addmd = false;
  var md_buf;
  var key = new Buffer(nkey);
  var keyidx = 0;

  while (true)
    {
    debug('loop nkey=%d mds=%d', nkey, mds);
    var c = crypto.createHash('md5');

    if (addmd)
      c.update(md_buf);
    else
      addmd = true;

    if (!Buffer.isBuffer(passphrase))
      c.update(passphrase, 'ascii');
    else
      c.update(passphrase);

    c.update(salt);
    md_buf = c.digest('buffer');

    var i = 0;
    while (nkey && i < mds)
      {
      key[keyidx++] = md_buf[i];
      nkey--;
      i++;
      }

    var steps = Math.min(niv, mds - i);
    niv -= steps;
    i += steps;

    if ((nkey == 0) && (niv == 0)) break;
    }

  return key
  }
542841
def encrypt(pubkey, password):
    
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password)
689654
function parse_EncryptionVerifier(blob, length/*:number*/) {
	var o = {}, tgt = blob.l + length;
	blob.l += 4; // SaltSize must be 0x10
	o.Salt = blob.slice(blob.l, blob.l+16); blob.l += 16;
	o.Verifier = blob.slice(blob.l, blob.l+16); blob.l += 16;
	/*var sz = */blob.read_shift(4);
	o.VerifierHash = blob.slice(blob.l, tgt); blob.l = tgt;
	return o;
}
265838
def generate_payload(exclude=None, **kwargs):
    
    if exclude is None:
        exclude = []
    return {key: value for key, value in kwargs.items() if
            key not in exclude + DEFAULT_FILTER
            and value is not None
            and not key.startswith('_')}
1128316
def payload(self, p):
        
        if isinstance(p, tuple):
            k = p[0]
            v = p[1]
            self.actual_content_type = k
            self._payload[k] = v
        else:
            self._payload = {defines.Content_types["text/plain"]: p}
931728
def encryptParams(self, params, key):
        
        keypair = Curve.generateKeyPair()
        encodedparams = self.urlencodeParams(params)

        cipher = AESGCM(Curve.calculateAgreement(key, keypair.privateKey))
        ciphertext = cipher.encrypt(b'\x00\x00\x00\x00' + struct.pack('>Q', 0), encodedparams.encode(), b'')

        payload = base64.b64encode(keypair.publicKey.serialize()[1:] + ciphertext)
        return [('ENC', payload)]
1263925
def encrypt(self):
        
        value = self.parameters.get("Plaintext")
        if isinstance(value, six.text_type):
            value = value.encode('utf-8')
        return json.dumps({"CiphertextBlob": base64.b64encode(value).decode("utf-8"), 'KeyId': 'key_id'})