php教程自学网 - 轻松零基础学php视频教程
条幅广告
当前位置: 主页 > PHP7 >

PHP7.1 OpenSSL_encrypt 替换 Mcrypt_encrypt 的方法

时间:2018-08-22 19:14来源:未知 作者:admin 点击:
工具类: class DesEncrypt { private $key = ; private $iv = ; /** * 构造,传递二个已经进行base64_encode的KEY与IV * * @param string $key * @param string $iv */ function __construct ($key, $iv) { if (empty($key) || empty($iv))

工具类:

  class DesEncrypt {

  private $key = "";

  private $iv = "";

  /**

  * 构造,传递二个已经进行base64_encode的KEY与IV

  *

  * @param string $key

  * @param string $iv

  */

  function __construct ($key, $iv)

  {

  if (empty($key) || empty($iv)) {

  echo 'key and iv is not valid';

  exit();

  }

  $this->key = $key;

  $this->iv = $iv;

  }

  /**

  * @title 加密

  * @author gaowei

  * @date 2017/12/18

  * @param string $value 要传的参数

  * @ //OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING //AES-128-ECB|AES-256-CBC|BF-CBC

  * @return json

  * */

  public function encrypt ($value) {

  $value = $this->PaddingPKCS7($value);

  $key = $this->key;

  $iv = $this->iv;

  //AES-128-ECB|不能用 AES-256-CBC|16 AES-128-CBC|16 BF-CBC|8 aes-128-gcm|需要加$tag DES-EDE3-CBC|8

  $cipher = "DES-EDE3-CBC";

  if (in_array($cipher, openssl_get_cipher_methods())) {

  $result = openssl_encrypt($value, $cipher, $key, OPENSSL_SSLV23_PADDING, $iv);

  }

  return $result;

  }

  /**

  * @title 解密

  * @author gaowei

  * @date 2017/12/18

  * @param string $value 要传的参数

  * @return json

  * */

  public function decrypt ($value) {

  $key = $this->key;

  $iv = $this->iv;

  $decrypted = openssl_decrypt($value, 'DES-EDE3-CBC', $key, OPENSSL_SSLV23_PADDING, $iv);

  $ret = $this->UnPaddingPKCS7($decrypted);

  return $ret;

  }

  private function PaddingPKCS7 ($data) {

  $block_size = 8;

  $padding_char = $block_size - (strlen($data) % $block_size);

  $data .= str_repeat(chr($padding_char), $padding_char);

  return $data;

  }

  private function UnPaddingPKCS7($text) {

  $pad = ord($text{strlen($text) - 1});

  if ($pad > strlen($text)) {

  return false;

  }

  if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {

  return false;

  }

  return substr($text, 0, - 1 * $pad);

  }

  }

  使用方法:

  include "DesEncrypt.php";

  $str = '{"type":"test","user_id":"000"}';

  $des = new DesEncrypt("1234567890","01234567");

  echo $des->encrypt($str);

  echo "

  ";

  echo $des->decrypt("VsewcF6I94fHLZhrFYohB52GgASfdDeQJLZnr3C2AeE=");

(责任编辑:admin)
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
相关推荐