PHP中加密解密函数与DES加密解密
我了解中的php加密与解密方法有很多的,有常用的encrypt与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;
- }
使用如下所示:
- $str='作者:www.phpfensi.com';
- $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加密解密函数,代码如下:
- <?php
- class DES
- {
- var $key;
- var $iv;
-
- function DES( $key, $iv=0 ) {
-
- $this->key = $key;
- if( $iv == 0 ) {
- $this->iv = $key;
- } else {
- $this->iv = $iv;
- }
- }
-
- 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,代码如下:
-
-
-
- function args_encode($data) {
- if(is_array($data)) {
- $string = http_build_query($data);
- return base64_encode($string);
- } else {
- return false;
- }
- }
-
-
-
-
-
- function getargs() {
- $string = base64_decode($_GET['args']);
- parse_str($string,$g);
- return $g;
- }