Hmac.class.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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: cevin <cevin1991@gmail.com>
  10. // +----------------------------------------------------------------------
  11. /**
  12. * HMAC 加密实现类
  13. * @category ORG
  14. * @package ORG
  15. * @subpackage Crypt
  16. * @author cevin <cevin1991@gmail.com>
  17. */
  18. class Hmac {
  19. /**
  20. * SHA1加密
  21. * @access static
  22. * @param string $key 加密key
  23. * @param string $str 字符串
  24. * @return string
  25. */
  26. public static function sha1($key,$str) {
  27. $blocksize=64;
  28. $hashfunc='sha1';
  29. if (strlen($key)>$blocksize)
  30. $key=pack('H*', $hashfunc($key));
  31. $key=str_pad($key,$blocksize,chr(0x00));
  32. $ipad=str_repeat(chr(0x36),$blocksize);
  33. $opad=str_repeat(chr(0x5c),$blocksize);
  34. $hmac = pack(
  35. 'H*',$hashfunc(
  36. ($key^$opad).pack(
  37. 'H*',$hashfunc(
  38. ($key^$ipad).$str
  39. )
  40. )
  41. )
  42. );
  43. return $hmac;
  44. }
  45. /**
  46. * MD5加密
  47. * @access static
  48. * @param string $key 加密key
  49. * @param string $str 字符串
  50. * @return string
  51. */
  52. public static function md5($key, $str) {
  53. $b = 64;
  54. if (strlen($key) > $b) {
  55. $key = pack("H*",md5($key));
  56. }
  57. $key = str_pad($key, $b, chr(0x00));
  58. $ipad = str_pad('', $b, chr(0x36));
  59. $opad = str_pad('', $b, chr(0x5c));
  60. $k_ipad = $key ^ $ipad ;
  61. $k_opad = $key ^ $opad;
  62. return md5($k_opad . pack("H*",md5($k_ipad . $str)));
  63. }
  64. }