在做项目时经常会遇到加密与解密,例如用户注册后会发一封邮件到邮箱,点击邮件中的链接激活账号,这是就需要用到加密与解密。在加密与解密时经常会遇到一个问题,就是密匙中可能会有加号,在解密的时候就解密不了,原因是遇到加号就相当于密匙结束了,下面这段加密代码,经过修改后已完美解决了这个问题:
/*加密函数内部调用函数*/
function keyED($txt,$encrypt_key) {
$encrypt_key = md5($encrypt_key);
$ctr=0;
$tmp = "";
for ($i=0;$i<strlen($txt);$i++) {
if ($ctr==strlen($encrypt_key)) $ctr=0;
$tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
$ctr++;
}
return $tmp;
}
/*发送邮件中连接地址的加密函数*/
function inner_DYEncrypt( $encryptstr ){
return urlencode(inner_DYEncrypt_subfun($encryptstr));
}
function inner_DYEncrypt_subfun($encryptstr){
srand((double)microtime()*1000000);
$encrypt_key = md5(rand(0,32000));
$ctr=0; $tmpstr = "";
for ($i=0;$i<strlen($encryptstr);$i++){
if ($ctr==strlen($encrypt_key)) $ctr=0;
$tmpstr.= substr($encrypt_key,$ctr,1) .
(substr($encryptstr,$i,1) ^ substr($encrypt_key,$ctr,1));
$ctr++;
}
$returninfo = base64_encode(keyED($tmpstr,ENCRYPTKEY));
if (strrpos($returninfo,"/") or strrpos($returninfo,'') or strrpos($returninfo,'+'))
return inner_DYEncrypt_subfun( $encryptstr );
return $returninfo;
}
/*发送邮件中连接地址的解密函数*/
function inner_DYDecrypt( $decryptstr ){
$decryptstr = urldecode($decryptstr);
$decryptstr = keyED(base64_decode($decryptstr),ENCRYPTKEY);
$tmpstr = "";
for ($i=0;$i<strlen($decryptstr);$i++){
$md5 = substr($decryptstr,$i,1);
$i++;
$tmpstr.= (substr($decryptstr,$i,1) ^ $md5);
}
return $tmpstr;
}
/*演示*/
$key = "rdid=5135"; //待加密的字符串
echo "待加密的字符串:".$key."";
$key = inner_DYEncrypt($key);
echo "加密后的字符串:".$key."";
echo "解密后的字符串:".inner_DYDecrypt($key);
?>
本站原创,转载请标明:来自铭洪博客(http://blog.csdn.net/long892230)