代碼及使用說明:
<?php
/**
*PHP 識别 java 8位密鑰的加密和解密方式
*@desc 加密方式 通用
*/
class DES {
var $key;
var $iv; //偏移量
function DES($key) {
//key長度8例如:1234abcd
$this->key = $key;
}
//加密方式
function encrypt($str) {
$str = $this->pkcs5_pad($str);
$encode = mcrypt_encrypt(MCRYPT_DES, $this->key, $str, MCRYPT_MODE_ECB);
return bin2hex($encode);
}
//解密方式
function decrypt($str) {
$str = $this->hex2bin($str);
$str = mcrypt_decrypt(MCRYPT_DES, $this->key, $str, MCRYPT_MODE_ECB);
return $str;
}
//十六進制資料轉換成二進制資料流
function hex2bin($data) {
$len = strlen($data);
for($i=0;$i<$len;$i+=2) {
$newdata .= pack("C",hexdec(substr($data,$i,2)));
}
return $newdata;
}
function pkcs5_unpad($text)
{
$pad = ord($text{strlen($text)-1});
if ($pad > strlen($text)) return $text;
if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return $text;
return substr($text, 0, -1 * $pad);
}
//補位
function pkcs5_pad($text)
{
$len = strlen($text);
$mod = $len % 8;
$pad = 8 - $mod;
return $text.str_repeat(chr($pad),$pad);
}
}
?>
使用方式:
$key ='' 密鑰
$data = '123456'; 加密的字元串
$Des = new Des($key);
$encode = $Des->encrypt($data);//加密
$decode = $Des->decrypt($encode);//解密
echo $encode."<br/>";
echo $decode."<br/>";
朝朝暮暮.