PHP中openssl加密函数应用,openssl_encrypt加密openssl_decrypt解密各种算法应用自定义方法封装支持各种加密算法,支持php5,php6,php7,php8
示例:
$key = 'zhlcms01'; // 加密key(自定义)
$str = '314314314'; // 加密字符串(自定义)
$m = '5'; // 加密方式(openssl_get_cipher_methods数组索引,也可以直接传加密方式比如:AES-128-CBC)
$str = sys_encrypt($str, $key, $m); // 字符串加密
echo $str; // 输出加密后的字符串
echo '<br>';
$str = sys_decrypt($str, $key, $m); // 字符串解密
echo $str; // 输出解密后的字符串
封装的方法:
/**
* Notes: 字符串-加密
* Desc: 兼容字符串特殊字符
*/
function sys_encrypt($string, $key, $method = '0')
{
if(is_numeric($method)){
$methods = openssl_get_cipher_methods();
$method = $methods[$method];
}
$ivlen = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($ivlen);
$string = openssl_encrypt($string, $method, $key, true, $iv); // OPENSSL_RAW_DATA
$string = base64_encode($iv.$string);
return rtrim(strtr($string, '+/', '-_'), '=');
}
/**
* Notes: 字符串-解密
* Desc: 兼容字符串特殊字符
*/
function sys_decrypt($string, $key, $method = '0')
{
if(is_numeric($method)){
$methods = openssl_get_cipher_methods();
$method = $methods[$method];
}
$string = str_pad(strtr($string, '-_', '+/'), strlen($string) % 4, '=', STR_PAD_RIGHT);
$string = base64_decode($string);
$ivlen = openssl_cipher_iv_length($method);
$iv = substr($string, 0, $ivlen);
$string = substr($string, $ivlen);
$string = openssl_decrypt($string, $method, $key, true, $iv);
return $string;
}