3
votes

I have a problem with the openssl_decrypt function.

Example code:

// mcrypt
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);

// OpenSSL
$decrypted = openssl_decrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);

The mcrypt_decrypt function works fine. But openssl_decrypt returns FALSE and the following error:

error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt

The key is 32 bytes long and the iv 16 bytes.

Does anyone know what's wrong?

1
It is best not to use mcrypt, it is abandonware, has not been updated in years and does not support standard PKCS#7 (née PKCS#5) padding, only non-standard null padding that can't even be used with binary data. mcrypt had many outstanding bugs dating back to 2003.. Instead consider using defuse, it is being maintained and is correct. - zaph

1 Answers

8
votes

The solution to the problem is OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING:

$decrypted = openssl_decrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv);