Think.class.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. * Base64 加密实现类
  14. */
  15. class Think {
  16. /**
  17. * 加密字符串
  18. * @param string $str 字符串
  19. * @param string $key 加密key
  20. * @param integer $expire 有效期(秒)
  21. * @return string
  22. */
  23. public static function encrypt($data,$key,$expire=0) {
  24. $expire = sprintf('%010d', $expire ? $expire + time():0);
  25. $key = md5($key);
  26. $data = base64_encode($expire.$data);
  27. $x = 0;
  28. $len = strlen($data);
  29. $l = strlen($key);
  30. $char = $str = '';
  31. for ($i = 0; $i < $len; $i++) {
  32. if ($x == $l) $x = 0;
  33. $char .= substr($key, $x, 1);
  34. $x++;
  35. }
  36. for ($i = 0; $i < $len; $i++) {
  37. $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
  38. }
  39. return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));
  40. }
  41. /**
  42. * 解密字符串
  43. * @param string $str 字符串
  44. * @param string $key 加密key
  45. * @return string
  46. */
  47. public static function decrypt($data,$key) {
  48. $key = md5($key);
  49. $data = str_replace(array('-','_'),array('+','/'),$data);
  50. $mod4 = strlen($data) % 4;
  51. if ($mod4) {
  52. $data .= substr('====', $mod4);
  53. }
  54. $data = base64_decode($data);
  55. $x = 0;
  56. $len = strlen($data);
  57. $l = strlen($key);
  58. $char = $str = '';
  59. for ($i = 0; $i < $len; $i++) {
  60. if ($x == $l) $x = 0;
  61. $char .= substr($key, $x, 1);
  62. $x++;
  63. }
  64. for ($i = 0; $i < $len; $i++) {
  65. if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {
  66. $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
  67. }else{
  68. $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
  69. }
  70. }
  71. $data = base64_decode($str);
  72. $expire = substr($data,0,10);
  73. if($expire > 0 && $expire < time()) {
  74. return '';
  75. }
  76. $data = substr($data,10);
  77. return $data;
  78. }
  79. }