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