PHP通用DES加密算法

与java通用的加密解密方法

代码如下
 
class Des_Crypt
{
private $key;

function __construct($key)
{
$this->key = $key;
}

function encrypt($string)
{
$size = mcrypt_get_block_size('des','ecb');
$string = mb_convert_encoding($string, 'GBK', 'UTF-8');
$string = $this->pkcs5_pad($string, $size);
$key = $this->key;
$td = mcrypt_module_open('des', '', 'ecb', '');
$iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
@mcrypt_generic_init($td, $key, $iv);
$data = mcrypt_generic($td, $string);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$data = base64_encode($data);
return $data;
}
function decrypt($string)
{
$string = base64_decode($string);
$key =$this->key;
$td = mcrypt_module_open('des','','ecb','');
//使用MCRYPT_DES算法,cbc模式
$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$ks = mcrypt_enc_get_key_size($td);
@mcrypt_generic_init($td, $key, $iv);
//初始处理
$decrypted = mdecrypt_generic($td, $string);
//解密
mcrypt_generic_deinit($td);
//结束
mcrypt_module_close($td);

$result = $this->pkcs5_unpad($decrypted);
$result = mb_convert_encoding($result, 'UTF-8', 'GBK');
return $result;
}
function pkcs5_pad ($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
function pkcs5_unpad($text)
{
$pad = ord($text{strlen($text)-1});
if ($pad > strlen($text))
{
return false;
}
if (strspn($text, chr($pad), strlen($text) - $pad) != $pad)
{
return false;
}
return substr($text, 0, -1 * $pad);
}
}
/*
For example:

$key = "!@#%test";
$string1 = "13808080808";
$string2 = "这是中文测试";
$des = new Des_Crypt($key);

$encryption = $des->encrypt($string2);
$decryption = $des->decrypt($encryption);

echo "原始值:".$decryption;
echo "<br />";
echo "加密值:".$encryption;
*/

 

 
 

php中的des加密解密函数简介

 
php中的des加密解密,这里来看两个函数,是关于php的des加密、解密的,这两个函数可以把数据加密成复杂的字符串,如果不解密的话是无法知道未加密前的内容的,可以用des加密实现密码的加密保存之类的操作,php的mde加密和MD5都是加密的好东西。 两个函数如下:
加密函数:encrypt
function encrypt($encrypt,$key=”") {
$iv = mcrypt_create_iv ( mcrypt_get_iv_size ( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB ), MCRYPT_RAND );
$passcrypt = mcrypt_encrypt ( MCRYPT_RIJNDAEL_256, $key, $encrypt, MCRYPT_MODE_ECB, $iv );
$encode = base64_encode ( $passcrypt );
return $encode;
}

 

解密函数:decrypt
function decrypt($decrypt,$key=”") {
$decoded = base64_decode ( $decrypt );
$iv = mcrypt_create_iv ( mcrypt_get_iv_size ( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB ), MCRYPT_RAND );
$decrypted = mcrypt_decrypt ( MCRYPT_RIJNDAEL_256, $key, $decoded, MCRYPT_MODE_ECB, $iv );
return $decrypted;
}

 

 
下面来看这两个函数的实例:
<?php
$new = encrypt(“wo shi old”,”111″);
$old = decrypt($new,”111″);
echo $new.”的明文是:”.”<br>”;
echo $old;
?>

 

 
运行的结果为: bnF+S42hS0BzXqMwPJJN82yBa4/DiYoYcTGmt0TotwY=的明文是:wo shi old
 
注:加密或解密时一定要注意$key的值,加密后要想解密就必须要知道$key的值,不然不能解出正确的明文。

您可能还喜欢...

发表评论