php5.x バージョンでは、php 拡張子 php_mcrypt を追加します。
rree
.net バージョン
1 class STD3Des 2 { 3 private $key = ""; 4 private $iv = ""; 5 6 /** 7 * 构造,传递二个已经进行base64_encode的KEY与IV 8 * 9 * @param string $key10 * @param string $iv11 */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> $value25 * @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> $value43 * @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 }78 79 80 //使用81 include('STD3Des.class.php');82 $key='abcdefgh';83 $iv='abcdefgh';84 $msg='test string';85 $des=new STD3Des(base64_encode($key),base64_encode($iv));86 $rs1=$des->encrypt($msg);87 echo $rs1.'<br />';88 $rs2=$des->decrypt($rs1);89 echo $rs2;