KMAC128.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2021, Legrandin <helderijs@gmail.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. #
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # 2. Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in
  14. # the documentation and/or other materials provided with the
  15. # distribution.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  20. # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  21. # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  23. # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  27. # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. # POSSIBILITY OF SUCH DAMAGE.
  29. # ===================================================================
  30. from binascii import unhexlify
  31. from Crypto.Util.py3compat import bord, tobytes, is_bytes
  32. from Crypto.Random import get_random_bytes
  33. from . import cSHAKE128, SHA3_256
  34. from .cSHAKE128 import _bytepad, _encode_str, _right_encode
  35. class KMAC_Hash(object):
  36. """A KMAC hash object.
  37. Do not instantiate directly.
  38. Use the :func:`new` function.
  39. """
  40. def __init__(self, data, key, mac_len, custom,
  41. oid_variant, cshake, rate):
  42. # See https://tools.ietf.org/html/rfc8702
  43. self.oid = "2.16.840.1.101.3.4.2." + oid_variant
  44. self.digest_size = mac_len
  45. self._mac = None
  46. partial_newX = _bytepad(_encode_str(tobytes(key)), rate)
  47. self._cshake = cshake._new(partial_newX, custom, b"KMAC")
  48. if data:
  49. self._cshake.update(data)
  50. def update(self, data):
  51. """Authenticate the next chunk of message.
  52. Args:
  53. data (bytes/bytearray/memoryview): The next chunk of the message to
  54. authenticate.
  55. """
  56. if self._mac:
  57. raise TypeError("You can only call 'digest' or 'hexdigest' on this object")
  58. self._cshake.update(data)
  59. return self
  60. def digest(self):
  61. """Return the **binary** (non-printable) MAC tag of the message.
  62. :return: The MAC tag. Binary form.
  63. :rtype: byte string
  64. """
  65. if not self._mac:
  66. self._cshake.update(_right_encode(self.digest_size * 8))
  67. self._mac = self._cshake.read(self.digest_size)
  68. return self._mac
  69. def hexdigest(self):
  70. """Return the **printable** MAC tag of the message.
  71. :return: The MAC tag. Hexadecimal encoded.
  72. :rtype: string
  73. """
  74. return "".join(["%02x" % bord(x) for x in tuple(self.digest())])
  75. def verify(self, mac_tag):
  76. """Verify that a given **binary** MAC (computed by another party)
  77. is valid.
  78. Args:
  79. mac_tag (bytes/bytearray/memoryview): the expected MAC of the message.
  80. Raises:
  81. ValueError: if the MAC does not match. It means that the message
  82. has been tampered with or that the MAC key is incorrect.
  83. """
  84. secret = get_random_bytes(16)
  85. mac1 = SHA3_256.new(secret + mac_tag)
  86. mac2 = SHA3_256.new(secret + self.digest())
  87. if mac1.digest() != mac2.digest():
  88. raise ValueError("MAC check failed")
  89. def hexverify(self, hex_mac_tag):
  90. """Verify that a given **printable** MAC (computed by another party)
  91. is valid.
  92. Args:
  93. hex_mac_tag (string): the expected MAC of the message, as a hexadecimal string.
  94. Raises:
  95. ValueError: if the MAC does not match. It means that the message
  96. has been tampered with or that the MAC key is incorrect.
  97. """
  98. self.verify(unhexlify(tobytes(hex_mac_tag)))
  99. def new(self, **kwargs):
  100. """Return a new instance of a KMAC hash object.
  101. See :func:`new`.
  102. """
  103. if "mac_len" not in kwargs:
  104. kwargs["mac_len"] = self.digest_size
  105. return new(**kwargs)
  106. def new(**kwargs):
  107. """Create a new KMAC128 object.
  108. Args:
  109. key (bytes/bytearray/memoryview):
  110. The key to use to compute the MAC.
  111. It must be at least 128 bits long (16 bytes).
  112. data (bytes/bytearray/memoryview):
  113. Optional. The very first chunk of the message to authenticate.
  114. It is equivalent to an early call to :meth:`KMAC_Hash.update`.
  115. mac_len (integer):
  116. Optional. The size of the authentication tag, in bytes.
  117. Default is 64. Minimum is 8.
  118. custom (bytes/bytearray/memoryview):
  119. Optional. A customization byte string (``S`` in SP 800-185).
  120. Returns:
  121. A :class:`KMAC_Hash` hash object
  122. """
  123. key = kwargs.pop("key", None)
  124. if not is_bytes(key):
  125. raise TypeError("You must pass a key to KMAC128")
  126. if len(key) < 16:
  127. raise ValueError("The key must be at least 128 bits long (16 bytes)")
  128. data = kwargs.pop("data", None)
  129. mac_len = kwargs.pop("mac_len", 64)
  130. if mac_len < 8:
  131. raise ValueError("'mac_len' must be 8 bytes or more")
  132. custom = kwargs.pop("custom", b"")
  133. if kwargs:
  134. raise TypeError("Unknown parameters: " + str(kwargs))
  135. return KMAC_Hash(data, key, mac_len, custom, "19", cSHAKE128, 168)