Home >Backend Development >PHP Tutorial >Why Do Mcrypt and OpenSSL Produce Different Encryption Results for Blowfish-ECB?
Replacing Mcrypt with OpenSSL
Issue: Migrating an application from using Mcrypt to OpenSSL for data encryption. The encryption cipher is Blowfish and the mode is Electronic Code Book (ECB). However, the output from Openssl_encrypt and Openssl_decrypt functions differs from MCrypt counterparts, despite having the same parameters.
Cause:
The discrepancy arises from the different padding algorithms used by Mcrypt and OpenSSL. Mcrypt uses PKCS#5 padding, while OpenSSL uses PKCS#7 padding. PKCS#7 padding requires a minimum of 1 byte of padding, while PKCS#5 padding allows for a padding length of 0 bytes. Additionally, Mcrypt requires an Initialization Vector (IV) for ECB mode, even though IV is not necessary for ECB mode.
Resolution:
To resolve the issue, either manually pad the input data with PKCS#7 style padding before using MCrypt functions or re-encrypt the data using the correct padding algorithm.
Here is a modified version of the code provided in the question that uses PKCS#7 padding for MCrypt:
$key = "anotherpassword1"; $str = "does it work 12"; $enc = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $str."", MCRYPT_MODE_ECB); $dec = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $enc, MCRYPT_MODE_ECB); echo(bin2hex($enc).PHP_EOL); var_dump($dec); $enc = openssl_encrypt($str, 'bf-ecb', $key, true); $dec = openssl_decrypt($enc, 'bf-ecb', $key, true); echo(bin2hex($enc).PHP_EOL); var_dump($dec);
By adding 1 byte of padding to the input data before MCrypt encryption, the outputs from both Mcrypt and OpenSSL functions will match. Note that the ECB mode does not require an IV, and it is unnecessary to provide one.
The above is the detailed content of Why Do Mcrypt and OpenSSL Produce Different Encryption Results for Blowfish-ECB?. For more information, please follow other related articles on the PHP Chinese website!