php中3des加密(完全与.net中的兼容)
php中3des加密的结果与.Net/java不同的帖子与话题实在是太多了,我前不久也在倒腾这些,不过今天已经搞定了,完全与.net中的兼容 01.<?php 02.class Crypt3Des 03.{ 04.private $key = ""; 05.private $iv = ""; 06./** 07.* 构造,传递二个已经进行base64_encode的KEY与IV 08.* 09.* @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.* @param <type> $value 24.* @return <type> 25.*/ 26.public function encrypt ($value) 27.{ 28.$td = mcrypt_module_open(MCRYPT_3DES, '''', MCRYPT_MODE_CBC, ''''); 29.$iv = base64_decode($this->iv); 30.$value = $this->PaddingPKCS7($value); 31.$key = base64_decode($this->key); 32.mcrypt_generic_init($td, $key, $iv); 33.$ret = base64_encode(mcrypt_generic($td, $value)); 34.mcrypt_generic_deinit($td); 35.mcrypt_module_close($td); 36.return $ret; 37.} 38./** 39.*解密 40.* @param <type> $value 41.* @return <type> 42.*/ 43.public function decrypt ($value) 44.{ 45.$td = mcrypt_module_open(MCRYPT_3DES, '''', MCRYPT_MODE_CBC, ''''); 46.$iv = base64_decode($this->iv); 47.$key = base64_decode($this->key); 48.mcrypt_generic_init($td, $key, $iv); 49.$ret = trim(mdecrypt_generic($td, base64_decode($value))); 50.$ret = $this->UnPaddingPKCS7($ret); 51.mcrypt_generic_deinit($td); 52.mcrypt_module_close($td); 53.return $ret; 54.} 55.private function PaddingPKCS7 ($data) 56.{ 57.$block_size = mcrypt_get_block_size(''tripledes'', ''cbc''); 58.$padding_char = $block_size - (strlen($data) % $block_size); 59.$data .= str_repeat(chr($padding_char), $padding_char); 60.return $data; 61.} 62.private function UnPaddingPKCS7 ($text) 63.{ 64.$pad = ord($text{strlen($text) - 1}); 65.if ($pad > strlen($text)) { 66.return false; 67.} 68.if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) { 69.return false; 70.} 71.return substr($text, 0, - 1 * $pad); 72.} 73.} 74.?> |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |