background image

php 中 3des 加密代码(完全与.net 中的兼容)

php 中 3des 加密的结果与.Net/java 不同的帖子与话题实在是太多了,我前不久也在倒腾这
些,不过今天已经搞定了

,完全与.net 中的兼容

代码如下

:

 
<?php 

class

 Crypt3Des 

private

 

$key

 = ""; 

private

 

$iv

 = ""; 

/** 
* 构造,传递二个已经进行 base64_encode 的 KEY 与 IV 

* @param string $key 
* @param string $iv 
*/

 

function

 __construct (

$key

$iv

if

 (

empty

(

$key

) || 

empty

(

$iv

)) { 

echo

 'key and iv is not valid'; 

exit

(); 

$this

->key = 

$key

$this

->iv = 

$iv

/** 
*加密 
* @param <type> $value 
* @return <type> 
*/

 

public

 

function

 encrypt (

$value

$td

 = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, ''); 

$iv

 = 

base64_decode

(

$this

->iv); 

$value

 = 

$this

->PaddingPKCS7(

$value

); 

$key

 = 

base64_decode

(

$this

->key); 

mcrypt_generic_init(

$td

$key

$iv

); 

$ret

 = 

base64_encode

(mcrypt_generic(

$td

$value

)); 

mcrypt_generic_deinit(

$td

); 

mcrypt_module_close(

$td

);