標籤:des blog http io ar sp for on 資料
原文:php中des加密解密 匹配C#des加密解密 對稱式加密
網上找來的 php des加密解密 完全符合上一篇C# 字串加密解密函數 可以用於C#和php通訊 對資料進行加密,其中$key 是加密金鑰,$iv 是位移量,預設位移量和加密密匙是一樣的,<?phpclass DES{ var $key; var $iv; //位移量 function DES( $key, $iv=0) { //key長度8例如:1234abcd $this->key = $key; if( $iv == 0 ) { $this->iv = $key; //預設以$key 作為 iv } 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 < strlen ( $hexData ); $i += 2) { $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 = "xublog";$key = ‘12345678‘;$crypt = new DES($key);$mstr = $crypt->encrypt($str);echo "[ $str ]加密:[ $mstr]<br>";$str = $crypt->decrypt($mstr);echo "[ $mstr ]解密:[ $str]<br>";
php中des加密解密 匹配C#des加密解密 對稱式加密