hmac.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. """HMAC (Keyed-Hashing for Message Authentication) Python module.
  2. Implements the HMAC algorithm as described by RFC 2104.
  3. """
  4. import warnings as _warnings
  5. from operator import _compare_digest as compare_digest
  6. trans_5C = "".join ([chr (x ^ 0x5C) for x in xrange(256)])
  7. trans_36 = "".join ([chr (x ^ 0x36) for x in xrange(256)])
  8. # The size of the digests returned by HMAC depends on the underlying
  9. # hashing module used. Use digest_size from the instance of HMAC instead.
  10. digest_size = None
  11. # A unique object passed by HMAC.copy() to the HMAC constructor, in order
  12. # that the latter return very quickly. HMAC("") in contrast is quite
  13. # expensive.
  14. _secret_backdoor_key = []
  15. class HMAC:
  16. """RFC 2104 HMAC class. Also complies with RFC 4231.
  17. This supports the API for Cryptographic Hash Functions (PEP 247).
  18. """
  19. blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
  20. def __init__(self, key, msg = None, digestmod = None):
  21. """Create a new HMAC object.
  22. key: key for the keyed hash object.
  23. msg: Initial input for the hash, if provided.
  24. digestmod: A module supporting PEP 247. *OR*
  25. A hashlib constructor returning a new hash object.
  26. Defaults to hashlib.md5.
  27. """
  28. if key is _secret_backdoor_key: # cheap
  29. return
  30. if digestmod is None:
  31. import hashlib
  32. digestmod = hashlib.md5
  33. if hasattr(digestmod, '__call__'):
  34. self.digest_cons = digestmod
  35. else:
  36. self.digest_cons = lambda d='': digestmod.new(d)
  37. self.outer = self.digest_cons()
  38. self.inner = self.digest_cons()
  39. self.digest_size = self.inner.digest_size
  40. if hasattr(self.inner, 'block_size'):
  41. blocksize = self.inner.block_size
  42. if blocksize < 16:
  43. # Very low blocksize, most likely a legacy value like
  44. # Lib/sha.py and Lib/md5.py have.
  45. _warnings.warn('block_size of %d seems too small; using our '
  46. 'default of %d.' % (blocksize, self.blocksize),
  47. RuntimeWarning, 2)
  48. blocksize = self.blocksize
  49. else:
  50. _warnings.warn('No block_size attribute on given digest object; '
  51. 'Assuming %d.' % (self.blocksize),
  52. RuntimeWarning, 2)
  53. blocksize = self.blocksize
  54. if len(key) > blocksize:
  55. key = self.digest_cons(key).digest()
  56. key = key + chr(0) * (blocksize - len(key))
  57. self.outer.update(key.translate(trans_5C))
  58. self.inner.update(key.translate(trans_36))
  59. if msg is not None:
  60. self.update(msg)
  61. ## def clear(self):
  62. ## raise NotImplementedError, "clear() method not available in HMAC."
  63. def update(self, msg):
  64. """Update this hashing object with the string msg.
  65. """
  66. self.inner.update(msg)
  67. def copy(self):
  68. """Return a separate copy of this hashing object.
  69. An update to this copy won't affect the original object.
  70. """
  71. other = self.__class__(_secret_backdoor_key)
  72. other.digest_cons = self.digest_cons
  73. other.digest_size = self.digest_size
  74. other.inner = self.inner.copy()
  75. other.outer = self.outer.copy()
  76. return other
  77. def _current(self):
  78. """Return a hash object for the current state.
  79. To be used only internally with digest() and hexdigest().
  80. """
  81. h = self.outer.copy()
  82. h.update(self.inner.digest())
  83. return h
  84. def digest(self):
  85. """Return the hash value of this hashing object.
  86. This returns a string containing 8-bit data. The object is
  87. not altered in any way by this function; you can continue
  88. updating the object after calling this function.
  89. """
  90. h = self._current()
  91. return h.digest()
  92. def hexdigest(self):
  93. """Like digest(), but returns a string of hexadecimal digits instead.
  94. """
  95. h = self._current()
  96. return h.hexdigest()
  97. def new(key, msg = None, digestmod = None):
  98. """Create a new hashing object and return it.
  99. key: The starting key for the hash.
  100. msg: if available, will immediately be hashed into the object's starting
  101. state.
  102. You can now feed arbitrary strings into the object using its update()
  103. method, and can ask for the hash value at any time by calling its digest()
  104. method.
  105. """
  106. return HMAC(key, msg, digestmod)