网站首页 文章专栏 PHP加密算法,3DES对称加密

PHP加密算法,3DES对称加密

编辑时间:2018-04-19 14:59:34 作者:苹果 浏览量:452





    前言:传入两个自定义的key,调用encrypt($value)实现加密,调用decrypt($value)实现解密 $Crypt3DES = new Crypt3DES($key,$iv); $token = base64_encode($Crypt3DES->encrypt($value));


<?php

/**

 * 3Des加密解密算法

 * @DateTime:    2018-02-27 14:48:19

 * @Author:h

 */


class Crypt3DES {

private $key = "";

private $iv = "";


/**

* 构造,传递二个已经进行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 = base64_encode($key);

     $this->iv = base64_encode($iv);

}


/**

*加密

* @param <type> $value

* @return <type>

*/

public function encrypt($value) {

     $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');

     $iv = base64_decode($this->iv);

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

     $key = base64_decode($this->key);

     mcrypt_generic_init($td, $key, $iv);

     $ret = base64_encode(mcrypt_generic($td, $value));

     mcrypt_generic_deinit($td);

     mcrypt_module_close($td);

     return $ret;

}


/**

*解密

* @param <type> $value

* @return <type>

*/

public function decrypt($value) {

     $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');

     $iv = base64_decode($this->iv);

     $key = base64_decode($this->key);

     mcrypt_generic_init($td, $key, $iv);

     $ret = trim(mdecrypt_generic($td, base64_decode($value)));

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

     mcrypt_generic_deinit($td);

     mcrypt_module_close($td);

     return $ret;

}


private function PaddingPKCS7($data) {

     $block_size = mcrypt_get_block_size('tripledes', 'cbc');

     $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);

     }

}

?>



    出自:何冰华个人网站

    地址:http://www.hebinghua.com/

    转载请注明出处


来说两句吧
最新评论