在php7.1+以后,便不再支持php的mcrypt扩展,这里整理一套微信小程序端的加解密替换方案。当然自主编译安装mcrypt扩展也可以,这里不作详细说明。
原加密解密方法:
//获得16位随机字符串,填充到明文之前
$random = $this->getRandomStr();
$text = $random . pack(“N”, strlen($text)) . $text . $appid;
$iv = substr($this->key, 0, 16);
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, ”, MCRYPT_MODE_CBC, ”);
//使用自定义的填充方式对明文进行补位填充
$pkc_encoder = new PKCS7Encoder;
$text = $pkc_encoder->encode($text);
mcrypt_generic_init($module, $this->key, $iv);
//加密
$encrypted = mcrypt_generic($module, $text);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
原解密方法:
$ciphertext_dec = base64_decode($encrypted);
$iv = substr($this->key, 0, 16);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, ”, MCRYPT_MODE_CBC, ”);
mcrypt_generic_init($module, $this->key, $iv);
//解密
$decrypted = mdecrypt_generic($module, $ciphertext_dec);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
使用openssl替代后的加密方法:
//获得16位随机字符串,填充到明文之前
$random = $this->getRandomStr();
$text = $random . pack(“N”, strlen($text)) . $text . $appid;
$iv = substr($this->key, 0, 16);
$encrypted = openssl_encrypt($text, ‘AES-256-CBC’, $this->key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv);
解密方法:
$ciphertext_dec = base64_decode($encrypted); $iv = substr($this->key, 0, 16); $decrypted = openssl_decrypt($ciphertext_dec, ‘AES-256-CBC’, $this->key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv);