Digest.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Braintree;
  3. /**
  4. * Digest encryption module
  5. * Digest creates an HMAC-SHA1 hash for encrypting messages
  6. */
  7. class Digest
  8. {
  9. public static function hexDigestSha1($key, $string)
  10. {
  11. if(function_exists('hash_hmac')) {
  12. return self::_builtInHmacSha1($string, $key);
  13. } else {
  14. return self::_hmacSha1($string, $key);
  15. }
  16. }
  17. public static function hexDigestSha256($key, $string)
  18. {
  19. return hash_hmac('sha256', $string, hash('sha256', $key, true));
  20. }
  21. public static function secureCompare($left, $right)
  22. {
  23. if (strlen($left) != strlen($right)) {
  24. return false;
  25. }
  26. $leftBytes = unpack("C*", $left);
  27. $rightBytes = unpack("C*", $right);
  28. $result = 0;
  29. for ($i = 1; $i <= count($leftBytes); $i++) {
  30. $result = $result | ($leftBytes[$i] ^ $rightBytes[$i]);
  31. }
  32. return $result == 0;
  33. }
  34. public static function _builtInHmacSha1($message, $key)
  35. {
  36. return hash_hmac('sha1', $message, sha1($key, true));
  37. }
  38. public static function _hmacSha1($message, $key)
  39. {
  40. $pack = 'H40';
  41. $keyDigest = sha1($key,true);
  42. $innerPad = str_repeat(chr(0x36), 64);
  43. $outerPad = str_repeat(chr(0x5C), 64);
  44. for ($i = 0; $i < 20; $i++) {
  45. $innerPad{$i} = $keyDigest{$i} ^ $innerPad{$i};
  46. $outerPad{$i} = $keyDigest{$i} ^ $outerPad{$i};
  47. }
  48. return sha1($outerPad.pack($pack, sha1($innerPad.$message)));
  49. }
  50. }
  51. class_alias('Braintree\Digest', 'Braintree_Digest');