hmac.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. try:
  7. import _hashlib as _hashopenssl
  8. except ImportError:
  9. _hashopenssl = None
  10. _openssl_md_meths = None
  11. else:
  12. _openssl_md_meths = frozenset(_hashopenssl.openssl_md_meth_names)
  13. import hashlib as _hashlib
  14. trans_5C = bytes((x ^ 0x5C) for x in range(256))
  15. trans_36 = bytes((x ^ 0x36) for x in range(256))
  16. # The size of the digests returned by HMAC depends on the underlying
  17. # hashing module used. Use digest_size from the instance of HMAC instead.
  18. digest_size = None
  19. class HMAC:
  20. """RFC 2104 HMAC class. Also complies with RFC 4231.
  21. This supports the API for Cryptographic Hash Functions (PEP 247).
  22. """
  23. blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
  24. def __init__(self, key, msg = None, digestmod = None):
  25. """Create a new HMAC object.
  26. key: key for the keyed hash object.
  27. msg: Initial input for the hash, if provided.
  28. digestmod: Required. A module supporting PEP 247. *OR*
  29. A hashlib constructor returning a new hash object. *OR*
  30. A hash name suitable for hashlib.new().
  31. Note: key and msg must be a bytes or bytearray objects.
  32. """
  33. if not isinstance(key, (bytes, bytearray)):
  34. raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
  35. if digestmod is None:
  36. raise ValueError('`digestmod` is required.')
  37. if callable(digestmod):
  38. self.digest_cons = digestmod
  39. elif isinstance(digestmod, str):
  40. self.digest_cons = lambda d=b'': _hashlib.new(digestmod, d)
  41. else:
  42. self.digest_cons = lambda d=b'': digestmod.new(d)
  43. self.outer = self.digest_cons()
  44. self.inner = self.digest_cons()
  45. self.digest_size = self.inner.digest_size
  46. if hasattr(self.inner, 'block_size'):
  47. blocksize = self.inner.block_size
  48. if blocksize < 16:
  49. _warnings.warn('block_size of %d seems too small; using our '
  50. 'default of %d.' % (blocksize, self.blocksize),
  51. RuntimeWarning, 2)
  52. blocksize = self.blocksize
  53. else:
  54. _warnings.warn('No block_size attribute on given digest object; '
  55. 'Assuming %d.' % (self.blocksize),
  56. RuntimeWarning, 2)
  57. blocksize = self.blocksize
  58. # self.blocksize is the default blocksize. self.block_size is
  59. # effective block size as well as the public API attribute.
  60. self.block_size = blocksize
  61. if len(key) > blocksize:
  62. key = self.digest_cons(key).digest()
  63. key = key.ljust(blocksize, b'\0')
  64. self.outer.update(key.translate(trans_5C))
  65. self.inner.update(key.translate(trans_36))
  66. if msg is not None:
  67. self.update(msg)
  68. @property
  69. def name(self):
  70. return "hmac-" + self.inner.name
  71. def update(self, msg):
  72. """Update this hashing object with the string msg.
  73. """
  74. self.inner.update(msg)
  75. def copy(self):
  76. """Return a separate copy of this hashing object.
  77. An update to this copy won't affect the original object.
  78. """
  79. # Call __new__ directly to avoid the expensive __init__.
  80. other = self.__class__.__new__(self.__class__)
  81. other.digest_cons = self.digest_cons
  82. other.digest_size = self.digest_size
  83. other.inner = self.inner.copy()
  84. other.outer = self.outer.copy()
  85. return other
  86. def _current(self):
  87. """Return a hash object for the current state.
  88. To be used only internally with digest() and hexdigest().
  89. """
  90. h = self.outer.copy()
  91. h.update(self.inner.digest())
  92. return h
  93. def digest(self):
  94. """Return the hash value of this hashing object.
  95. This returns a string containing 8-bit data. The object is
  96. not altered in any way by this function; you can continue
  97. updating the object after calling this function.
  98. """
  99. h = self._current()
  100. return h.digest()
  101. def hexdigest(self):
  102. """Like digest(), but returns a string of hexadecimal digits instead.
  103. """
  104. h = self._current()
  105. return h.hexdigest()
  106. def new(key, msg = None, digestmod = None):
  107. """Create a new hashing object and return it.
  108. key: The starting key for the hash.
  109. msg: if available, will immediately be hashed into the object's starting
  110. state.
  111. You can now feed arbitrary strings into the object using its update()
  112. method, and can ask for the hash value at any time by calling its digest()
  113. method.
  114. """
  115. return HMAC(key, msg, digestmod)
  116. def digest(key, msg, digest):
  117. """Fast inline implementation of HMAC
  118. key: key for the keyed hash object.
  119. msg: input message
  120. digest: A hash name suitable for hashlib.new() for best performance. *OR*
  121. A hashlib constructor returning a new hash object. *OR*
  122. A module supporting PEP 247.
  123. Note: key and msg must be a bytes or bytearray objects.
  124. """
  125. if (_hashopenssl is not None and
  126. isinstance(digest, str) and digest in _openssl_md_meths):
  127. return _hashopenssl.hmac_digest(key, msg, digest)
  128. if callable(digest):
  129. digest_cons = digest
  130. elif isinstance(digest, str):
  131. digest_cons = lambda d=b'': _hashlib.new(digest, d)
  132. else:
  133. digest_cons = lambda d=b'': digest.new(d)
  134. inner = digest_cons()
  135. outer = digest_cons()
  136. blocksize = getattr(inner, 'block_size', 64)
  137. if len(key) > blocksize:
  138. key = digest_cons(key).digest()
  139. key = key + b'\x00' * (blocksize - len(key))
  140. inner.update(key.translate(trans_36))
  141. outer.update(key.translate(trans_5C))
  142. inner.update(msg)
  143. outer.update(inner.digest())
  144. return outer.digest()