I was encrypting and decrypting data using php mcrypt_encrypt
and mcrypt_decrypt()
with the following arguments:
- $cipher :
MCRYPT_RIJNDAEL_256
- $key : 32 bit hash sha1, generated as follow
substr(hash("sha1", $some_var),0,32)
- $data : can be number or string
- $mode :
MCRYPT_MODE_CBC
- $iv : 32 bit hash sha1 generated as follow
substr(hash("sha1", $other_var),0,32)
Then the generated string is passed to base64_encode
and the result is the encrypted data.
The final function look something like:
function encrypt($data, $key1, $key2) {
return
trim( base64_encode( mcrypt_encrypt(
MCRYPT_RIJNDAEL_256,
substr($key1,0,32),
$data,
MCRYPT_MODE_CBC,
substr($key2,0,32)
)));
}
i want to do the same thing using mysql
, so i can decrypt data while selecting them.
I want to write mysql function that encrypt my data the same as the php encrypt
function above.
I searched mysql documentation and found that AES_ENCRYPT
can do the same thing as mcrypt_encrypt
and TO_BASE64(str)
can do the function of base64_encode
CREATE DEFINER=`root`@`localhost` FUNCTION `mcrypt_encrypt`(
_data text,
_key1 varchar(40),
_key2 varchar(40)
) RETURNS varchar(40) CHARSET utf8
BEGIN
DECLARE encryData varchar(40);
SET @@session.block_encryption_mode = 'aes-256-cbc';
SET encryData = AES_ENCRYPT(
_data,
SUBSTRING(key1,1,32),
SUBSTRING(key2,1,32)
);
RETURN TO_BASE64(encryData);
END
but it not working as the php function.
the output of echo encrypt('abcdefg', $key1, $key2);
where
$key1
is '5c2787d529149d3016ce50451290df1779ec93c7'- and
$key2
is '33db3475db4badb7f6ba86489257c873610e9298' is 'FO51NxIIdOO/UQYtCTGhf2O0eq52C0AnRNTr9CxdOZc='
while the output of
Select mcrypt_encrypt(
'abcdefg',
'5c2787d529149d3016ce50451290df1779ec93c7',
'33db3475db4badb7f6ba86489257c873610e9298'
) as a
is 'FQ=='
i use:
- XAMPP for Linux 5.6.8-0!
- PHP Version 5.6.8
- MySQL 5.6.24 - Source distribution
- i disable case sensitivity in mysql