Base64.class.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. * @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. for ($i=0;$i< $len;$i++) {
  31. if ($x== $l) $x=0;
  32. $char .=substr($key,$x,1);
  33. $x++;
  34. }
  35. for ($i=0;$i< $len;$i++) {
  36. $str .=chr(ord(substr($data,$i,1))+(ord(substr($char,$i,1)))%256);
  37. }
  38. return $str;
  39. }
  40. /**
  41. * 解密字符串
  42. * @param string $str 字符串
  43. * @param string $key 加密key
  44. * @return string
  45. */
  46. public static function decrypt($data,$key) {
  47. $key = md5($key);
  48. $x=0;
  49. $len = strlen($data);
  50. $l = strlen($key);
  51. for ($i=0;$i< $len;$i++) {
  52. if ($x== $l) $x=0;
  53. $char .=substr($key,$x,1);
  54. $x++;
  55. }
  56. for ($i=0;$i< $len;$i++) {
  57. if (ord(substr($data,$i,1))<ord(substr($char,$i,1))) {
  58. $str .=chr((ord(substr($data,$i,1))+256)-ord(substr($char,$i,1)));
  59. }else{
  60. $str .=chr(ord(substr($data,$i,1))-ord(substr($char,$i,1)));
  61. }
  62. }
  63. $data = base64_decode($str);
  64. $expire = substr($data,0,10);
  65. if($expire > 0 && $expire < time()) {
  66. return '';
  67. }
  68. $data = substr($data,10);
  69. return $data;
  70. }
  71. }