mcrypt加密解密弃用后用openssl解决

mcrypt加密

try {
   //获得16位随机字符串,填充到明文之前
   $random = $this->getRandomStr();
   $text = $random . pack("N", strlen($text)) . $text . $appid;
   // 网络字节序
   $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
   $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
   $iv = substr($this->key, 0, 16);
   //使用自定义的填充方式对明文进行补位填充
   $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);

   //print(base64_encode($encrypted));
   //使用BASE64对加密后的字符串进行编码
   return array(ErrorCode::$OK, base64_encode($encrypted));
} catch (Exception $e) {
   //print $e;
   return array(ErrorCode::$EncryptAESError, null);
}

mcrypt解密

try {
   //使用BASE64对需要解密的字符串进行解码
   $ciphertext_dec = base64_decode($encrypted);
   $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
   $iv = substr($this->key, 0, 16);
   mcrypt_generic_init($module, $this->key, $iv);

   //解密
   $decrypted = mdecrypt_generic($module, $ciphertext_dec);
   mcrypt_generic_deinit($module);
   mcrypt_module_close($module);
} catch (Exception $e) {
   return array(ErrorCode::$DecryptAESError, null);
}

改成一下方法用openssl即可解决

openssl_encrypt 加密

try {
   //获得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, $iv);
   return array(ErrorCode::$OK, base64_encode($encrypted));
} catch (Exception $e) {
   //print $e;
   return array(ErrorCode::$EncryptAESError, null);
}

openssl_decrypt 解密

try {
          $iv = substr($this->key, 0, 16);
          $decrypted = openssl_decrypt(base64_decode($encrypted), 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA,$iv);
} catch (Exception $e) {
   return array(ErrorCode::$DecryptAESError, null);
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值