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.?>