繁体   English   中英

PHP 使用 openssl 解密数据(使用 mcrypt 加密)

[英]PHP Decrypt data (encrypted with mcrypt) using openssl

我有一个充满 3DES (ECB) 加密数据的数据库,这些数据是用 php Mcrypt 库加密的。 由于 Mcrypt 已弃用,我需要切换到 OpenSSL 对其进行解密。 所有数据将使用 xchacha20-poly1305-ietf 重新加密。

所以我不需要关于 3DES 不安全和 ECB 坏等的评论,我们知道,这就是我们试图解密以获得更好的加密算法的原因。

我在下面提供了用于使用 mcrypt 加密的代码以及我们尝试使用的 1 行(openssl)来解密它。 它总是返回 false,我们想知道为什么。

我开始怀疑问题在于 mcrypt 库使用 8 字节 IV 而打开 SSL 说它必须是 0 字节。

如果您能找到一种使用 openssl 解密值的方法,我们将不胜感激。

提前致谢。

这是代码:

$sEncryptionKey = 'aaaabbbbccccddddeeeeffff';
$sDataToEncrypt = 'Foo bar';

echo "Data to be Encrypted: $sDataToEncrypt\n";

$rMcrypt = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');
$iIvSize = mcrypt_enc_get_iv_size($rMcrypt); //This gives 8 bytes

$sInitializationVector = mcrypt_create_iv($iIvSize, MCRYPT_RAND);
$iKeySize = mcrypt_enc_get_key_size($rMcrypt);

if ($iKeySize != strlen($sEncryptionKey)) {
    throw new Exception ('Invalid key length: '.$iKeySize);
}

mcrypt_generic_init($rMcrypt, $sEncryptionKey, $sInitializationVector);
$sEncryptedString = base64_encode(mcrypt_generic($rMcrypt, $sDataToEncrypt));

echo "Data Encrypted: $sEncryptedString\n";
$sDecryptedString = trim(mdecrypt_generic($rMcrypt, base64_decode($sEncryptedString)));

echo "Data Decrypted: $sDecryptedString\n";
mcrypt_generic_deinit($rMcrypt);
mcrypt_module_close($rMcrypt);

$sDecryptedString2 = openssl_decrypt(base64_decode($sEncryptedString), 'des-ede3', $sEncryptionKey, 0, ''); //this returns false.
echo "Data Decrypted (open SSL): $sDecryptedString2\n";

$sDecryptedString2 = openssl_decrypt(base64_decode($sEncryptedString), 'des-ede3', $sEncryptionKey, 0, $sInitializationVector); //Warning: openssl_decrypt(): IV passed is 8 bytes long which is longer than the 0 expected by selected cipher, truncating
?>

程序的输出显示:

Data to be Encrypted: Foo bar
Data Encrypted: 5Mraf9swmaI=
Data Decrypted: Foo bar
Data Decrypted (open SSL): 

Warning: openssl_decrypt(): IV passed is 8 bytes long which is longer than the 0 expected by selected cipher, truncating in /usr/local/www/appcluster01.ezmax.ca/pub/web/test/ian/test.cmd on line 31

我刚刚意识到我错误地使用了 openssl_decrypt。

更改为这个工作正常:

$sDecryptedString2 = openssl_decrypt(base64_decode($sEncryptedString), 'des-ede3', $sEncryptionKey, OPENSSL_ZERO_PADDING | OPENSSL_RAW_DATA, '');

我希望有一天它会帮助某人。

谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM