Base64.class.php 2.5 KB

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