php7.3->使用OpenSSL来代替Mcrypt加解密的function制作方法

 

但因为php7.1之取消了Mcrypt加密套件,所以原本的方法就不能使用了,必须改用OpenSSL来加密资料,以下为吧Mcrypt加密function替换为OpenSSL加密function的方法,只需要更动function内容即可,在模组中引入的function及传入值参都不须更动。

原本的Mcrypt加密function

//AES 资料加密
function encryptdecode($var="",$types="",$key=""){
//製作SHA384-KEY
$hash_string = $key;
$hash = hash('SHA384', $hash_string, true);
$app_cc_aes_key = substr($hash, 0, 32);
$app_cc_aes_iv = substr($hash, 32, 16);
//加密
if($types==encrypt){
$data = $var;
$padding = 16 - (strlen($data) % 16);
$data .= str_repeat(chr($padding), $padding);
$encrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $app_cc_aes_key, $data, MCRYPT_MODE_CBC, $app_cc_aes_iv);
$encrypt_text = base64_encode($encrypt);
$returnvar=$encrypt_text;
}
//解密
if($types==decryption){
$encrypt =base64_decode($var);
$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $app_cc_aes_key, $encrypt, MCRYPT_MODE_CBC, $app_cc_aes_iv);
$padding = ord($data[strlen($data) - 1]);
$decrypt_text = substr($data, 0, -$padding);
$returnvar=$decrypt_text;
}
return $returnvar;
}

直接替换成以下的OpenSSL加密function

//openssl资料加密
function encryptdecode($var="",$types="",$key=""){

//加密
if($types=="encrypt"){
$id=serialize($var);//加密资料
$data['iv']=base64_encode(substr('fdakinel;injajdji',0,16));
$data['value']=openssl_encrypt($id, 'AES-256-CBC',$key,0,base64_decode($data['iv']));
$encrypt=base64_encode(json_encode($data));
$returnvar=$encrypt;
}
//解密
if($types=="decryption"){
$encrypt=$var; //解密资料
$encrypt = json_decode(base64_decode($encrypt), true);
$iv = base64_decode($encrypt['iv']);
$decrypt = openssl_decrypt($encrypt['value'], 'AES-256-CBC', $key, 0, $iv);
$id = unserialize($decrypt);
if($id){
return $id;
}else{
return 0;
}
}
return $returnvar;
}

使用方法跟原本的Mcrypt加密function一样

$var为加密解密资料传入值
$key为加密解密key值(必须一样)
$types为选择function加密或解密

//资料加密
echo encryptdecode($var="Good day, 201852",$types="encrypt",$key=test123);

输出加密字串:dO7N6jPnOhfWpBHnefP9w0GHVrnvpkZQGmkXcCnxXFg=

//资料解密
echo encryptdecode($var="dO7N6jPnOhfWpBHnefP9w0GHVrnvpkZQGmkXcCnxXFg=",$types="decryption",$key=test123);

输出解密字串:Good day, 201852

参与评论