CMAC.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Hash/CMAC.py - Implements the CMAC algorithm
  4. #
  5. # ===================================================================
  6. # The contents of this file are dedicated to the public domain. To
  7. # the extent that dedication to the public domain is not available,
  8. # everyone is granted a worldwide, perpetual, royalty-free,
  9. # non-exclusive license to exercise all rights associated with the
  10. # contents of this file for any purpose whatsoever.
  11. # No rights are reserved.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  17. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  18. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  19. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. # ===================================================================
  22. from binascii import unhexlify
  23. from Cryptodome.Hash import BLAKE2s
  24. from Cryptodome.Util.strxor import strxor
  25. from Cryptodome.Util.number import long_to_bytes, bytes_to_long
  26. from Cryptodome.Util.py3compat import bord, tobytes, _copy_bytes
  27. from Cryptodome.Random import get_random_bytes
  28. # The size of the authentication tag produced by the MAC.
  29. digest_size = None
  30. def _shift_bytes(bs, xor_lsb=0):
  31. num = (bytes_to_long(bs) << 1) ^ xor_lsb
  32. return long_to_bytes(num, len(bs))[-len(bs):]
  33. class CMAC(object):
  34. """A CMAC hash object.
  35. Do not instantiate directly. Use the :func:`new` function.
  36. :ivar digest_size: the size in bytes of the resulting MAC tag
  37. :vartype digest_size: integer
  38. """
  39. digest_size = None
  40. def __init__(self, key, msg, ciphermod, cipher_params, mac_len,
  41. update_after_digest):
  42. self.digest_size = mac_len
  43. self._key = _copy_bytes(None, None, key)
  44. self._factory = ciphermod
  45. self._cipher_params = cipher_params
  46. self._block_size = bs = ciphermod.block_size
  47. self._mac_tag = None
  48. self._update_after_digest = update_after_digest
  49. # Section 5.3 of NIST SP 800 38B and Appendix B
  50. if bs == 8:
  51. const_Rb = 0x1B
  52. self._max_size = 8 * (2 ** 21)
  53. elif bs == 16:
  54. const_Rb = 0x87
  55. self._max_size = 16 * (2 ** 48)
  56. else:
  57. raise TypeError("CMAC requires a cipher with a block size"
  58. " of 8 or 16 bytes, not %d" % bs)
  59. # Compute sub-keys
  60. zero_block = b'\x00' * bs
  61. self._ecb = ciphermod.new(key,
  62. ciphermod.MODE_ECB,
  63. **self._cipher_params)
  64. L = self._ecb.encrypt(zero_block)
  65. if bord(L[0]) & 0x80:
  66. self._k1 = _shift_bytes(L, const_Rb)
  67. else:
  68. self._k1 = _shift_bytes(L)
  69. if bord(self._k1[0]) & 0x80:
  70. self._k2 = _shift_bytes(self._k1, const_Rb)
  71. else:
  72. self._k2 = _shift_bytes(self._k1)
  73. # Initialize CBC cipher with zero IV
  74. self._cbc = ciphermod.new(key,
  75. ciphermod.MODE_CBC,
  76. zero_block,
  77. **self._cipher_params)
  78. # Cache for outstanding data to authenticate
  79. self._cache = bytearray(bs)
  80. self._cache_n = 0
  81. # Last piece of ciphertext produced
  82. self._last_ct = zero_block
  83. # Last block that was encrypted with AES
  84. self._last_pt = None
  85. # Counter for total message size
  86. self._data_size = 0
  87. if msg:
  88. self.update(msg)
  89. def update(self, msg):
  90. """Authenticate the next chunk of message.
  91. Args:
  92. data (byte string/byte array/memoryview): The next chunk of data
  93. """
  94. if self._mac_tag is not None and not self._update_after_digest:
  95. raise TypeError("update() cannot be called after digest() or verify()")
  96. self._data_size += len(msg)
  97. bs = self._block_size
  98. if self._cache_n > 0:
  99. filler = min(bs - self._cache_n, len(msg))
  100. self._cache[self._cache_n:self._cache_n+filler] = msg[:filler]
  101. self._cache_n += filler
  102. if self._cache_n < bs:
  103. return self
  104. msg = memoryview(msg)[filler:]
  105. self._update(self._cache)
  106. self._cache_n = 0
  107. remain = len(msg) % bs
  108. if remain > 0:
  109. self._update(msg[:-remain])
  110. self._cache[:remain] = msg[-remain:]
  111. else:
  112. self._update(msg)
  113. self._cache_n = remain
  114. return self
  115. def _update(self, data_block):
  116. """Update a block aligned to the block boundary"""
  117. bs = self._block_size
  118. assert len(data_block) % bs == 0
  119. if len(data_block) == 0:
  120. return
  121. ct = self._cbc.encrypt(data_block)
  122. if len(data_block) == bs:
  123. second_last = self._last_ct
  124. else:
  125. second_last = ct[-bs*2:-bs]
  126. self._last_ct = ct[-bs:]
  127. self._last_pt = strxor(second_last, data_block[-bs:])
  128. def copy(self):
  129. """Return a copy ("clone") of the CMAC object.
  130. The copy will have the same internal state as the original CMAC
  131. object.
  132. This can be used to efficiently compute the MAC tag of byte
  133. strings that share a common initial substring.
  134. :return: An :class:`CMAC`
  135. """
  136. obj = self.__new__(CMAC)
  137. obj.__dict__ = self.__dict__.copy()
  138. obj._cbc = self._factory.new(self._key,
  139. self._factory.MODE_CBC,
  140. self._last_ct,
  141. **self._cipher_params)
  142. obj._cache = self._cache[:]
  143. obj._last_ct = self._last_ct[:]
  144. return obj
  145. def digest(self):
  146. """Return the **binary** (non-printable) MAC tag of the message
  147. that has been authenticated so far.
  148. :return: The MAC tag, computed over the data processed so far.
  149. Binary form.
  150. :rtype: byte string
  151. """
  152. bs = self._block_size
  153. if self._mac_tag is not None and not self._update_after_digest:
  154. return self._mac_tag
  155. if self._data_size > self._max_size:
  156. raise ValueError("MAC is unsafe for this message")
  157. if self._cache_n == 0 and self._data_size > 0:
  158. # Last block was full
  159. pt = strxor(self._last_pt, self._k1)
  160. else:
  161. # Last block is partial (or message length is zero)
  162. partial = self._cache[:]
  163. partial[self._cache_n:] = b'\x80' + b'\x00' * (bs - self._cache_n - 1)
  164. pt = strxor(strxor(self._last_ct, partial), self._k2)
  165. self._mac_tag = self._ecb.encrypt(pt)[:self.digest_size]
  166. return self._mac_tag
  167. def hexdigest(self):
  168. """Return the **printable** MAC tag of the message authenticated so far.
  169. :return: The MAC tag, computed over the data processed so far.
  170. Hexadecimal encoded.
  171. :rtype: string
  172. """
  173. return "".join(["%02x" % bord(x)
  174. for x in tuple(self.digest())])
  175. def verify(self, mac_tag):
  176. """Verify that a given **binary** MAC (computed by another party)
  177. is valid.
  178. Args:
  179. mac_tag (byte string/byte array/memoryview): the expected MAC of the message.
  180. Raises:
  181. ValueError: if the MAC does not match. It means that the message
  182. has been tampered with or that the MAC key is incorrect.
  183. """
  184. secret = get_random_bytes(16)
  185. mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=mac_tag)
  186. mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=self.digest())
  187. if mac1.digest() != mac2.digest():
  188. raise ValueError("MAC check failed")
  189. def hexverify(self, hex_mac_tag):
  190. """Return the **printable** MAC tag of the message authenticated so far.
  191. :return: The MAC tag, computed over the data processed so far.
  192. Hexadecimal encoded.
  193. :rtype: string
  194. """
  195. self.verify(unhexlify(tobytes(hex_mac_tag)))
  196. def new(key, msg=None, ciphermod=None, cipher_params=None, mac_len=None,
  197. update_after_digest=False):
  198. """Create a new MAC object.
  199. Args:
  200. key (byte string/byte array/memoryview):
  201. key for the CMAC object.
  202. The key must be valid for the underlying cipher algorithm.
  203. For instance, it must be 16 bytes long for AES-128.
  204. ciphermod (module):
  205. A cipher module from :mod:`Cryptodome.Cipher`.
  206. The cipher's block size has to be 128 bits,
  207. like :mod:`Cryptodome.Cipher.AES`, to reduce the probability
  208. of collisions.
  209. msg (byte string/byte array/memoryview):
  210. Optional. The very first chunk of the message to authenticate.
  211. It is equivalent to an early call to `CMAC.update`. Optional.
  212. cipher_params (dict):
  213. Optional. A set of parameters to use when instantiating a cipher
  214. object.
  215. mac_len (integer):
  216. Length of the MAC, in bytes.
  217. It must be at least 4 bytes long.
  218. The default (and recommended) length matches the size of a cipher block.
  219. update_after_digest (boolean):
  220. Optional. By default, a hash object cannot be updated anymore after
  221. the digest is computed. When this flag is ``True``, such check
  222. is no longer enforced.
  223. Returns:
  224. A :class:`CMAC` object
  225. """
  226. if ciphermod is None:
  227. raise TypeError("ciphermod must be specified (try AES)")
  228. cipher_params = {} if cipher_params is None else dict(cipher_params)
  229. if mac_len is None:
  230. mac_len = ciphermod.block_size
  231. if mac_len < 4:
  232. raise ValueError("MAC tag length must be at least 4 bytes long")
  233. if mac_len > ciphermod.block_size:
  234. raise ValueError("MAC tag length cannot be larger than a cipher block (%d) bytes" % ciphermod.block_size)
  235. return CMAC(key, msg, ciphermod, cipher_params, mac_len,
  236. update_after_digest)