首页 > 开发 > PHP > 正文

经典PHP加密解密函数Authcode()修复版代码

2024-05-04 23:33:56
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了经典PHP加密解密函数Authcode()修复版代码,需要的朋友可以参考下

Authcode这个函数很多人都使用,这函数来自Discuz程序,用于加密解密字符串,可以设置钥匙(key)和过期时间,在很多时候都用得着。原版的函数代码可能会生成+、/、&这样的字符,导致通过URL传值取回时被转义,导致无法解密。火端网络稍加修改,把这几个字符替换成其它字符,解密时再替换回去,这样就完美了!

代码如下:

 

 
  1. function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0){ 
  2.  
  3. if($operation == 'DECODE') { 
  4. $string = str_replace('[a]','+',$string); 
  5. $string = str_replace('[b]','&',$string); 
  6. $string = str_replace('[c]','/',$string); 
  7. } 
  8. $ckey_length = 4; 
  9. $key = md5($key ? $key : 'livcmsencryption '); 
  10. $keya = md5(substr($key, 0, 16)); 
  11. $keyb = md5(substr($key, 16, 16)); 
  12. $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : ''; 
  13. $cryptkey = $keya.md5($keya.$keyc); 
  14. $key_length = strlen($cryptkey); 
  15. $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string; 
  16. $string_length = strlen($string); 
  17. $result = ''; 
  18. $box = range(0, 255); 
  19. $rndkey = array(); 
  20. for($i = 0; $i <= 255; $i++) { 
  21. $rndkey[$i] = ord($cryptkey[$i % $key_length]); 
  22. } 
  23. for($j = $i = 0; $i < 256; $i++) { 
  24. $j = ($j + $box[$i] + $rndkey[$i]) % 256; 
  25. $tmp = $box[$i]; 
  26. $box[$i] = $box[$j]; 
  27. $box[$j] = $tmp; 
  28. } 
  29. for($a = $j = $i = 0; $i < $string_length; $i++) { 
  30. $a = ($a + 1) % 256; 
  31. $j = ($j + $box[$a]) % 256; 
  32. $tmp = $box[$a]; 
  33. $box[$a] = $box[$j]; 
  34. $box[$j] = $tmp; 
  35. $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); 
  36. } 
  37. if($operation == 'DECODE') { 
  38. if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) { 
  39.  
  40. return substr($result, 26); 
  41. } else { 
  42. return ''; 
  43. } 
  44. } else { 
  45. $ustr = $keyc.str_replace('=', '', base64_encode($result)); 
  46. $ustr = str_replace('+','[a]',$ustr); 
  47. $ustr = str_replace('&','[b]',$ustr); 
  48. $ustr = str_replace('/','[c]',$ustr); 
  49. return $ustr; 
  50. } 
  51. } 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表