-
class Bdes extends CBase {
-
private $key; //密码
-
private $iv; //iv
-
private $mcrypt;
-
private $blockSize;
-
<span id="more-201"></span> /**
-
*
-
* @author 肖江
-
* @param $key
-
* @param $iv
-
* @return unknown_type
-
*/
-
function __construct($key,$iv) {
-
$this->key=$this->hexstr($key);
-
$this->iv=$this->toKey($iv);
-
$encodeType = MCRYPT_TripleDES;
-
$mod = MCRYPT_MODE_CBC;
-
////////////////////////////////////3des ecb/pkcs5 加密/////////////////
-
$this->mcrypt = mcrypt_module_open($encodeType, ”, $mod, ”);
-
if($this->mcrypt == false) {
-
$this->error(‘加密解密模块打开错误,请安装相关组件’,110011);
-
}
-
}
-
/**
-
*
-
* @author 肖江
-
* @return unknown_type
-
*/
-
function __destruct() {
-
mcrypt_generic_deinit($this->mcrypt);
-
mcrypt_module_close($this->mcrypt);
-
}
-
/**
-
*
-
* @author 肖江
-
* @param $data
-
* @return unknown_type
-
*/
-
function desEncode($data) {
-
$encodeType = MCRYPT_TripleDES;
-
$ks = mcrypt_enc_get_key_size($this->mcrypt);
-
$key = substr($this->key, 0, $ks);
-
-
if(mcrypt_generic_init($this->mcrypt, $key, $this->iv) < 0)
-
{
-
mcrypt_module_close($this->mcrypt);
-
$this->error(‘加密解密模块执行错误’,110012);
-
}
-
$this->blockSize = mcrypt_module_get_algo_block_size ($encodeType);
-
$tmpLen = $this->blockSize – strlen($data)% $this->blockSize;
-
for($i = 0; $i < $tmpLen; $i++) {
-
$data .= pack("h", $tmpLen);
-
}
-
-
$encodeStr = mcrypt_generic($this->mcrypt, $data);
-
return $this->strhex($encodeStr);
-
}
-
//DES 解密
-
/**
-
*
-
* @author 肖江
-
* @param $data
-
* @return unknown_type
-
*/
-
function desDecode($data)
-
{
-
$ks = mcrypt_enc_get_key_size($this->mcrypt);
-
$key = substr($this->key, 0, $ks);
-
-
if(mcrypt_generic_init($this->mcrypt, $key, $this->iv) < 0)
-
{
-
mcrypt_module_close($this->mcrypt);
-
$this->error(‘加密解密模块执行错误’,110012);
-
}
-
$data=$this->hexstr($data);
-
$decodeStr = mdecrypt_generic($this->mcrypt, $data);
-
//去掉pkcs5填充
-
$strLen = strlen($decodeStr);
-
$theLastPosChar = substr($decodeStr, -1);
-
$theFill = hexdec(bin2hex($theLastPosChar));
-
$decodeStr = substr($decodeStr, 0, $strLen – $theFill);
-
return $decodeStr;
-
}
-
/**
-
*
-
* @author 肖江
-
* @param $var
-
* @return unknown_type
-
*/
-
function toKey($var) {
-
$re=”;
-
foreach($var as $per) {
-
$re=$re.chr($per);
-
}
-
return $re;
-
}
-
/**
-
*
-
* @author 肖江
-
* @param $string
-
* @return unknown_type
-
*/
-
function strHex($string) {
-
$hex="";
-
for ($i=0;$i<strlen($string);$i++)
-
$hex.=(strlen(dechex(ord($string[$i])))<2)? "0".dechex(ord($string[$i])): dechex(ord($string[$i]));
-
return $hex;
-
}
-
/**
-
*
-
* @author 肖江
-
* @param $hex
-
* @return unknown_type
-
*/
-
function hexstr($hex)
-
{
-
$string="";
-
for ($i=0;$i<strlen($hex)-1;$i+=2)
-
$string.=chr(hexdec($hex[$i].$hex[$i+1]));
-
return $string;
-
}
-
}
PKCS5填充 PHP DES算法库
- No comments yet.
- No trackbacks yet.
Recent Comments