hmac.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. """HMAC (Keyed-Hashing for Message Authentication) module.
  2. Implements the HMAC algorithm as described by RFC 2104.
  3. """
  4. import warnings as _warnings
  5. try:
  6. import _hashlib as _hashopenssl
  7. except ImportError:
  8. _hashopenssl = None
  9. _functype = None
  10. from _operator import _compare_digest as compare_digest
  11. else:
  12. compare_digest = _hashopenssl.compare_digest
  13. _functype = type(_hashopenssl.openssl_sha256) # builtin type
  14. import hashlib as _hashlib
  15. trans_5C = bytes((x ^ 0x5C) for x in range(256))
  16. trans_36 = bytes((x ^ 0x36) for x in range(256))
  17. # The size of the digests returned by HMAC depends on the underlying
  18. # hashing module used. Use digest_size from the instance of HMAC instead.
  19. digest_size = None
  20. class HMAC:
  21. """RFC 2104 HMAC class. Also complies with RFC 4231.
  22. This supports the API for Cryptographic Hash Functions (PEP 247).
  23. """
  24. blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
  25. __slots__ = (
  26. "_hmac", "_inner", "_outer", "block_size", "digest_size"
  27. )
  28. def __init__(self, key, msg=None, digestmod=''):
  29. """Create a new HMAC object.
  30. key: bytes or buffer, key for the keyed hash object.
  31. msg: bytes or buffer, Initial input for the hash or None.
  32. digestmod: A hash name suitable for hashlib.new(). *OR*
  33. A hashlib constructor returning a new hash object. *OR*
  34. A module supporting PEP 247.
  35. Required as of 3.8, despite its position after the optional
  36. msg argument. Passing it as a keyword argument is
  37. recommended, though not required for legacy API reasons.
  38. """
  39. if not isinstance(key, (bytes, bytearray)):
  40. raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
  41. if not digestmod:
  42. raise TypeError("Missing required argument 'digestmod'.")
  43. if _hashopenssl and isinstance(digestmod, (str, _functype)):
  44. try:
  45. self._init_hmac(key, msg, digestmod)
  46. except _hashopenssl.UnsupportedDigestmodError:
  47. self._init_old(key, msg, digestmod)
  48. else:
  49. self._init_old(key, msg, digestmod)
  50. def _init_hmac(self, key, msg, digestmod):
  51. self._hmac = _hashopenssl.hmac_new(key, msg, digestmod=digestmod)
  52. self.digest_size = self._hmac.digest_size
  53. self.block_size = self._hmac.block_size
  54. def _init_old(self, key, msg, digestmod):
  55. if callable(digestmod):
  56. digest_cons = digestmod
  57. elif isinstance(digestmod, str):
  58. digest_cons = lambda d=b'': _hashlib.new(digestmod, d)
  59. else:
  60. digest_cons = lambda d=b'': digestmod.new(d)
  61. self._hmac = None
  62. self._outer = digest_cons()
  63. self._inner = digest_cons()
  64. self.digest_size = self._inner.digest_size
  65. if hasattr(self._inner, 'block_size'):
  66. blocksize = self._inner.block_size
  67. if blocksize < 16:
  68. _warnings.warn('block_size of %d seems too small; using our '
  69. 'default of %d.' % (blocksize, self.blocksize),
  70. RuntimeWarning, 2)
  71. blocksize = self.blocksize
  72. else:
  73. _warnings.warn('No block_size attribute on given digest object; '
  74. 'Assuming %d.' % (self.blocksize),
  75. RuntimeWarning, 2)
  76. blocksize = self.blocksize
  77. if len(key) > blocksize:
  78. key = digest_cons(key).digest()
  79. # self.blocksize is the default blocksize. self.block_size is
  80. # effective block size as well as the public API attribute.
  81. self.block_size = blocksize
  82. key = key.ljust(blocksize, b'\0')
  83. self._outer.update(key.translate(trans_5C))
  84. self._inner.update(key.translate(trans_36))
  85. if msg is not None:
  86. self.update(msg)
  87. @property
  88. def name(self):
  89. if self._hmac:
  90. return self._hmac.name
  91. else:
  92. return f"hmac-{self._inner.name}"
  93. def update(self, msg):
  94. """Feed data from msg into this hashing object."""
  95. inst = self._hmac or self._inner
  96. inst.update(msg)
  97. def copy(self):
  98. """Return a separate copy of this hashing object.
  99. An update to this copy won't affect the original object.
  100. """
  101. # Call __new__ directly to avoid the expensive __init__.
  102. other = self.__class__.__new__(self.__class__)
  103. other.digest_size = self.digest_size
  104. if self._hmac:
  105. other._hmac = self._hmac.copy()
  106. other._inner = other._outer = None
  107. else:
  108. other._hmac = None
  109. other._inner = self._inner.copy()
  110. other._outer = self._outer.copy()
  111. return other
  112. def _current(self):
  113. """Return a hash object for the current state.
  114. To be used only internally with digest() and hexdigest().
  115. """
  116. if self._hmac:
  117. return self._hmac
  118. else:
  119. h = self._outer.copy()
  120. h.update(self._inner.digest())
  121. return h
  122. def digest(self):
  123. """Return the hash value of this hashing object.
  124. This returns the hmac value as bytes. The object is
  125. not altered in any way by this function; you can continue
  126. updating the object after calling this function.
  127. """
  128. h = self._current()
  129. return h.digest()
  130. def hexdigest(self):
  131. """Like digest(), but returns a string of hexadecimal digits instead.
  132. """
  133. h = self._current()
  134. return h.hexdigest()
  135. def new(key, msg=None, digestmod=''):
  136. """Create a new hashing object and return it.
  137. key: bytes or buffer, The starting key for the hash.
  138. msg: bytes or buffer, Initial input for the hash, or None.
  139. digestmod: A hash name suitable for hashlib.new(). *OR*
  140. A hashlib constructor returning a new hash object. *OR*
  141. A module supporting PEP 247.
  142. Required as of 3.8, despite its position after the optional
  143. msg argument. Passing it as a keyword argument is
  144. recommended, though not required for legacy API reasons.
  145. You can now feed arbitrary bytes into the object using its update()
  146. method, and can ask for the hash value at any time by calling its digest()
  147. or hexdigest() methods.
  148. """
  149. return HMAC(key, msg, digestmod)
  150. def digest(key, msg, digest):
  151. """Fast inline implementation of HMAC.
  152. key: bytes or buffer, The key for the keyed hash object.
  153. msg: bytes or buffer, Input message.
  154. digest: A hash name suitable for hashlib.new() for best performance. *OR*
  155. A hashlib constructor returning a new hash object. *OR*
  156. A module supporting PEP 247.
  157. """
  158. if _hashopenssl is not None and isinstance(digest, (str, _functype)):
  159. try:
  160. return _hashopenssl.hmac_digest(key, msg, digest)
  161. except _hashopenssl.UnsupportedDigestmodError:
  162. pass
  163. if callable(digest):
  164. digest_cons = digest
  165. elif isinstance(digest, str):
  166. digest_cons = lambda d=b'': _hashlib.new(digest, d)
  167. else:
  168. digest_cons = lambda d=b'': digest.new(d)
  169. inner = digest_cons()
  170. outer = digest_cons()
  171. blocksize = getattr(inner, 'block_size', 64)
  172. if len(key) > blocksize:
  173. key = digest_cons(key).digest()
  174. key = key + b'\x00' * (blocksize - len(key))
  175. inner.update(key.translate(trans_36))
  176. outer.update(key.translate(trans_5C))
  177. inner.update(msg)
  178. outer.update(inner.digest())
  179. return outer.digest()