Debian Codegraph @

lib/Crypto/Hash/BLAKE2b.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2014, 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
34
35 from Crypto.Random import get_random_bytes
36 from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
37 VoidPointer, SmartPointer,
38 create_string_buffer,
39 get_raw_buffer, c_size_t,
40 c_uint8_ptr)
41
42 _raw_blake2b_lib = load_pycryptodome_raw_lib("Crypto.Hash._BLAKE2b",
43 """
44 int blake2b_init(void **state,
45 const uint8_t *key,
46 size_t key_size,
47 size_t digest_size);
48 int blake2b_destroy(void *state);
49 int blake2b_update(void *state,
50 const uint8_t *buf,
51 size_t len);
52 int blake2b_digest(const void *state,
53 uint8_t digest[64]);
54 int blake2b_copy(const void *src, void *dst);
55 """)
56
57
58 class BLAKE2b_Hash(object):
59 """A BLAKE2b hash object.
60 Do not instantiate directly. Use the :func:`new` function.
61
62 :ivar oid: ASN.1 Object ID
63 :vartype oid: string
64
65 :ivar block_size: the size in bytes of the internal message block,
66 input to the compression function
67 :vartype block_size: integer
68
69 :ivar digest_size: the size in bytes of the resulting hash
70 :vartype digest_size: integer
71 """
72
73 # The internal block size of the hash algorithm in bytes.
74 block_size = 64
75
76 def __init__(self, data, key, digest_bytes, update_after_digest):
77
78 # The size of the resulting hash in bytes.
79 self.digest_size = digest_bytes
80
81 self._update_after_digest = update_after_digest
82 self._digest_done = False
83
84 # See https://tools.ietf.org/html/rfc7693
85 if digest_bytes in (20, 32, 48, 64) and not key:
86 self.oid = "1.3.6.1.4.1.1722.12.2.1." + str(digest_bytes)
87
88 state = VoidPointer()
89 result = _raw_blake2b_lib.blake2b_init(state.address_of(),
90 c_uint8_ptr(key),
91 c_size_t(len(key)),
92 c_size_t(digest_bytes)
93 )
94 if result:
95 raise ValueError("Error %d while instantiating BLAKE2b" % result)
96 self._state = SmartPointer(state.get(),
97 _raw_blake2b_lib.blake2b_destroy)
98 if data:
99 self.update(data)
100
101
102 def update(self, data):
103 """Continue hashing of a message by consuming the next chunk of data.
104
105 Args:
106 data (bytes/bytearray/memoryview): The next chunk of the message being hashed.
107 """
108
109 if self._digest_done and not self._update_after_digest:
110 raise TypeError("You can only call 'digest' or 'hexdigest' on this object")
111
112 result = _raw_blake2b_lib.blake2b_update(self._state.get(),
113 c_uint8_ptr(data),
114 c_size_t(len(data)))
115 if result:
116 raise ValueError("Error %d while hashing BLAKE2b data" % result)
117 return self
118
119
120 def digest(self):
121 """Return the **binary** (non-printable) digest of the message that has been hashed so far.
122
123 :return: The hash digest, computed over the data processed so far.
124 Binary form.
125 :rtype: byte string
126 """
127
128 bfr = create_string_buffer(64)
129 result = _raw_blake2b_lib.blake2b_digest(self._state.get(),
130 bfr)
131 if result:
132 raise ValueError("Error %d while creating BLAKE2b digest" % result)
133
134 self._digest_done = True
135
136 return get_raw_buffer(bfr)[:self.digest_size]
137
138
139 def hexdigest(self):
140 """Return the **printable** digest of the message that has been hashed so far.
141
142 :return: The hash digest, computed over the data processed so far.
143 Hexadecimal encoded.
144 :rtype: string
145 """
146
147 return "".join(["%02x" % bord(x) for x in tuple(self.digest())])
148
149
150 def verify(self, mac_tag):
151 """Verify that a given **binary** MAC (computed by another party)
152 is valid.
153
154 Args:
155 mac_tag (bytes/bytearray/memoryview): the expected MAC of the message.
156
157 Raises:
158 ValueError: if the MAC does not match. It means that the message
159 has been tampered with or that the MAC key is incorrect.
160 """
161
162 secret = get_random_bytes(16)
163
164 mac1 = new(digest_bits=160, key=secret, data=mac_tag)
165 mac2 = new(digest_bits=160, key=secret, data=self.digest())
166
167 if mac1.digest() != mac2.digest():
168 raise ValueError("MAC check failed")
169
170
171 def hexverify(self, hex_mac_tag):
172 """Verify that a given **printable** MAC (computed by another party)
173 is valid.
174
175 Args:
176 hex_mac_tag (string): the expected MAC of the message, as a hexadecimal string.
177
178 Raises:
179 ValueError: if the MAC does not match. It means that the message
180 has been tampered with or that the MAC key is incorrect.
181 """
182
183 self.verify(unhexlify(tobytes(hex_mac_tag)))
184
185
186 def new(self, **kwargs):
187 """Return a new instance of a BLAKE2b hash object.
188 See :func:`new`.
189 """
190
191 if "digest_bytes" not in kwargs and "digest_bits" not in kwargs:
192 kwargs["digest_bytes"] = self.digest_size
193
194 return new(**kwargs)
195
196
197 def new(**kwargs):
198 """Create a new hash object.
199
200 Args:
201 data (bytes/bytearray/memoryview):
202 Optional. The very first chunk of the message to hash.
203 It is equivalent to an early call to :meth:`BLAKE2b_Hash.update`.
204 digest_bytes (integer):
205 Optional. The size of the digest, in bytes (1 to 64). Default is 64.
206 digest_bits (integer):
207 Optional and alternative to ``digest_bytes``.
208 The size of the digest, in bits (8 to 512, in steps of 8).
209 Default is 512.
210 key (bytes/bytearray/memoryview):
211 Optional. The key to use to compute the MAC (1 to 64 bytes).
212 If not specified, no key will be used.
213 update_after_digest (boolean):
214 Optional. By default, a hash object cannot be updated anymore after
215 the digest is computed. When this flag is ``True``, such check
216 is no longer enforced.
217
218 Returns:
219 A :class:`BLAKE2b_Hash` hash object
220 """
221
222 data = kwargs.pop("data", None)
223 update_after_digest = kwargs.pop("update_after_digest", False)
224
225 digest_bytes = kwargs.pop("digest_bytes", None)
226 digest_bits = kwargs.pop("digest_bits", None)
227 if None not in (digest_bytes, digest_bits):
228 raise TypeError("Only one digest parameter must be provided")
229 if (None, None) == (digest_bytes, digest_bits):
230 digest_bytes = 64
231 if digest_bytes is not None:
232 if not (1 <= digest_bytes <= 64):
233 raise ValueError("'digest_bytes' not in range 1..64")
234 else:
235 if not (8 <= digest_bits <= 512) or (digest_bits % 8):
236 raise ValueError("'digest_bits' not in range 8..512, "
237 "with steps of 8")
238 digest_bytes = digest_bits // 8
239
240 key = kwargs.pop("key", b"")
241 if len(key) > 64:
242 raise ValueError("BLAKE2b key cannot exceed 64 bytes")
243
244 if kwargs:
245 raise TypeError("Unknown parameters: " + str(kwargs))
246
247 return BLAKE2b_Hash(data, key, digest_bytes, update_after_digest)