hmac.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. _openssl_md_meths = None
  10. from _operator import _compare_digest as compare_digest
  11. else:
  12. _openssl_md_meths = frozenset(_hashopenssl.openssl_md_meth_names)
  13. compare_digest = _hashopenssl.compare_digest
  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. "_digest_cons", "_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 parameter 'digestmod'.")
  43. if callable(digestmod):
  44. self._digest_cons = digestmod
  45. elif isinstance(digestmod, str):
  46. self._digest_cons = lambda d=b'': _hashlib.new(digestmod, d)
  47. else:
  48. self._digest_cons = lambda d=b'': digestmod.new(d)
  49. self._outer = self._digest_cons()
  50. self._inner = self._digest_cons()
  51. self.digest_size = self._inner.digest_size
  52. if hasattr(self._inner, 'block_size'):
  53. blocksize = self._inner.block_size
  54. if blocksize < 16:
  55. _warnings.warn('block_size of %d seems too small; using our '
  56. 'default of %d.' % (blocksize, self.blocksize),
  57. RuntimeWarning, 2)
  58. blocksize = self.blocksize
  59. else:
  60. _warnings.warn('No block_size attribute on given digest object; '
  61. 'Assuming %d.' % (self.blocksize),
  62. RuntimeWarning, 2)
  63. blocksize = self.blocksize
  64. # self.blocksize is the default blocksize. self.block_size is
  65. # effective block size as well as the public API attribute.
  66. self.block_size = blocksize
  67. if len(key) > blocksize:
  68. key = self._digest_cons(key).digest()
  69. key = key.ljust(blocksize, b'\0')
  70. self._outer.update(key.translate(trans_5C))
  71. self._inner.update(key.translate(trans_36))
  72. if msg is not None:
  73. self.update(msg)
  74. @property
  75. def name(self):
  76. return "hmac-" + self._inner.name
  77. @property
  78. def digest_cons(self):
  79. return self._digest_cons
  80. @property
  81. def inner(self):
  82. return self._inner
  83. @property
  84. def outer(self):
  85. return self._outer
  86. def update(self, msg):
  87. """Feed data from msg into this hashing object."""
  88. self._inner.update(msg)
  89. def copy(self):
  90. """Return a separate copy of this hashing object.
  91. An update to this copy won't affect the original object.
  92. """
  93. # Call __new__ directly to avoid the expensive __init__.
  94. other = self.__class__.__new__(self.__class__)
  95. other._digest_cons = self._digest_cons
  96. other.digest_size = self.digest_size
  97. other._inner = self._inner.copy()
  98. other._outer = self._outer.copy()
  99. return other
  100. def _current(self):
  101. """Return a hash object for the current state.
  102. To be used only internally with digest() and hexdigest().
  103. """
  104. h = self._outer.copy()
  105. h.update(self._inner.digest())
  106. return h
  107. def digest(self):
  108. """Return the hash value of this hashing object.
  109. This returns the hmac value as bytes. The object is
  110. not altered in any way by this function; you can continue
  111. updating the object after calling this function.
  112. """
  113. h = self._current()
  114. return h.digest()
  115. def hexdigest(self):
  116. """Like digest(), but returns a string of hexadecimal digits instead.
  117. """
  118. h = self._current()
  119. return h.hexdigest()
  120. def new(key, msg=None, digestmod=''):
  121. """Create a new hashing object and return it.
  122. key: bytes or buffer, The starting key for the hash.
  123. msg: bytes or buffer, Initial input for the hash, or None.
  124. digestmod: A hash name suitable for hashlib.new(). *OR*
  125. A hashlib constructor returning a new hash object. *OR*
  126. A module supporting PEP 247.
  127. Required as of 3.8, despite its position after the optional
  128. msg argument. Passing it as a keyword argument is
  129. recommended, though not required for legacy API reasons.
  130. You can now feed arbitrary bytes into the object using its update()
  131. method, and can ask for the hash value at any time by calling its digest()
  132. or hexdigest() methods.
  133. """
  134. return HMAC(key, msg, digestmod)
  135. def digest(key, msg, digest):
  136. """Fast inline implementation of HMAC.
  137. key: bytes or buffer, The key for the keyed hash object.
  138. msg: bytes or buffer, Input message.
  139. digest: A hash name suitable for hashlib.new() for best performance. *OR*
  140. A hashlib constructor returning a new hash object. *OR*
  141. A module supporting PEP 247.
  142. """
  143. if (_hashopenssl is not None and
  144. isinstance(digest, str) and digest in _openssl_md_meths):
  145. return _hashopenssl.hmac_digest(key, msg, digest)
  146. if callable(digest):
  147. digest_cons = digest
  148. elif isinstance(digest, str):
  149. digest_cons = lambda d=b'': _hashlib.new(digest, d)
  150. else:
  151. digest_cons = lambda d=b'': digest.new(d)
  152. inner = digest_cons()
  153. outer = digest_cons()
  154. blocksize = getattr(inner, 'block_size', 64)
  155. if len(key) > blocksize:
  156. key = digest_cons(key).digest()
  157. key = key + b'\x00' * (blocksize - len(key))
  158. inner.update(key.translate(trans_36))
  159. outer.update(key.translate(trans_5C))
  160. inner.update(msg)
  161. outer.update(inner.digest())
  162. return outer.digest()