---
title: "三个超好用的PHP加密解密函数"
author: "yd514"
date: "2013-10-28T16:24:46Z"
tags: []
categories: ["编程语言"]
slug: "php"
draft: false
lastmod: "2013-10-28T16:24:46Z"
id: 1965708
url: "https://yd514.iteye.com/blog/1965708"
---

三个超好用的PHP加密解密函数,貌似是discuz里的…使用这些加密解密的原因是因为有时自己的URL地址被人获取以后想破解你里面传值的内容就必须知道你的key，没有key，他应该要破了一阵子才能知道你URL里面的内容吧。

将它们打包成一个文件就叫fun.php吧 

复制代码 代码如下:  
&lt;?php   
function passport\_encrypt($txt, $key) {   
srand((double)microtime() * 1000000);   
$encrypt\_key = md5(rand(0, 32000));   
$ctr = 0;   
$tmp = '';   
for($i = 0;$i &lt; strlen($txt); $i++) {   
$ctr = $ctr == strlen($encrypt\_key) ? 0 : $ctr;   
$tmp .= $encrypt\_key\[$ctr].($txt\[$i] ^ $encrypt\_key\[$ctr++]);   
}   
return base64\_encode(passport\_key($tmp, $key));   
} 

function passport\_decrypt($txt, $key) {   
$txt = passport\_key(base64\_decode($txt), $key);   
$tmp = '';   
for($i = 0;$i &lt; strlen($txt); $i++) {   
$md5 = $txt\[$i];   
$tmp .= $txt\[++$i] ^ $md5;   
}   
return $tmp;   
} 

function passport\_key($txt, $encrypt\_key) {   
$encrypt\_key = md5($encrypt\_key);   
$ctr = 0;   
$tmp = '';   
for($i = 0; $i &lt; strlen($txt); $i++) {   
$ctr = $ctr == strlen($encrypt\_key) ? 0 : $ctr;   
$tmp .= $txt\[$i] ^ $encrypt\_key\[$ctr++];   
}   
return $tmp;   
}   
?&gt; 

以下是一些示例加深对这三个加密解密函数的理解   
复制代码 代码如下:  
//string.php   
&lt;?php   
include “fun.php”; 

$txt = “This is a test”;   
$key = “testkey”;   
$encrypt = passport\_encrypt($txt,$key);   
$decrypt = passport\_decrypt($encrypt,$key); 

echo $txt.”&lt;br&gt;&lt;hr&gt;”;   
echo $encrypt.”&lt;br&gt;&lt;hr&gt;”;   
echo $decrypt.”&lt;br&gt;&lt;hr&gt;”;   
?&gt; 

//array.php   
&lt;?php   
include “fun.php”; 

$array = array(   
"a" =&gt; "1",   
"b" =&gt; "2",   
"c" =&gt; "3",   
"d" =&gt; "4"   
);   
//serialize产生一个可存储的值,返回一个字符串,unserialize还原   
$txt = serialize($array);   
$key = “testkey”;   
$encrypt = passport\_encrypt($txt,$key);   
$decrypt = passport\_decrypt($encrypt,$key);   
$decryptArray = unserialize($decrypt); 

echo $txt.”&lt;br&gt;&lt;hr&gt;”;   
echo $encrypt.”&lt;br&gt;&lt;hr&gt;”;   
echo $decrypt.”&lt;br&gt;&lt;hr&gt;”;   
echo $decryptArray.”&lt;br&gt;&lt;hr&gt;”;   
?&gt;

来源：http://bbs.php100.com/read-htm-tid-504795.html