php7 替换 mcrypt_decrypt,mcrypt_decrypt
openssl_encrypt 函数参数备注
openssl_encrypt ( string $data , string $method , string $key [, int $options = 0 [, string KaTeX parse error: Expected 'EOF', got '&' at position 19: …= "" [, string &̲tag = NULL [, string $aad = “” [, int $tag_length = 16 ]]]]] ) : string
$data 加密前参数,字符串类型
$method 方法
如果是 des 加密,解密 使用 openssl_get_cipher_methods() 获取
$key 密钥
$options 数据格式选项(可选)【选项有:】
0
OPENSSL_RAW_DATA=1
OPENSSL_ZERO_PADDING=2
OPENSSL_NO_PADDING=3
$iv 非 NULL 的初始化向量。长度根据加解密方法来定 ecb 不填写向量
$tag 使用 AEAD 密码模式(GCM 或 CCM)时传引用的验证标签。
$add 附加数据
$tag_length 验证tag 的长度 GCM 或 CCM 的 长度为4-16位
mcrypt_encrypt 使用 openssl_encrypt 替换
mcrypt_decrypt 使用 openssl_decrypt 替换
mcrypt 相关函数实现 aes/ecb 模式
//加密主函数
//mcrypt_get_block_size 获得加密算法的分组大小 mcrypt_module_open 算法名称
public static function encrypt($input, $key) {
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$input = Aesmodel::pkcs5_pad($input, $size);
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$data = mcrypt_generic($td, $input);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$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);
}
/**
* 十六进制转字符串
* 16进制的转为2进制字符串
* @param 十六进制 $hex
* @return string
*/
function hexToStr($hex)
{
$string="";
for($i=0;$i<strlen($hex)-1;$i+=2)
$string.=chr(hexdec($hex[$i].$hex[$i+1]));
return $string;
}
/**
* 字符串转十六进制
* @param string $string
* @return string
*/
function strToHex($string)
{
$hex="";
$tmp="";
for($i=0;$i<strlen($string);$i++)
{
$tmp = dechex(ord($string[$i]));
$hex.= strlen($tmp) == 1 ? "0".$tmp : $tmp;
}
$hex=strtoupper($hex);
return $hex;
}
//解密
public static function decrypt($sStr, $sKey) {
$decrypted= mcrypt_decrypt(MCRYPT_RIJNDAEL_128,$sKey,base64_decode($sStr),MCRYPT_MODE_ECB);
$dec_s = strlen($decrypted);
$padding = ord($decrypted[$dec_s-1]);
$decrypted = substr($decrypted, 0, -$padding);
return $decrypted;
}
openssl 相关函数实现加密解密
//加密 输出结果根据自己需求来定,此处展示输出为16进制
$data = openssl_encrypt($data, 'aes-128-ecb', base64_decode($this->key), OPENSSL_RAW_DATA);
$res_en = strToHex($data);
return $res_en;
//解密
$string = hexToStr($sStr);
$decrypted = openssl_decrypt($string, 'aes-128-ecb', base64_decode($this->key), OPENSSL_RAW_DATA);
return $decrypted;