token.class.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * token.class.php
  4. *
  5. * @version v0.01
  6. * @create time 2017/7/14
  7. * @update time
  8. * @author TQ
  9. * @copyright Copyright (c) 微普科技 WiiPu Tech Inc. (http://www.wiipu.com)
  10. */
  11. class token
  12. {
  13. const LimitTime = 31536000;
  14. const TOKEN_KEY = "***gdoctor***";
  15. static public function genToken($id){
  16. $str = json_encode(array(time(),mt_rand(1000,9999),$id));
  17. return self::authcode($str, 'ENCODE', self::TOKEN_KEY);
  18. }
  19. static public function checkToken($token){
  20. $str = self::authcode($token, 'DECODE', self::TOKEN_KEY);
  21. $result = json_decode($str);
  22. if(is_array($result)){
  23. if(time()-$result[0]>self::LimitTime)
  24. {
  25. throw new MyException("token已失效!",100);
  26. }
  27. return $result[2];
  28. }else{
  29. throw new MyException("解密失败!",100);
  30. }
  31. }
  32. static public function authcode($string, $operation = 'DECODE', $key){
  33. $ckey_length = 4; // 随机密钥长度 取值 0-32;
  34. $key = md5($key);
  35. $keya = md5(substr($key, 0, 16));
  36. $keyb = md5(substr($key, 16, 16));
  37. $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
  38. $cryptkey = $keya.md5($keya.$keyc);
  39. $key_length = strlen($cryptkey);
  40. $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', 0).substr(md5($string.$keyb), 0, 16).$string;
  41. $string_length = strlen($string);
  42. $result = '';
  43. $box = range(0, 255);
  44. $rndkey = array();
  45. for($i = 0; $i <= 255; $i++) {
  46. $rndkey[$i] = ord($cryptkey[$i % $key_length]);
  47. }
  48. for($j = $i = 0; $i < 256; $i++) {
  49. $j = ($j + $box[$i] + $rndkey[$i]) % 256;
  50. $tmp = $box[$i];
  51. $box[$i] = $box[$j];
  52. $box[$j] = $tmp;
  53. }
  54. for($a = $j = $i = 0; $i < $string_length; $i++) {
  55. $a = ($a + 1) % 256;
  56. $j = ($j + $box[$a]) % 256;
  57. $tmp = $box[$a];
  58. $box[$a] = $box[$j];
  59. $box[$j] = $tmp;
  60. $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
  61. }
  62. if($operation == 'DECODE') {
  63. if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
  64. return substr($result, 26);
  65. } else {
  66. return '';
  67. }
  68. } else {
  69. return $keyc.str_replace('=', '', base64_encode($result));
  70. }
  71. }
  72. }
  73. ?>