首页 > 解决方案 > PHP 使用 openssl 解密数据(使用 mcrypt 加密)

问题描述

我有一个数据库,其中包含使用 php Mcrypt 库加密的 3DES (ECB) 加密数据。由于不推荐使用 Mcrypt,我需要切换到 OpenSSL 来解密它。所有数据将使用 xchacha20-poly1305-ietf 重新加密。

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

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

我开始怀疑问题出在使用 8 字节 IV 的 mcrypt 库上,而打开 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

标签: phpopensslmcrypt3desecb

解决方案


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

更改为此工作正常:

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

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

谢谢


推荐阅读