Mysql AES encrypt value with secret key.

    :param val: Plain text value.
    :param key: The AES key.
    :returns: The encrypted AES value.
762738
def mysql_aes_encrypt(val, key):
    
    assert isinstance(val, binary_type) or isinstance(val, text_type)
    assert isinstance(key, binary_type) or isinstance(key, text_type)
    k = _mysql_aes_key(_to_binary(key))
    v = _mysql_aes_pad(_to_binary(val))
    e = _mysql_aes_engine(k).encryptor()

    return e.update(v) + e.finalize()
359734
def encrypt(self, data):
        '''
        
        '''
        aes_key, hmac_key = self.keys
        pad = self.AES_BLOCK_SIZE - len(data) % self.AES_BLOCK_SIZE
        if six.PY2:
            data = data + pad * chr(pad)
        else:
            data = data + salt.utils.stringutils.to_bytes(pad * chr(pad))
        iv_bytes = os.urandom(self.AES_BLOCK_SIZE)
        if HAS_M2:
            cypher = EVP.Cipher(alg='aes_192_cbc', key=aes_key, iv=iv_bytes, op=1, padding=False)
            encr = cypher.update(data)
            encr += cypher.final()
        else:
            cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes)
            encr = cypher.encrypt(data)
        data = iv_bytes + encr
        sig = hmac.new(hmac_key, data, hashlib.sha256).digest()
        return data + sig
4064
def encrypt(self, txt, key):
        
        # log.debug("encrypt(txt='%s', key='%s')", txt, key)
        assert isinstance(txt, six.text_type), "txt: %s is not text type!" % repr(txt)
        assert isinstance(key, six.text_type), "key: %s is not text type!" % repr(key)

        if len(txt) != len(key):
            raise SecureJSLoginError("encrypt error: %s and '%s' must have the same length!" % (txt, key))

        pbkdf2_hash = PBKDF2SHA1Hasher1().get_salt_hash(txt)

        txt=force_bytes(txt)
        key=force_bytes(key)
        crypted = self.xor(txt, key)
        crypted = binascii.hexlify(crypted)
        crypted = six.text_type(crypted, "ascii")
        return "%s$%s" % (pbkdf2_hash, crypted)
538522
public static String encrypt(String c, String key) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(Hex.decodeHex(key.toCharArray()), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encoded = cipher.doFinal(c.getBytes());
            return new String(Hex.encodeHex(encoded));

        } catch (final Exception e) {
            logger.warn("Could not encrypt string", e);
            return null;
        }
    }
221757
def encrypt_var(csv_keys):
    """"""
    keys = massage_keys(csv_keys.split(','))
    data = sys.stdin.read()
    encrypted = cryptorito.encrypt_var(data, keys)
    print(cryptorito.portable_b64encode(encrypted))
1355268
function encrypt(key, kdfParams) {
    var uuid = kdfParams.get('$UUID');
    if (!uuid || !(uuid instanceof ArrayBuffer)) {
        return Promise.reject(new KdbxError(Consts.ErrorCodes.FileCorrupt, 'no kdf uuid'));
    }
    var kdfUuid = ByteUtils.bytesToBase64(uuid);
    switch (kdfUuid) {
        case Consts.KdfId.Argon2:
            return encryptArgon2(key, kdfParams);
        case Consts.KdfId.Aes:
            return encryptAes(key, kdfParams);
        default:
            return Promise.reject(new KdbxError(Consts.ErrorCodes.Unsupported, 'bad kdf'));
    }
}
971278
def with_value(self, key, val):
        ''' 
        '''
        new_dict = dict(self._dict)
        new_dict[key] = val
        return AuthContext(new_dict)
1193146
static public function mysql_aes_decrypt($val, $ky)
    {

        if (empty($ky) && empty($val)) return null;

        $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
        for ($a = 0; $a < strlen($ky); $a++) {
            $key[$a % 16] = chr(ord($key[$a % 16]) ^ ord($ky[$a]));
        }
        $mode = MCRYPT_MODE_ECB;
        $enc  = MCRYPT_RIJNDAEL_128;
        $dec  = @mcrypt_decrypt($enc, $key, $val, $mode, @mcrypt_create_iv(@mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM));

        return rtrim($dec, ((ord(substr($dec, strlen($dec) - 1, 1)) >= 0 && ord(substr($dec, strlen($dec) - 1, 1)) <= 16) ? chr(ord(substr($dec, strlen($dec) - 1, 1))) : null));
    }
858507
public static String encryptByAES(final String content, final String key) {
        try {
            final KeyGenerator kgen = KeyGenerator.getInstance("AES");
            final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(key.getBytes());
            kgen.init(128, secureRandom);
            final SecretKey secretKey = kgen.generateKey();
            final byte[] enCodeFormat = secretKey.getEncoded();
            final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
            final Cipher cipher = Cipher.getInstance("AES");
            final byte[] byteContent = content.getBytes("UTF-8");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            final byte[] result = cipher.doFinal(byteContent);

            return Hex.encodeHexString(result);
        } catch (final Exception e) {
            LOGGER.log(Level.WARN, "Encrypt failed", e);

            return null;
        }
    }
400925
private static byte[] aes(byte[] input, byte[] key, int mode) {
		try {
			SecretKey secretKey = new SecretKeySpec(key, AES_ALG);
			Cipher cipher = Cipher.getInstance(AES_ALG);
			cipher.init(mode, secretKey);
			return cipher.doFinal(input);
		} catch (GeneralSecurityException e) {
			throw ExceptionUtil.unchecked(e);
		}
	}
415663
async def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]:
        
        if self.public_key is None:
            raise ValueError('Public key not provided during initialisation, cannot encrypt key encrypting key')

        random_bytes = os.urandom(32)

        ciphertext = await self._loop.run_in_executor(
            None, lambda: (self.public_key.encrypt(random_bytes, padding.PKCS1v15())))

        return random_bytes, {}, base64.b64encode(ciphertext).decode()
1121745
async def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes:
        
        if self.private_key is None:
            raise ValueError('Private key not provided during initialisation, cannot decrypt key encrypting key')

        plaintext = await self._loop.run_in_executor(None, lambda: (self.private_key.decrypt(key, padding.PKCS1v15())))

        return plaintext
529325
public static String aesDecrypt(byte[] input, byte[] key) {
		byte[] decryptResult = aes(input, key, Cipher.DECRYPT_MODE);
		return new String(decryptResult, Charsets.UTF_8);
	}
1202452
def encrypt(self, key, iv="", cek="", **kwargs):
        

        _msg = as_bytes(self.msg)
        if "zip" in self:
            if self["zip"] == "DEF":
                _msg = zlib.compress(_msg)
            else:
                raise ParameterError("Zip has unknown value: %s" % self["zip"])

        kwarg_cek = cek or None

        _enc = self["enc"]
        iv = self._generate_iv(_enc, iv)
        cek = self._generate_key(_enc, cek)
        self["cek"] = cek

        logger.debug("cek: %s, iv: %s" % ([c for c in cek], [c for c in iv]))

        _encrypt = RSAEncrypter(self.with_digest).encrypt

        _alg = self["alg"]
        if kwarg_cek:
            jwe_enc_key = ''
        elif _alg == "RSA-OAEP":
            jwe_enc_key = _encrypt(cek, key, 'pkcs1_oaep_padding')
        elif _alg == "RSA-OAEP-256":
            jwe_enc_key = _encrypt(cek, key, 'pkcs1_oaep_256_padding')
        elif _alg == "RSA1_5":
            jwe_enc_key = _encrypt(cek, key)
        else:
            raise NotSupportedAlgorithm(_alg)

        jwe = JWEnc(**self.headers())

        try:
            _auth_data = kwargs['auth_data']
        except KeyError:
            _auth_data = jwe.b64_encode_header()

        ctxt, tag, key = self.enc_setup(_enc, _msg, key=cek, iv=iv,
                                        auth_data=_auth_data)
        return jwe.pack(parts=[jwe_enc_key, iv, ctxt, tag])
1178299
def encrypt(data, key):
    ''''''
    data = __tobytes(data)
    data_len = len(data)
    data = ffi.from_buffer(data)
    key = ffi.from_buffer(__tobytes(key))
    out_len = ffi.new('size_t *')
    result = lib.xxtea_encrypt(data, data_len, key, out_len)
    ret = ffi.buffer(result, out_len[0])[:]
    lib.free(result)
    return ret
291564
def encrypt(self, value):
        """"""
        timestamp = str(int(time.time()))
        value = base64.b64encode(value.encode(self.encoding))
        signature = create_signature(self.secret, value + timestamp.encode(),
                                     encoding=self.encoding)
        return "|".join([value.decode(self.encoding), timestamp, signature])
418623
def encrypt(field)
      return if field !~ /\S/
      aes = OpenSSL::Cipher.new(symmetric_algorithm)
      aes_key = aes.random_key
      iv = aes.random_iv
      encrypt_data(iv, aes_key, field.force_encoding(encoding))
    end