mcrypt_encrypt到openssl_encrypt ecb des [英] mcrypt_encrypt to openssl_encrypt ecb des
问题描述
我必须使用openssl_encrypt替换不推荐使用的函数mcrypt_encrypt. 我以前的mcrypt函数使用"des"密码和"ecb"模式. 我尝试了所有密码选项(openssl_get_cipher_methods),但找不到相同的结果.请帮助
$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;
}
}
这是因为数据填充不同-MCrypt的PKCS#5和OpenSSL的PKCS#7.
您可以自己预先填充$message
(两种标准都可以,但PKCS#7更好),然后将OPENSSL_ZERO_PADDING
标志与OPENSSL_RAW_DATA
一起使用.这也意味着您必须在解密后手动剥离填充-所有分组密码模式都是这种情况.
但这是您最少的问题...
今天没有人应该使用ECB或DES;您应该尽快远离两者.如果您维护旧系统,这是可以理解的,但是不必那样加密 new 数据.
当您最终转换到另一种模式时,请不要忽略IV要求-ECB不好的原因恰恰是因为它没有利用IV.
此外,我知道这只是示例代码,但是示例中的$key
并不是正确的密钥……请使用random_bytes()
生成一个.
所有这些以及您甚至不知道的更多问题都可以解决,如果您只使用流行的,经过严格审查的加密库-它会为您轻松完成所有工作.
请认真考虑这一点-即使是专业密码学家也更喜欢使用第三方库而不是编写自己的代码,这是有充分理由的.
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.
这篇关于mcrypt_encrypt到openssl_encrypt ecb des的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!