Crypt.class.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace Think\Crypt\Driver;
  12. /**
  13. * Crypt 加密实现类
  14. * @category ORG
  15. * @package ORG
  16. * @subpackage Crypt
  17. * @author liu21st <liu21st@gmail.com>
  18. */
  19. class Crypt {
  20. /**
  21. * 加密字符串
  22. * @param string $str 字符串
  23. * @param string $key 加密key
  24. * @param integer $expire 有效期(秒)
  25. * @return string
  26. */
  27. public static function encrypt($str,$key,$expire=0){
  28. $expire = sprintf('%010d', $expire ? $expire + time():0);
  29. $r = md5($key);
  30. $c=0;
  31. $v = "";
  32. $str = $expire.$str;
  33. $len = strlen($str);
  34. $l = strlen($r);
  35. for ($i=0;$i<$len;$i++){
  36. if ($c== $l) $c=0;
  37. $v.= substr($r,$c,1) .
  38. (substr($str,$i,1) ^ substr($r,$c,1));
  39. $c++;
  40. }
  41. return self::ed($v,$key);
  42. }
  43. /**
  44. * 解密字符串
  45. * @param string $str 字符串
  46. * @param string $key 加密key
  47. * @return string
  48. */
  49. public static function decrypt($str,$key) {
  50. $str = self::ed($str,$key);
  51. $v = "";
  52. $len = strlen($str);
  53. for ($i=0;$i<$len;$i++){
  54. $md5 = substr($str,$i,1);
  55. $i++;
  56. $v.= (substr($str,$i,1) ^ $md5);
  57. }
  58. $data = $v;
  59. $expire = substr($data,0,10);
  60. if($expire > 0 && $expire < time()) {
  61. return '';
  62. }
  63. $data = substr($data,10);
  64. return $data;
  65. }
  66. function ed($str,$key) {
  67. $r = md5($key);
  68. $c=0;
  69. $v = "";
  70. $len = strlen($str);
  71. $l = strlen($r);
  72. for ($i=0;$i<$len;$i++) {
  73. if ($c==$l) $c=0;
  74. $v.= substr($str,$i,1) ^ substr($r,$c,1);
  75. $c++;
  76. }
  77. return $v;
  78. }
  79. }