php 7.1 openssl_decrypt代替 mcrypt_module_open方法
解决方案
经过调试发现php版本由原来的7.0升到了7.1。
mcrypt_module_open()函数在7.1中被贬低,将在7.2中被移除,
要用openssl_decrypt()函数代替
明文加密
原代码
$random = $this->getRandomStr();
$text = $random . pack("N", strlen($text)) . $text . $appid;
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
$iv = substr($this->key, 0, 16);
$pkc_encoder = new PKCS7Encoder;
$text = $pkc_encoder->encode($text);
mcrypt_generic_init($module, $this->key, $iv);
$encrypted = mcrypt_generic($module, $text);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
修改为
$random = $this->getRandomStr();
$text = $random . pack("N", strlen($text)) . $text . $appid;
$iv = substr($this->key, 0, 16);
$pkc_encoder = new PKCS7Encoder;
$text = $pkc_encoder->encode($text);
$encrypted = openssl_encrypt($text, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv);
明文解密
原代码
$ciphertext_dec = base64_decode($encrypted);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
$iv = substr($this->key, 0, 16);
mcrypt_generic_init($module, $this->key, $iv);
$decrypted = mdecrypt_generic($module, $ciphertext_dec);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
修改为
$ciphertext_dec = base64_decode($encrypted);
$iv = substr($this->key, 0, 16);
$decrypted = openssl_decrypt($ciphertext_dec, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv);
随机生成16位字符串
/**
* 随机生成16位字符串
* @return string 生成的字符串
*/
function getRandomStr()
{
$str = "";
$str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
$max = strlen($str_pol) - 1;
for ($i = 0; $i < 16; $i++) {
$str .= $str_pol[mt_rand(0, $max)];
}
return $str;
}
随着PHP版本升级到7.1,mcrypt_module_open函数被废弃,推荐使用openssl_decrypt进行加密解密操作。本文介绍了如何将原有代码中的mcrypt_module_open转换为openssl_decrypt的实现,包括明文加密和解密的示例代码,以及如何生成16位随机字符串。
947

被折叠的 条评论
为什么被折叠?



