mcrypt_encrypt to openssl_encrypt ecb des

喜夏-厌秋 提交于 2019-12-12 04:55:24

问题


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;
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/45912756/mcrypt-encrypt-to-openssl-encrypt-ecb-des

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!