免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1596 | 回复: 0

三重des加密 [复制链接]

论坛徽章:
0
发表于 2015-07-16 14:04 |显示全部楼层
  1. class STD3Des
  2. {
  3.     private $key = "";
  4.     private $iv = "";
  5.   
  6.     /**
  7.     * 构造,传递二个已经进行base64_encode的KEY与IV
  8.     *
  9.     * @param string $key
  10.     * @param string $iv
  11.     */
  12.     function __construct ($key, $iv)
  13.     {
  14.         if (empty($key) || empty($iv)) {
  15.             echo 'key and iv is not valid';
  16.             exit();
  17.         }
  18.         $this->key = $key;
  19.         $this->iv = $iv;
  20.     }
  21.   
  22.     /**
  23.     *加密
  24.     * @param <type> $value
  25.     * @return <type>
  26.     */
  27.     public function encrypt ($value)
  28.     {
  29.         $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
  30.         $iv = base64_decode($this->iv);
  31.         $value = $this->PaddingPKCS7($value);
  32.         $key = base64_decode($this->key);
  33.         mcrypt_generic_init($td, $key, $iv);
  34.         $ret = base64_encode(mcrypt_generic($td, $value));
  35.         mcrypt_generic_deinit($td);
  36.         mcrypt_module_close($td);
  37.         return $ret;
  38.     }
  39.   
  40.     /**
  41.     *解密
  42.     * @param <type> $value
  43.     * @return <type>
  44.     */
  45.     public function decrypt ($value)
  46.     {
  47.         $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
  48.         $iv = base64_decode($this->iv);
  49.         $key = base64_decode($this->key);
  50.         mcrypt_generic_init($td, $key, $iv);
  51.         $ret = trim(mdecrypt_generic($td, base64_decode($value)));
  52.         $ret = $this->UnPaddingPKCS7($ret);
  53.         mcrypt_generic_deinit($td);
  54.         mcrypt_module_close($td);
  55.         return $ret;
  56.     }
  57.   
  58.     private function PaddingPKCS7 ($data)
  59.     {
  60.         $block_size = mcrypt_get_block_size('tripledes', 'cbc');
  61.         $padding_char = $block_size - (strlen($data) % $block_size);
  62.         $data .= str_repeat(chr($padding_char), $padding_char);
  63.         return $data;
  64.     }
  65.   
  66.     private function UnPaddingPKCS7($text)
  67.     {
  68.         $pad = ord($text{strlen($text) - 1});
  69.         if ($pad > strlen($text)) {
  70.             return false;
  71.         }
  72.         if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
  73.             return false;
  74.         }
  75.         return substr($text, 0, - 1 * $pad);
  76.     }
  77. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP