您的位置:首页 > 编程语言 > PHP开发

使用PHP7.1的openssl加解密AES-128-CBC,与7.0之前的版本匹配

2017-12-20 14:53 1206 查看
因为老版本与线上环境的mcrypt不兼容,在php7.1上使用会报错,官网也说了:Warning

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

这里贴上解决办法。

先上7.0之前的代码:

<?php
class Security
{
private static $iv = "1234567890123456";

public static function encrypt($input, $key) {
$key = base64_decode($key);
$localIV = Security::$iv;
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
mcrypt_generic_init($module, $key, $localIV);
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$input = Security::pkcs5_pad($input, $size);
$data = mcrypt_generic($module, $input);

mcrypt_generic_deinit($module);
mcrypt_module_close($module);
$data = base64_encode($data);
return $data;
}

private static function pkcs5_pad ($text, $blocksize) {
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}

public static function decrypt($sStr, $key) {
$key = base64_decode($key);
$localIV = Security::$iv;
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
mcrypt_generic_init($module, $key, $localIV);
$encryptedData = base64_decode($sStr);
$encryptedData = mdecrypt_generic($module, $encryptedData);

$dec_s = strlen($encryptedData);
$padding = ord($encryptedData[$dec_s-1]);
$decrypted = substr($encryptedData, 0, -$padding);

mcrypt_generic_deinit($module);
mcrypt_module_close($module);
if(!$decrypted){
throw new Exception("Decrypt Error,Please Check SecretKey");
}
return $decrypted;
}
}

$key = 'abcdefghijklmn'; // 随意

echo '用来加密的串:------------------------';
echo $str = '中文数字123字母ABC符号!@#$%^&*()';

echo '<br />用7.1之前的mcrypt加密:------------------------';
echo $strEncode = Security::encrypt('中文数字123字母ABC符号!@#$%^&*()', $key);

echo '<br />用7.1之前的mcrypt解密:------------------------';
echo Security::decrypt($strEncode, $key);


然后是7.1的:

$iv = '1234567890123456'; // 16位
echo '<br />用PHP 7.1的openssl加密:------------------------';
echo base64_encode(openssl_encrypt($str, 'aes-128-cbc', base64_decode($key), true, $iv));

echo '<br />用PHP 7.1的openssl解密:------------------------';
echo openssl_decrypt(base64_decode($strEncode), 'aes-128-cbc', base64_decode($key), true, $iv);


输出结果:

用来加密的串:--------中文数字123字母ABC符号!@#$%^&*()
用7.1之前的mcrypt加密:--------sfuG4bHFUPdBmmGAB14YYotuJtDPdDsG4YWnazDvDtmMlK8jr0gcWvXgGFW+t9fu
用7.1之前的mcrypt解密:--------中文数字123字母ABC符号!@#$%^&*()
用PHP 7.1的openssl加密:--------sfuG4bHFUPdBmmGAB14YYotuJtDPdDsG4YWnazDvDtmMlK8jr0gcWvXgGFW+t9fu
用PHP 7.1的openssl解密:--------中文数字123字母ABC符号!@#$%^&*()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: