升级 PHP7.1 后 openssl 解密 mcrypt AES 数据不兼容问题的处理方法

正文开始

旧版代码



$aesKey=base64_decode('pEJ0hDyJ8NUJBZijzR0T8DjP+W/fCaKwsB9tXbnSQSA='); $aesIV= base64_decode('BuqTZn/rPWQ3eo/b5EP2xw=='); $str = 'abc123'; $CIPHER = 'rijndael-128'; $mode = 'cbc'; print base64_encode(mcrypt_encrypt($CIPHER, $aesKey, $str, $mode, $aesIV));

输出结果:9RWAFwihFNQMa/wp24x0vw==

php7+ 新版代码


$aesKey=base64_decode('pEJ0hDyJ8NUJBZijzR0T8DjP+W/fCaKwsB9tXbnSQSA='); $aesIV= base64_decode('BuqTZn/rPWQ3eo/b5EP2xw=='); $str = 'abc123'; $__aesEncode = function($data, $privateKey, $iv=''){ if (strlen($data) % 16) { $data = str_pad($data,strlen($data) + 16 - strlen($data) % 16, "\0"); } $encrypted= openssl_encrypt($data, 'AES-256-CBC',$privateKey,OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING,$iv); return base64_encode(($encrypted)); }; $str1 = $__aesEncode($str, $aesKey, $aesIV); print_r($str1); //新版解密: public function decode( $key,$iv, $str ){ $str = openssl_decrypt($str, 'AES-256-CBC', $key, OPENSSL_ZERO_PADDING, $iv); $str = rtrim($str, "\0"); return $str; }

输出结果:9RWAFwihFNQMa/wp24x0vw==

正文结束

PHP接口(interface)和抽象类(abstract) php 实现阿里云函数计算FC 打包oss的文件夹