Debian Codegraph @

lib/Crypto/Hash/KangarooTwelve.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 Crypto.Util.number import long_to_bytes
32 from Crypto.Util.py3compat import bchr
33
34 from . import TurboSHAKE128
35
36 def _length_encode(x):
37 if x == 0:
38 return b'\x00'
39
40 S = long_to_bytes(x)
41 return S + bchr(len(S))
42
43
44 # Possible states for a KangarooTwelve instance, which depend on the amount of data processed so far.
45 SHORT_MSG = 1 # Still within the first 8192 bytes, but it is not certain we will exceed them.
46 LONG_MSG_S0 = 2 # Still within the first 8192 bytes, and it is certain we will exceed them.
47 LONG_MSG_SX = 3 # Beyond the first 8192 bytes.
48 SQUEEZING = 4 # No more data to process.
49
50
51 class K12_XOF(object):
52 """A KangarooTwelve hash object.
53 Do not instantiate directly.
54 Use the :func:`new` function.
55 """
56
57 def __init__(self, data, custom):
58
59 if custom == None:
60 custom = b''
61
62 self._custom = custom + _length_encode(len(custom))
63 self._state = SHORT_MSG
64 self._padding = None # Final padding is only decided in read()
65
66 # Internal hash that consumes FinalNode
67 # The real domain separation byte will be known before squeezing
68 self._hash1 = TurboSHAKE128.new(domain=1)
69 self._length1 = 0
70
71 # Internal hash that produces CV_i (reset each time)
72 self._hash2 = None
73 self._length2 = 0
74
75 # Incremented by one for each 8192-byte block
76 self._ctr = 0
77
78 if data:
79 self.update(data)
80
81 def update(self, data):
82 """Hash the next piece of data.
83
84 .. note::
85 For better performance, submit chunks with a length multiple of 8192 bytes.
86
87 Args:
88 data (byte string/byte array/memoryview): The next chunk of the
89 message to hash.
90 """
91
92 if self._state == SQUEEZING:
93 raise TypeError("You cannot call 'update' after the first 'read'")
94
95 if self._state == SHORT_MSG:
96 next_length = self._length1 + len(data)
97
98 if next_length + len(self._custom) <= 8192:
99 self._length1 = next_length
100 self._hash1.update(data)
101 return self
102
103 # Switch to tree hashing
104 self._state = LONG_MSG_S0
105
106 if self._state == LONG_MSG_S0:
107 data_mem = memoryview(data)
108 assert(self._length1 < 8192)
109 dtc = min(len(data), 8192 - self._length1)
110 self._hash1.update(data_mem[:dtc])
111 self._length1 += dtc
112
113 if self._length1 < 8192:
114 return self
115
116 # Finish hashing S_0 and start S_1
117 assert(self._length1 == 8192)
118
119 divider = b'\x03' + b'\x00' * 7
120 self._hash1.update(divider)
121 self._length1 += 8
122
123 self._hash2 = TurboSHAKE128.new(domain=0x0B)
124 self._length2 = 0
125 self._ctr = 1
126
127 self._state = LONG_MSG_SX
128 return self.update(data_mem[dtc:])
129
130 # LONG_MSG_SX
131 assert(self._state == LONG_MSG_SX)
132 index = 0
133 len_data = len(data)
134
135 # All iteractions could actually run in parallel
136 data_mem = memoryview(data)
137 while index < len_data:
138
139 new_index = min(index + 8192 - self._length2, len_data)
140 self._hash2.update(data_mem[index:new_index])
141 self._length2 += new_index - index
142 index = new_index
143
144 if self._length2 == 8192:
145 cv_i = self._hash2.read(32)
146 self._hash1.update(cv_i)
147 self._length1 += 32
148 self._hash2._reset()
149 self._length2 = 0
150 self._ctr += 1
151
152 return self
153
154 def read(self, length):
155 """
156 Produce more bytes of the digest.
157
158 .. note::
159 You cannot use :meth:`update` anymore after the first call to
160 :meth:`read`.
161
162 Args:
163 length (integer): the amount of bytes this method must return
164
165 :return: the next piece of XOF output (of the given length)
166 :rtype: byte string
167 """
168
169 custom_was_consumed = False
170
171 if self._state == SHORT_MSG:
172 self._hash1.update(self._custom)
173 self._padding = 0x07
174 self._state = SQUEEZING
175
176 if self._state == LONG_MSG_S0:
177 self.update(self._custom)
178 custom_was_consumed = True
179 assert(self._state == LONG_MSG_SX)
180
181 if self._state == LONG_MSG_SX:
182 if not custom_was_consumed:
183 self.update(self._custom)
184
185 # Is there still some leftover data in hash2?
186 if self._length2 > 0:
187 cv_i = self._hash2.read(32)
188 self._hash1.update(cv_i)
189 self._length1 += 32
190 self._hash2._reset()
191 self._length2 = 0
192 self._ctr += 1
193
194 trailer = _length_encode(self._ctr - 1) + b'\xFF\xFF'
195 self._hash1.update(trailer)
196
197 self._padding = 0x06
198 self._state = SQUEEZING
199
200 self._hash1._domain = self._padding
201 return self._hash1.read(length)
202
203 def new(self, data=None, custom=b''):
204 return type(self)(data, custom)
205
206
207 def new(data=None, custom=None):
208 """Return a fresh instance of a KangarooTwelve object.
209
210 Args:
211 data (bytes/bytearray/memoryview):
212 Optional.
213 The very first chunk of the message to hash.
214 It is equivalent to an early call to :meth:`update`.
215 custom (bytes):
216 Optional.
217 A customization byte string.
218
219 :Return: A :class:`K12_XOF` object
220 """
221
222 return K12_XOF(data, custom)