I'm upgrading a legacy application from PHP 7.0 to 7.2 and my decrypt function isn't working when I switch out mcrypt for openssl.
I tried the existing answers like mcrypt is deprecated, what is the alternative?, and Gists like https://gist.github.com/odan/c1dc2798ef9cedb9fedd09cdfe6e8e76, but I'm still not able to make the code work.
Can anyone shed some light what I'm doing wrong?
Old code
function decrypt($value, $key) {
$ivLength = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = substr($value, 0, $ivLength);
return rtrim(
mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true),
substr($value, $ivLength),
MCRYPT_MODE_CBC,
$iv
),
"\0"
);
}
New code (not working with existing inputs)
function decrypt($value, $key) {
$ivLength = openssl_cipher_iv_length('AES-128-CBC');
$iv = substr($value, 0, $ivLength);
// Note: $key is hashed because it was hashed in the old encrypt function below
return openssl_decrypt(substr($value, $ivLength), 'AES-128-CBC', hash('sha256', $key, true), OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
}
For context, here's how the old code encrypted the values:
function encrypt($value, $key) {
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_DEV_URANDOM);
return $iv . mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true),
$value,
MCRYPT_MODE_CBC,
$iv
);
}
Also, the raw value in $value
is twice as long when output to the error log in the new code than the old code and looks similar but with more characters.