Debian Codegraph @

lib/Crypto/Hash/KMAC128.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2021, Legrandin <[email protected]>
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
31 from binascii import unhexlify
32
33 from Crypto.Util.py3compat import bord, tobytes, is_bytes
34 from Crypto.Random import get_random_bytes
35
36 from . import cSHAKE128, SHA3_256
37 from .cSHAKE128 import _bytepad, _encode_str, _right_encode
38
39
40 class KMAC_Hash(object):
41 """A KMAC hash object.
42 Do not instantiate directly.
43 Use the :func:`new` function.
44 """
45
46 def __init__(self, data, key, mac_len, custom,
47 oid_variant, cshake, rate):
48
49 # See https://tools.ietf.org/html/rfc8702
50 self.oid = "2.16.840.1.101.3.4.2." + oid_variant
51 self.digest_size = mac_len
52
53 self._mac = None
54
55 partial_newX = _bytepad(_encode_str(tobytes(key)), rate)
56 self._cshake = cshake._new(partial_newX, custom, b"KMAC")
57
58 if data:
59 self._cshake.update(data)
60
61 def update(self, data):
62 """Authenticate the next chunk of message.
63
64 Args:
65 data (bytes/bytearray/memoryview): The next chunk of the message to
66 authenticate.
67 """
68
69 if self._mac:
70 raise TypeError("You can only call 'digest' or 'hexdigest' on this object")
71
72 self._cshake.update(data)
73 return self
74
75 def digest(self):
76 """Return the **binary** (non-printable) MAC tag of the message.
77
78 :return: The MAC tag. Binary form.
79 :rtype: byte string
80 """
81
82 if not self._mac:
83 self._cshake.update(_right_encode(self.digest_size * 8))
84 self._mac = self._cshake.read(self.digest_size)
85
86 return self._mac
87
88 def hexdigest(self):
89 """Return the **printable** MAC tag of the message.
90
91 :return: The MAC tag. Hexadecimal encoded.
92 :rtype: string
93 """
94
95 return "".join(["%02x" % bord(x) for x in tuple(self.digest())])
96
97 def verify(self, mac_tag):
98 """Verify that a given **binary** MAC (computed by another party)
99 is valid.
100
101 Args:
102 mac_tag (bytes/bytearray/memoryview): the expected MAC of the message.
103
104 Raises:
105 ValueError: if the MAC does not match. It means that the message
106 has been tampered with or that the MAC key is incorrect.
107 """
108
109 secret = get_random_bytes(16)
110
111 mac1 = SHA3_256.new(secret + mac_tag)
112 mac2 = SHA3_256.new(secret + self.digest())
113
114 if mac1.digest() != mac2.digest():
115 raise ValueError("MAC check failed")
116
117 def hexverify(self, hex_mac_tag):
118 """Verify that a given **printable** MAC (computed by another party)
119 is valid.
120
121 Args:
122 hex_mac_tag (string): the expected MAC of the message, as a hexadecimal string.
123
124 Raises:
125 ValueError: if the MAC does not match. It means that the message
126 has been tampered with or that the MAC key is incorrect.
127 """
128
129 self.verify(unhexlify(tobytes(hex_mac_tag)))
130
131 def new(self, **kwargs):
132 """Return a new instance of a KMAC hash object.
133 See :func:`new`.
134 """
135
136 if "mac_len" not in kwargs:
137 kwargs["mac_len"] = self.digest_size
138
139 return new(**kwargs)
140
141
142 def new(**kwargs):
143 """Create a new KMAC128 object.
144
145 Args:
146 key (bytes/bytearray/memoryview):
147 The key to use to compute the MAC.
148 It must be at least 128 bits long (16 bytes).
149 data (bytes/bytearray/memoryview):
150 Optional. The very first chunk of the message to authenticate.
151 It is equivalent to an early call to :meth:`KMAC_Hash.update`.
152 mac_len (integer):
153 Optional. The size of the authentication tag, in bytes.
154 Default is 64. Minimum is 8.
155 custom (bytes/bytearray/memoryview):
156 Optional. A customization byte string (``S`` in SP 800-185).
157
158 Returns:
159 A :class:`KMAC_Hash` hash object
160 """
161
162 key = kwargs.pop("key", None)
163 if not is_bytes(key):
164 raise TypeError("You must pass a key to KMAC128")
165 if len(key) < 16:
166 raise ValueError("The key must be at least 128 bits long (16 bytes)")
167
168 data = kwargs.pop("data", None)
169
170 mac_len = kwargs.pop("mac_len", 64)
171 if mac_len < 8:
172 raise ValueError("'mac_len' must be 8 bytes or more")
173
174 custom = kwargs.pop("custom", b"")
175
176 if kwargs:
177 raise TypeError("Unknown parameters: " + str(kwargs))
178
179 return KMAC_Hash(data, key, mac_len, custom, "19", cSHAKE128, 168)