php中3des加密的结果与.Net/java不同的帖子与话题实在是太多了
,我前不久也在倒腾这些
,不过今天已经搞定了,完全与.net中的兼容
01.<?php
02.classCrypt3Des
03.{
04.private$key="";
05.private$iv="";
06./**
07.*构造,传递二个已经进行base64_encode的KEY与IV
08.*
09.*@paramstring$key 10.*@paramstring$iv 11.*/
12.function__construct($key,$iv)
13.{
14.if(empty($key)||empty($iv)){
15.echo'keyandivisnotvalid';
16.exit();
17.}
18.$this->key=$key;
19.$this->iv=$iv;
20.}
21./**
22.*加密
23.*@param<type>$value 24.*@return<type>
25.*/
26.publicfunctionencrypt($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.publicfunctiondecrypt($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.privatefunctionPaddingPKCS7($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.privatefunctionUnPaddingPKCS7($text)
63.{
64.$pad=ord($text{strlen($text)-1});
65.if($pad>strlen($text)){
66.returnfalse;
67.}
68.if(strspn($text,chr($pad),strlen($text)-$pad)!=$pad){
69.returnfalse;
70.}
71.returnsubstr($text,0,-1*$pad);
72.}
73.}
74.?>