Reputation: 967
I want to move from mcrypt_encrypt() to openssl_encrypt() for AES 256 encryption
But the encrypted data are different !
For example mcrypt_encrypt() output:
Od2i8FHmWvMeXt+HwCy7k93koPVClK1erHsZwoB6sUE=
and openssl_encrypt() output:
Od2i8FHmWvMeXt+HwCy7kyCt0nvHTaO4IdjdiF15LAc=
My code:
<?php
$encryption_key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(16);
$data = "Here's some data to encrypt!";
$encrypted = openssl_encrypt($data, "aes-256-cbc", $encryption_key, 0, $iv);
echo "encrypted: $encrypted\n\n";
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $encryption_key, $data, MCRYPT_MODE_CBC, $iv));
echo "encrypted: $encrypted\n\n";
?>
What is the problem? Thank you
Upvotes: 1
Views: 753
Reputation: 112857
It is most likely the padding. Notice that the first block is the same for each and the last block is different.
The text being encrypted is 28 bytes so the the last block will have 4 bytes of padding: 16-(28%16) = 4.
PHP mcrypt does not support standard PKCS#7 (née PKCS#5) padding, only non-standard null padding.
So PHP mcrypt will appoint 4-bytes of 0x00 and openssl 4-bytes of 0x04. See PKCS#7 padding.
So if you want to create the same encrypted output with openssl_encrypt
you need too specify zero padding option (OPENSSL_ZERO_PADDING
) and add the null padding yourself. Note: null padding is not robust because it can not correctly handle all binary data.
Example: openssl_encrypt($data, "aes-256-cbc", $encryption_key, OPENSSL_ZERO_PADDING, $iv);
mcrypt_encrypt():
Base64: Od2i8FHmWvMeXt+HwCy7k93koPVClK1erHsZwoB6sUE=
Hex: 39DDA2F051E65AF31E5EDF87C02CBB93 DDE4A0F54294AD5EAC7B19C2807AB141
openssl_encrypt:
Base64: Od2i8FHmWvMeXt+HwCy7kyCt0nvHTaO4IdjdiF15LAc=
Hex: 39DDA2F051E65AF31E5EDF87C02CBB93 20ADD27BC74DA3B821D8DD885D792C07
Upvotes: 3