You are currently browsing the archives of 乱七八糟 .

php 加解密函数

  1. <?php
  2. //加解密函数
  3. $encode = authcode('我要加密','ENCODE','34577');
  4.  
  5. $decode = authcode($encode,'DECODE','34577');
  6.  
  7. echo $encode."
  8. ";
  9. echo $decode;
  10.  
  11. //$auth_key = 34577 ; //密钥
  12. function authcode($string, $operation, $key = '')
  13. {
  14.  
  15. $key = md5($key ? $key : $GLOBALS['auth_key']);
  16. $key_length = strlen($key);
  17.  
  18. $string = $operation == 'DECODE' ? base64_decode($string) : substr(md5($string.$key), 0, 8).$string;
  19. $string_length = strlen($string);
  20.  
  21. $rndkey = $box = array();
  22. $result = '';
  23.  
  24. for($i = 0; $i &lt;= 255; $i++) {
  25. $rndkey[$i] = ord($key[$i % $key_length]);
  26. $box[$i] = $i;
  27. }
  28.  
  29. for($j = $i = 0; $i &lt; 256; $i++) {
  30. $j = ($j + $box[$i] + $rndkey[$i]) % 256;
  31. $tmp = $box[$i];
  32. $box[$i] = $box[$j];
  33. $box[$j] = $tmp;
  34. }
  35.  
  36. for($a = $j = $i = 0; $i &lt; $string_length; $i++) {
  37. $a = ($a + 1) % 256;
  38. $j = ($j + $box[$a]) % 256;
  39. $tmp = $box[$a];
  40. $box[$a] = $box[$j];
  41. $box[$j] = $tmp;
  42. $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
  43. }
  44.  
  45. if($operation == 'DECODE') {
  46. if(substr($result, 0, 8) == substr(md5(substr($result, 8).$key), 0, 8)) {
  47. return substr($result, 8);
  48. } else {
  49. return '';
  50. }
  51. } else {
  52. return str_replace('=', '', base64_encode($result));
  53. }
  54.  
  55. }
  56. ?>

Posted by shuck on Mar 3rd 2008 | Filed in php技术 | 评论(0)