PageRenderTime 41ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/core/src/main/php/security/checksum/HMAC_MD5.class.php

http://github.com/xp-framework/xp-framework
PHP | 60 lines | 21 code | 8 blank | 31 comment | 2 complexity | 5135547357ce06b76dd14333c38f8fca MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /* This class is part of the XP framework
  3. *
  4. * $Id$
  5. */
  6. uses('security.checksum.Checksum', 'io.FileUtil');
  7. /**
  8. * HMAC_MD5 checksum
  9. *
  10. * @see xp://security.checksum.Checksum
  11. * @purpose Provide an API to check HMAC_MD5 checksums
  12. */
  13. class HMAC_MD5 extends Checksum {
  14. /**
  15. * Calculate HMAC_MD5 for given string (and key, if specified)
  16. *
  17. * @param string str
  18. * @param string key default NULL
  19. * @return string
  20. */
  21. public static function hash($str, $key= NULL) {
  22. if (NULL === $key) return pack('H*', md5($str));
  23. $key= str_pad($key, 0x40, "\x00");
  24. if (strlen($key) > 0x40) {
  25. $key= pack('H*', md5($key));
  26. }
  27. $ip= $key ^ str_repeat("\x36", 0x40);
  28. $op= $key ^ str_repeat("\x5c", 0x40);
  29. return HMAC_MD5::hash($op.pack('H*', md5($ip.$str)));
  30. }
  31. /**
  32. * Create a new checksum from a string
  33. *
  34. * @param string str
  35. * @param string key default NULL
  36. * @return security.checksum.HMAC_MD5
  37. */
  38. public static function fromString($str, $key= NULL) {
  39. return new HMAC_MD5(HMAC_MD5::hash($str, $key));
  40. }
  41. /**
  42. * Create a new checksum from a file object
  43. *
  44. * @param io.File file
  45. * @param string key default NULL
  46. * @return security.checksum.HMAC_MD5
  47. */
  48. public static function fromFile($file, $key= NULL) {
  49. return new HMAC_MD5(HMAC_MD5::hash(FileUtil::getContents($file), $key));
  50. }
  51. }
  52. ?>