本文執行個體講述了PHP中加密解密函數與DES加密解密的應用,分享給大家供大家參考。具體如下:
例子,php加密解密的例子
加密函數:
/**功能:對字串進行加密處理*參數一:需要加密的內容*參數二:密鑰*/function passport_encrypt($str,$key){ //加密函數 srand((double)microtime() * 1000000); $encrypt_key=md5(rand(0, 32000)); $ctr=0; $tmp=''; for($i=0;$i<strlen($str);$i++){ $ctr=$ctr==strlen($encrypt_key)?0:$ctr; $tmp.=$encrypt_key[$ctr].($str[$i] ^ $encrypt_key[$ctr++]); } return base64_encode(passport_key($tmp,$key));}
解密代碼如下:
/**功能:對字串進行解密處理*參數一:需要解密的密文*參數二:密鑰*/function passport_decrypt($str,$key){ //解密函數 $str=passport_key(base64_decode($str),$key); $tmp=''; for($i=0;$i<strlen($str);$i++){ $md5=$str[$i]; $tmp.=$str[++$i] ^ $md5; } return $tmp;}
輔助函數:
/**輔助函數*/function passport_key($str,$encrypt_key){ $encrypt_key=md5($encrypt_key); $ctr=0; $tmp=''; for($i=0;$i<strlen($str);$i++){ $ctr=$ctr==strlen($encrypt_key)?0:$ctr; $tmp.=$str[$i] ^ $encrypt_key[$ctr++]; } return $tmp;}
使用如下所示
$key='123456';$encrypt=passport_encrypt($str,$key);$decrypt=passport_decrypt($encrypt,$key);echo '原文:',$str."<br><hr>";echo '密文:',$encrypt."<br><hr>";echo '譯文:',$decrypt."<br><hr>";
DES加密解密函數具體代碼如下:
<?phpclass 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 < 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 = '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;}
希望本文所述對大家的PHP程式設計有所協助。