CMAC.py 10 KB

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