class DES
{
var $key;
var $iv; //偏移量
function DES( $key, $iv=0 ) {
//key长度8例如:1234abcd
$this->key = $key;
if( $iv == 0 ) {
$this->iv = $key;
} else {
$this->iv = $iv; //mcrypt_create_iv ( mcrypt_get_block_size (MCRYPT_DES, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM );
}
}
function encrypt($str) {
//加密,返回大写十六进制字符串
$size = mcrypt_get_block_size ( MCRYPT_DES, MCRYPT_MODE_CBC );
$str = $this->pkcs5Pad ( $str, $size );
return strtoupper( bin2hex( mcrypt_cbc(MCRYPT_DES, $this->key, $str, MCRYPT_ENCRYPT, $this->iv ) ) );
}
function decrypt($str) {
//解密
$strBin = $this->hex2bin( strtolower( $str ) );
$str = mcrypt_cbc( MCRYPT_DES, $this->key, $strBin, MCRYPT_DECRYPT, $this->iv );
$str = $this->pkcs5Unpad( $str );
return $str;
}
function hex2bin($hexData) {
$binData = "";
for($i = 0; $i
$binData .= chr ( hexdec ( substr ( $hexData, $i, 2 ) ) );
}
return $binData;
}
function pkcs5Pad($text, $blocksize) {
$pad = $blocksize - (strlen ( $text ) % $blocksize);
return $text . str_repeat ( chr ( $pad ), $pad );
}
function pkcs5Unpad($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 );
}
}
?>
以下是测试结果:
代码如下:
$str = '12345678';
$key = '1234abcd';
$crypt = new DES($key);
$mstr = $crypt->encrypt($str);
$str = $crypt->decrypt($mstr);
echo $str.' '.$mstr;
例子2
代码如下:
代码如下:
/**
*加密需通过get方式在url中传递的参数
*/
function args_encode($data) {
if(is_array($data)) {
$string = http_build_query($data);
return base64_encode($string);
} else {
return false;
}
}
/**
*获取url中get方式传递的参数
*/
function getargs() {
$string = base64_decode($_GET['args']);
parse_str($string,$g);
return $g;
}
http://www.bkjia.com/PHPjc/896780.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/896780.htmlTechArticlePHP中加密解密函数与DES加密解密实例 例子,php加密解密的例子 加密函数: 代码如下: /* *功能:对字符串进行加密处理 *参数一:需要加密...