今天是: 收藏本站 设为主页
网站首页 >  技术专栏  >  php  > 

3des加密解密(php版本)

日期:2011-07-15  点击率:2336


<?php
class Crypt3Des
{
public $key = "";
public $iv = "12345678";
function Crypt3Des($key) {
$this->key = $key;
}
//加密
public function encrypt($input)
{
$size = mcrypt_get_block_size('tripledes', 'cbc');
$input = $this->pkcs5_pad($input, $size); //pkcs5填充方式

$td = mcrypt_module_open( MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
//使用MCRYPT_3DES算法,cbc模式
mcrypt_generic_init($td, $this->key, $this->iv);
//初始处理
$data = mcrypt_generic($td, $input);
//加密
mcrypt_generic_deinit($td);
//结束
mcrypt_module_close($td);
//$data = $this->removeBR(base64_encode($data));
$data = $this->removeBR($data);
return bin2hex($data);
}

//解密
public function decrypt($encrypted)
{

$encrypted = pack('H*', $encrypted);

$td = mcrypt_module_open( MCRYPT_3DES,'',MCRYPT_MODE_CBC,'');
//使用MCRYPT_3DES算法,cbc模式
mcrypt_generic_init($td, $this->key, $this->iv);
//初始处理
$decrypted = mdecrypt_generic($td, $encrypted);
//解密
mcrypt_generic_deinit($td);
//结束
mcrypt_module_close($td);
$decrypted = $this->pkcs5_unpad($decrypted); //pkcs5填充方式
return $decrypted;
}

//删除回车和换行
public function removeBR( $str )
{
$len = strlen( $str );
$newstr = "";
$str = str_split($str);
for ($i = 0; $i < $len; $i++ )
{
if ($str[$i] != '\n' and $str[$i] != '\r')
{
$newstr .= $str[$i];
}
}

return $newstr;
}

public function pkcs5_pad($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}

public 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);
}

}



//test
$input = "duddfdkkkewwer";
$crypt = new Crypt3Des("123456");
echo "Encode:".$crypt->encrypt($input)."<br/>";
echo "Decode:".$crypt->decrypt($crypt->encrypt($input));
?>



下一篇:MySQL日期时间函数大全   上一篇:Ubuntu Server LTS 10.04 中文乱码解决办法