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

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

代码如下:

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