Debian Codegraph @

lib/Crypto/Hash/cSHAKE128.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.py3compat import bchr, concat_buffers
32
33 from Crypto.Util._raw_api import (VoidPointer, SmartPointer,
34 create_string_buffer,
35 get_raw_buffer, c_size_t,
36 c_uint8_ptr, c_ubyte)
37
38 from Crypto.Util.number import long_to_bytes
39
40 from Crypto.Hash.keccak import _raw_keccak_lib
41
42
43 def _left_encode(x):
44 """Left encode function as defined in NIST SP 800-185"""
45
46 assert (x < (1 << 2040) and x >= 0)
47
48 # Get number of bytes needed to represent this integer.
49 num = 1 if x == 0 else (x.bit_length() + 7) // 8
50
51 return bchr(num) + long_to_bytes(x)
52
53
54 def _right_encode(x):
55 """Right encode function as defined in NIST SP 800-185"""
56
57 assert (x < (1 << 2040) and x >= 0)
58
59 # Get number of bytes needed to represent this integer.
60 num = 1 if x == 0 else (x.bit_length() + 7) // 8
61
62 return long_to_bytes(x) + bchr(num)
63
64
65 def _encode_str(x):
66 """Encode string function as defined in NIST SP 800-185"""
67
68 bitlen = len(x) * 8
69 if bitlen >= (1 << 2040):
70 raise ValueError("String too large to encode in cSHAKE")
71
72 return concat_buffers(_left_encode(bitlen), x)
73
74
75 def _bytepad(x, length):
76 """Zero pad byte string as defined in NIST SP 800-185"""
77
78 to_pad = concat_buffers(_left_encode(length), x)
79
80 # Note: this implementation works with byte aligned strings,
81 # hence no additional bit padding is needed at this point.
82 npad = (length - len(to_pad) % length) % length
83
84 return to_pad + b'\x00' * npad
85
86
87 class cSHAKE_XOF(object):
88 """A cSHAKE hash object.
89 Do not instantiate directly.
90 Use the :func:`new` function.
91 """
92
93 def __init__(self, data, custom, capacity, function):
94 state = VoidPointer()
95
96 if custom or function:
97 prefix_unpad = _encode_str(function) + _encode_str(custom)
98 prefix = _bytepad(prefix_unpad, (1600 - capacity)//8)
99 self._padding = 0x04
100 else:
101 prefix = None
102 self._padding = 0x1F # for SHAKE
103
104 result = _raw_keccak_lib.keccak_init(state.address_of(),
105 c_size_t(capacity//8),
106 c_ubyte(24))
107 if result:
108 raise ValueError("Error %d while instantiating cSHAKE"
109 % result)
110 self._state = SmartPointer(state.get(),
111 _raw_keccak_lib.keccak_destroy)
112 self._is_squeezing = False
113
114 if prefix:
115 self.update(prefix)
116
117 if data:
118 self.update(data)
119
120 def update(self, data):
121 """Continue hashing of a message by consuming the next chunk of data.
122
123 Args:
124 data (byte string/byte array/memoryview): The next chunk of the message being hashed.
125 """
126
127 if self._is_squeezing:
128 raise TypeError("You cannot call 'update' after the first 'read'")
129
130 result = _raw_keccak_lib.keccak_absorb(self._state.get(),
131 c_uint8_ptr(data),
132 c_size_t(len(data)))
133 if result:
134 raise ValueError("Error %d while updating %s state"
135 % (result, self.name))
136 return self
137
138 def read(self, length):
139 """
140 Compute the next piece of XOF output.
141
142 .. note::
143 You cannot use :meth:`update` anymore after the first call to
144 :meth:`read`.
145
146 Args:
147 length (integer): the amount of bytes this method must return
148
149 :return: the next piece of XOF output (of the given length)
150 :rtype: byte string
151 """
152
153 self._is_squeezing = True
154 bfr = create_string_buffer(length)
155 result = _raw_keccak_lib.keccak_squeeze(self._state.get(),
156 bfr,
157 c_size_t(length),
158 c_ubyte(self._padding))
159 if result:
160 raise ValueError("Error %d while extracting from %s"
161 % (result, self.name))
162
163 return get_raw_buffer(bfr)
164
165
166 def _new(data, custom, function):
167 # Use Keccak[256]
168 return cSHAKE_XOF(data, custom, 256, function)
169
170
171 def new(data=None, custom=None):
172 """Return a fresh instance of a cSHAKE128 object.
173
174 Args:
175 data (bytes/bytearray/memoryview):
176 Optional.
177 The very first chunk of the message to hash.
178 It is equivalent to an early call to :meth:`update`.
179 custom (bytes):
180 Optional.
181 A customization bytestring (``S`` in SP 800-185).
182
183 :Return: A :class:`cSHAKE_XOF` object
184 """
185
186 # Use Keccak[256]
187 return cSHAKE_XOF(data, custom, 256, b'')