HMAC.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. #
  2. # HMAC.py - Implements the HMAC algorithm as described by RFC 2104.
  3. #
  4. # ===================================================================
  5. #
  6. # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
  7. # All rights reserved.
  8. #
  9. # Redistribution and use in source and binary forms, with or without
  10. # modification, are permitted provided that the following conditions
  11. # are met:
  12. #
  13. # 1. Redistributions of source code must retain the above copyright
  14. # notice, this list of conditions and the following disclaimer.
  15. # 2. Redistributions in binary form must reproduce the above copyright
  16. # notice, this list of conditions and the following disclaimer in
  17. # the documentation and/or other materials provided with the
  18. # distribution.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  23. # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  24. # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  25. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  26. # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  27. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  28. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  29. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  30. # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  31. # POSSIBILITY OF SUCH DAMAGE.
  32. # ===================================================================
  33. from Crypto.Util.py3compat import bord, tobytes
  34. from binascii import unhexlify
  35. from Crypto.Hash import BLAKE2s
  36. from Crypto.Util.strxor import strxor
  37. from Crypto.Random import get_random_bytes
  38. __all__ = ['new', 'HMAC']
  39. _hash2hmac_oid = {
  40. '1.3.14.3.2.26': '1.2.840.113549.2.7', # SHA-1
  41. '2.16.840.1.101.3.4.2.4': '1.2.840.113549.2.8', # SHA-224
  42. '2.16.840.1.101.3.4.2.1': '1.2.840.113549.2.9', # SHA-256
  43. '2.16.840.1.101.3.4.2.2': '1.2.840.113549.2.10', # SHA-384
  44. '2.16.840.1.101.3.4.2.3': '1.2.840.113549.2.11', # SHA-512
  45. '2.16.840.1.101.3.4.2.5': '1.2.840.113549.2.12', # SHA-512_224
  46. '2.16.840.1.101.3.4.2.6': '1.2.840.113549.2.13', # SHA-512_256
  47. '2.16.840.1.101.3.4.2.7': '2.16.840.1.101.3.4.2.13', # SHA-3 224
  48. '2.16.840.1.101.3.4.2.8': '2.16.840.1.101.3.4.2.14', # SHA-3 256
  49. '2.16.840.1.101.3.4.2.9': '2.16.840.1.101.3.4.2.15', # SHA-3 384
  50. '2.16.840.1.101.3.4.2.10': '2.16.840.1.101.3.4.2.16', # SHA-3 512
  51. }
  52. _hmac2hash_oid = {v: k for k, v in _hash2hmac_oid.items()}
  53. class HMAC(object):
  54. """An HMAC hash object.
  55. Do not instantiate directly. Use the :func:`new` function.
  56. :ivar digest_size: the size in bytes of the resulting MAC tag
  57. :vartype digest_size: integer
  58. :ivar oid: the ASN.1 object ID of the HMAC algorithm.
  59. Only present if the algorithm was officially assigned one.
  60. """
  61. def __init__(self, key, msg=b"", digestmod=None):
  62. if digestmod is None:
  63. from Crypto.Hash import MD5
  64. digestmod = MD5
  65. if msg is None:
  66. msg = b""
  67. # Size of the MAC tag
  68. self.digest_size = digestmod.digest_size
  69. self._digestmod = digestmod
  70. # Hash OID --> HMAC OID
  71. try:
  72. self.oid = _hash2hmac_oid[digestmod.oid]
  73. except (KeyError, AttributeError):
  74. pass
  75. if isinstance(key, memoryview):
  76. key = key.tobytes()
  77. try:
  78. if len(key) <= digestmod.block_size:
  79. # Step 1 or 2
  80. key_0 = key + b"\x00" * (digestmod.block_size - len(key))
  81. else:
  82. # Step 3
  83. hash_k = digestmod.new(key).digest()
  84. key_0 = hash_k + b"\x00" * (digestmod.block_size - len(hash_k))
  85. except AttributeError:
  86. # Not all hash types have "block_size"
  87. raise ValueError("Hash type incompatible to HMAC")
  88. # Step 4
  89. key_0_ipad = strxor(key_0, b"\x36" * len(key_0))
  90. # Start step 5 and 6
  91. self._inner = digestmod.new(key_0_ipad)
  92. self._inner.update(msg)
  93. # Step 7
  94. key_0_opad = strxor(key_0, b"\x5c" * len(key_0))
  95. # Start step 8 and 9
  96. self._outer = digestmod.new(key_0_opad)
  97. def update(self, msg):
  98. """Authenticate the next chunk of message.
  99. Args:
  100. data (byte string/byte array/memoryview): The next chunk of data
  101. """
  102. self._inner.update(msg)
  103. return self
  104. def _pbkdf2_hmac_assist(self, first_digest, iterations):
  105. """Carry out the expensive inner loop for PBKDF2-HMAC"""
  106. result = self._digestmod._pbkdf2_hmac_assist(
  107. self._inner,
  108. self._outer,
  109. first_digest,
  110. iterations)
  111. return result
  112. def copy(self):
  113. """Return a copy ("clone") of the HMAC object.
  114. The copy will have the same internal state as the original HMAC
  115. object.
  116. This can be used to efficiently compute the MAC tag of byte
  117. strings that share a common initial substring.
  118. :return: An :class:`HMAC`
  119. """
  120. new_hmac = HMAC(b"fake key", digestmod=self._digestmod)
  121. # Syncronize the state
  122. new_hmac._inner = self._inner.copy()
  123. new_hmac._outer = self._outer.copy()
  124. return new_hmac
  125. def digest(self):
  126. """Return the **binary** (non-printable) MAC tag of the message
  127. authenticated so far.
  128. :return: The MAC tag digest, computed over the data processed so far.
  129. Binary form.
  130. :rtype: byte string
  131. """
  132. frozen_outer_hash = self._outer.copy()
  133. frozen_outer_hash.update(self._inner.digest())
  134. return frozen_outer_hash.digest()
  135. def verify(self, mac_tag):
  136. """Verify that a given **binary** MAC (computed by another party)
  137. is valid.
  138. Args:
  139. mac_tag (byte string/byte string/memoryview): the expected MAC of the message.
  140. Raises:
  141. ValueError: if the MAC does not match. It means that the message
  142. has been tampered with or that the MAC key is incorrect.
  143. """
  144. secret = get_random_bytes(16)
  145. mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=mac_tag)
  146. mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=self.digest())
  147. if mac1.digest() != mac2.digest():
  148. raise ValueError("MAC check failed")
  149. def hexdigest(self):
  150. """Return the **printable** MAC tag of the message authenticated so far.
  151. :return: The MAC tag, computed over the data processed so far.
  152. Hexadecimal encoded.
  153. :rtype: string
  154. """
  155. return "".join(["%02x" % bord(x)
  156. for x in tuple(self.digest())])
  157. def hexverify(self, hex_mac_tag):
  158. """Verify that a given **printable** MAC (computed by another party)
  159. is valid.
  160. Args:
  161. hex_mac_tag (string): the expected MAC of the message,
  162. as a hexadecimal string.
  163. Raises:
  164. ValueError: if the MAC does not match. It means that the message
  165. has been tampered with or that the MAC key is incorrect.
  166. """
  167. self.verify(unhexlify(tobytes(hex_mac_tag)))
  168. def new(key, msg=b"", digestmod=None):
  169. """Create a new MAC object.
  170. Args:
  171. key (bytes/bytearray/memoryview):
  172. key for the MAC object.
  173. It must be long enough to match the expected security level of the
  174. MAC.
  175. msg (bytes/bytearray/memoryview):
  176. Optional. The very first chunk of the message to authenticate.
  177. It is equivalent to an early call to :meth:`HMAC.update`.
  178. digestmod (module):
  179. The hash to use to implement the HMAC.
  180. Default is :mod:`Crypto.Hash.MD5`.
  181. Returns:
  182. An :class:`HMAC` object
  183. """
  184. return HMAC(key, msg, digestmod)