i have to replace deprecated function mcrypt_encrypt using openssl_encrypt.
My old mcrypt function use 'des' cipher and 'ecb' mode.
I tried all cipher options (openssl_get_cipher_methods) and i cant find same result. Help please
$key = '04647132';
$message = hex2bin('046471324B3680');
$mcrypt = base64_encode(mcrypt_encrypt('des', $key, $message, 'ecb'));
foreach (openssl_get_cipher_methods(true) as $cipher) {
$openSsl = base64_encode(@openssl_encrypt($message, $cipher, $key, OPENSSL_RAW_DATA));
if ($openSsl == $mcrypt) {
echo 'FOUND - ' . $cipher . ' = ' . $openSsl;
exit;
}
}
This is because of the different data padding - PKCS#5 for MCrypt and PKCS#7 for OpenSSL.
You can pre-pad $message
yourself (either standard would work, but PKCS#7 is better) and use the OPENSSL_ZERO_PADDING
flag together with OPENSSL_RAW_DATA
. That also means you have to manually strip the padding after decryption - this is the case with all block cipher modes.
But this is the least of your problems ...
Nobody should be using using ECB, or DES today; you should move away from both as soon as possible. It's understandable if you maintain a legacy system, but you don't have to encrypt new data that way.
When you eventually move to another mode, don't ignore the IV requirement - the reason why ECB is bad is exactly because it doesn't utilize an IV.
Also, I know this is just sample code, but $key
in your example isn't a proper key ... use random_bytes()
to generate one.
All of this, and more issues that you don't even know about, could be resolved if you simply used a popular, well-vetted cryptography library - it would do all the work for you in one easy step.
Please do seriously consider this - even professional cryptographers prefer third-party libraries instead of writing their own code, and there's good reasons for that.