我已将我的php版本更新到7.1。
我以前使用mcrypt加密数据的函数现在被弃用了。
那么,如何在不回退到旧版本的php的情况下解密数据呢?
以下是我使用的代码:
public function encrypt($plaintext) {
$ivSize = mcrypt_get_iv_size(self::CIPHER, self::MODE);
$iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
$ciphertext = mcrypt_encrypt(self::CIPHER, $this->key, $plaintext, self::MODE, $iv);
return base64_encode($iv.$ciphertext);
}
public function decrypt($ciphertext) {
$ciphertext = base64_decode($ciphertext);
$ivSize = mcrypt_get_iv_size(self::CIPHER, self::MODE);
if (strlen($ciphertext) < $ivSize) {
throw new Exception('Missing initialization vector');
}
$iv = substr($ciphertext, 0, $ivSize);
$ciphertext = substr($ciphertext, $ivSize);
$plaintext = mcrypt_decrypt(self::CIPHER, $this->key, $ciphertext, self::MODE, $iv);
return rtrim($plaintext, "\0");
}
使用常量:
const CIPHER = MCRYPT_RIJNDAEL_128; // Rijndael-128 is AES
const MODE = MCRYPT_MODE_CBC;
我看到建议使用OpenSSL,从现在开始我会使用它。但是如何使用这种方法解密旧数据呢?
谢谢。
编辑: 我知道我可以使用OpenSSL作为替代方案。 这就是我现在正在做的内容。 但我需要解密我的旧内容中的加密代码。
*@symcbean的编辑请求
尝试使用以下方式使用OpenSSL进行解密:
public function decrypt($ciphertext) {
$ciphertext = base64_decode($ciphertext);
if (!function_exists("openssl_decrypt")) {
throw new Exception("aesDecrypt needs openssl php module.");
}
$key = $this->key;
$method = 'AES-256-CBC';
$ivSize = openssl_cipher_iv_length($method);
$iv = substr($ciphertext,0,$ivSize);
$data = substr($ciphertext,$ivSize);
$clear = openssl_decrypt ($data, $method, $key, 'OPENSSL_RAW_DATA'|'OPENSSL_ZERO_PADDING', $iv);
return $clear;
}
MCRYPT_RIJNDAEL_128
,那么您的$method
应该是"AES-128-CBC"
。另外,openssl_decrypt
标志是常量,而不是字符串,因此请删除引号,例如OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING
。 - Joe