问题描述
因此,随着时间的推移,mcrypt 将在 PHP 7.2 中出现.当然还有一个选择:openssl.
So as time moves on mcrypt will go in PHP 7.2. Of course there is an alternative: openssl.
我发现很难从 mcrypt 切换到 openssl,使用 AES 256 CBC 并保留 IV.我对密码学有点陌生,所以我并不是什么都知道,但我了解基础知识.
I find it difficult to switch from mcrypt to openssl, using AES 256 CBC and preserving IVs. I am sort of new to cryptography, so I don't really know everything, but I understand the basics.
假设我有以下代码
function encrypt($masterPassword, $data)
{
$keySize = mcrypt_get_key_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
$key = mb_substr(hash('SHA256', $masterPassword), 0, $keySize);
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_CBC, $iv);
return base64_encode($iv . $encrypted);
}
function decrypt($masterPassword, $base64)
{
$keySize = mcrypt_get_key_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$key = mb_substr(hash('SHA256', $masterPassword), 0, $keySize);
$data = base64_decode($base64);
$iv = substr($data, 0, $ivSize);
$encrypted = substr($data, $ivSize, strlen($data));
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, MCRYPT_MODE_CBC, $iv);
return trim($decrypted);
}
如何转换"此代码以使用由 mcrypt 插入的 openssl?
How can I "convert" this code to use openssl insted of mcrypt?
推荐答案
您无法转换它,因为 Rijndael-256 不是 AES-256,并且 OpenSSL 扩展不附带 Rijndael-256 支持.
AES-256 是具有 256 位(32 字节)密钥的 Rijndael-128.
You can't convert it, because Rijndael-256 is not AES-256, and the OpenSSL extension doesn't ship with Rijndael-256 support.
AES-256 is Rijndael-128 with a 256-bit (32-byte) key.
很遗憾,您必须重新加密所有数据.
Unfortunately, you'll have to re-encrypt all of your data.
此外,您当前使用的方案存在一些问题:
Also, the scheme you're currently using has some problems:
- 它缺乏身份验证(HMAC 是在 PHP 中最简单的方法)
- 它缺少适当的填充(mcrypt 填充零字节;您需要类似 PKCS#5 的填充),这是块模式加密安全所必需的.
- 它不是字节安全的(您使用的是
mb_substr()
)
好消息是 OpenSSL 会自动为你做 PKCS#5 填充,但你应该更进一步,使用像 defuse/php-encryption.
The good news is that OpenSSL will do PKCS#5 padding for you automatically, but you should go even further and use a solid encryption library like defuse/php-encryption.
这篇关于准备在 PHP 7.2 中删除 Mcrypt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!