1 /* SHA3 module
2 *
3 * This module provides an interface to the SHA3 algorithm
4 *
5 * See below for information about the original code this module was
6 * based upon. Additional work performed by:
7 *
8 * Andrew Kuchling (amk@amk.ca)
9 * Greg Stein (gstein@lyra.org)
10 * Trevor Perrin (trevp@trevp.net)
11 * Gregory P. Smith (greg@krypto.org)
12 *
13 * Copyright (C) 2012-2016 Christian Heimes (christian@python.org)
14 * Licensed to PSF under a Contributor Agreement.
15 *
16 */
17
18 #include "Python.h"
19 #include "pystrhex.h"
20 #include "../hashlib.h"
21
22 /* **************************************************************************
23 * SHA-3 (Keccak) and SHAKE
24 *
25 * The code is based on KeccakCodePackage from 2016-04-23
26 * commit 647f93079afc4ada3d23737477a6e52511ca41fd
27 *
28 * The reference implementation is altered in this points:
29 * - C++ comments are converted to ANSI C comments.
30 * - all function names are mangled
31 * - typedef for UINT64 is commented out.
32 * - brg_endian.h is removed
33 *
34 * *************************************************************************/
35
36 #ifdef __sparc
37 /* opt64 uses un-aligned memory access that causes a BUS error with msg
38 * 'invalid address alignment' on SPARC. */
39 #define KeccakOpt 32
40 #elif PY_BIG_ENDIAN
41 /* opt64 is not yet supported on big endian platforms */
42 #define KeccakOpt 32
43 #elif SIZEOF_VOID_P == 8
44 /* opt64 works only on little-endian 64bit platforms with unsigned int64 */
45 #define KeccakOpt 64
46 #else
47 /* opt32 is used for the remaining 32 and 64bit platforms */
48 #define KeccakOpt 32
49 #endif
50
51 #if KeccakOpt == 64
52 /* 64bit platforms with unsigned int64 */
53 typedef uint64_t UINT64;
54 typedef unsigned char UINT8;
55 #endif
56
57 /* replacement for brg_endian.h */
58 #define IS_LITTLE_ENDIAN 1234
59 #define IS_BIG_ENDIAN 4321
60 #if PY_LITTLE_ENDIAN
61 #define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
62 #endif
63 #if PY_BIG_ENDIAN
64 #define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
65 #endif
66
67 /* mangle names */
68 #define KeccakF1600_FastLoop_Absorb _PySHA3_KeccakF1600_FastLoop_Absorb
69 #define Keccak_HashFinal _PySHA3_Keccak_HashFinal
70 #define Keccak_HashInitialize _PySHA3_Keccak_HashInitialize
71 #define Keccak_HashSqueeze _PySHA3_Keccak_HashSqueeze
72 #define Keccak_HashUpdate _PySHA3_Keccak_HashUpdate
73 #define KeccakP1600_AddBytes _PySHA3_KeccakP1600_AddBytes
74 #define KeccakP1600_AddBytesInLane _PySHA3_KeccakP1600_AddBytesInLane
75 #define KeccakP1600_AddLanes _PySHA3_KeccakP1600_AddLanes
76 #define KeccakP1600_ExtractAndAddBytes _PySHA3_KeccakP1600_ExtractAndAddBytes
77 #define KeccakP1600_ExtractAndAddBytesInLane _PySHA3_KeccakP1600_ExtractAndAddBytesInLane
78 #define KeccakP1600_ExtractAndAddLanes _PySHA3_KeccakP1600_ExtractAndAddLanes
79 #define KeccakP1600_ExtractBytes _PySHA3_KeccakP1600_ExtractBytes
80 #define KeccakP1600_ExtractBytesInLane _PySHA3_KeccakP1600_ExtractBytesInLane
81 #define KeccakP1600_ExtractLanes _PySHA3_KeccakP1600_ExtractLanes
82 #define KeccakP1600_Initialize _PySHA3_KeccakP1600_Initialize
83 #define KeccakP1600_OverwriteBytes _PySHA3_KeccakP1600_OverwriteBytes
84 #define KeccakP1600_OverwriteBytesInLane _PySHA3_KeccakP1600_OverwriteBytesInLane
85 #define KeccakP1600_OverwriteLanes _PySHA3_KeccakP1600_OverwriteLanes
86 #define KeccakP1600_OverwriteWithZeroes _PySHA3_KeccakP1600_OverwriteWithZeroes
87 #define KeccakP1600_Permute_12rounds _PySHA3_KeccakP1600_Permute_12rounds
88 #define KeccakP1600_Permute_24rounds _PySHA3_KeccakP1600_Permute_24rounds
89 #define KeccakWidth1600_Sponge _PySHA3_KeccakWidth1600_Sponge
90 #define KeccakWidth1600_SpongeAbsorb _PySHA3_KeccakWidth1600_SpongeAbsorb
91 #define KeccakWidth1600_SpongeAbsorbLastFewBits _PySHA3_KeccakWidth1600_SpongeAbsorbLastFewBits
92 #define KeccakWidth1600_SpongeInitialize _PySHA3_KeccakWidth1600_SpongeInitialize
93 #define KeccakWidth1600_SpongeSqueeze _PySHA3_KeccakWidth1600_SpongeSqueeze
94 #if KeccakOpt == 32
95 #define KeccakP1600_AddByte _PySHA3_KeccakP1600_AddByte
96 #define KeccakP1600_Permute_Nrounds _PySHA3_KeccakP1600_Permute_Nrounds
97 #define KeccakP1600_SetBytesInLaneToZero _PySHA3_KeccakP1600_SetBytesInLaneToZero
98 #endif
99
100 /* we are only interested in KeccakP1600 */
101 #define KeccakP200_excluded 1
102 #define KeccakP400_excluded 1
103 #define KeccakP800_excluded 1
104
105 /* inline all Keccak dependencies */
106 #include "kcp/KeccakHash.h"
107 #include "kcp/KeccakSponge.h"
108 #include "kcp/KeccakHash.c"
109 #include "kcp/KeccakSponge.c"
110 #if KeccakOpt == 64
111 #include "kcp/KeccakP-1600-opt64.c"
112 #elif KeccakOpt == 32
113 #include "kcp/KeccakP-1600-inplace32BI.c"
114 #endif
115
116 #define SHA3_MAX_DIGESTSIZE 64 /* 64 Bytes (512 Bits) for 224 to 512 */
117 #define SHA3_LANESIZE (20 * 8) /* ExtractLane needs max uint64_t[20] extra. */
118 #define SHA3_state Keccak_HashInstance
119 #define SHA3_init Keccak_HashInitialize
120 #define SHA3_process Keccak_HashUpdate
121 #define SHA3_done Keccak_HashFinal
122 #define SHA3_squeeze Keccak_HashSqueeze
123 #define SHA3_copystate(dest, src) memcpy(&(dest), &(src), sizeof(SHA3_state))
124
125
126 /*[clinic input]
127 module _sha3
128 class _sha3.sha3_224 "SHA3object *" "&SHA3_224typ"
129 class _sha3.sha3_256 "SHA3object *" "&SHA3_256typ"
130 class _sha3.sha3_384 "SHA3object *" "&SHA3_384typ"
131 class _sha3.sha3_512 "SHA3object *" "&SHA3_512typ"
132 class _sha3.shake_128 "SHA3object *" "&SHAKE128type"
133 class _sha3.shake_256 "SHA3object *" "&SHAKE256type"
134 [clinic start generated code]*/
135 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=b8a53680f370285a]*/
136
137 /* The structure for storing SHA3 info */
138
139 typedef struct {
140 PyObject_HEAD
141 SHA3_state hash_state;
142 PyThread_type_lock lock;
143 } SHA3object;
144
145 static PyTypeObject SHA3_224type;
146 static PyTypeObject SHA3_256type;
147 static PyTypeObject SHA3_384type;
148 static PyTypeObject SHA3_512type;
149 #ifdef PY_WITH_KECCAK
150 static PyTypeObject Keccak_224type;
151 static PyTypeObject Keccak_256type;
152 static PyTypeObject Keccak_384type;
153 static PyTypeObject Keccak_512type;
154 #endif
155 static PyTypeObject SHAKE128type;
156 static PyTypeObject SHAKE256type;
157
158 #include "clinic/sha3module.c.h"
159
160 static SHA3object *
newSHA3object(PyTypeObject * type)161 newSHA3object(PyTypeObject *type)
162 {
163 SHA3object *newobj;
164 newobj = (SHA3object *)PyObject_New(SHA3object, type);
165 if (newobj == NULL) {
166 return NULL;
167 }
168 newobj->lock = NULL;
169 return newobj;
170 }
171
172 /*[clinic input]
173 @classmethod
174 _sha3.sha3_224.__new__ as py_sha3_new
175 data: object(c_default="NULL") = b''
176 /
177 *
178 usedforsecurity: bool = True
179
180 Return a new BLAKE2b hash object.
181 [clinic start generated code]*/
182
183 static PyObject *
py_sha3_new_impl(PyTypeObject * type,PyObject * data,int usedforsecurity)184 py_sha3_new_impl(PyTypeObject *type, PyObject *data, int usedforsecurity)
185 /*[clinic end generated code: output=90409addc5d5e8b0 input=bcfcdf2e4368347a]*/
186 {
187 SHA3object *self = NULL;
188 Py_buffer buf = {NULL, NULL};
189 HashReturn res;
190
191 self = newSHA3object(type);
192 if (self == NULL) {
193 goto error;
194 }
195
196 if (type == &SHA3_224type) {
197 res = Keccak_HashInitialize_SHA3_224(&self->hash_state);
198 } else if (type == &SHA3_256type) {
199 res = Keccak_HashInitialize_SHA3_256(&self->hash_state);
200 } else if (type == &SHA3_384type) {
201 res = Keccak_HashInitialize_SHA3_384(&self->hash_state);
202 } else if (type == &SHA3_512type) {
203 res = Keccak_HashInitialize_SHA3_512(&self->hash_state);
204 #ifdef PY_WITH_KECCAK
205 } else if (type == &Keccak_224type) {
206 res = Keccak_HashInitialize(&self->hash_state, 1152, 448, 224, 0x01);
207 } else if (type == &Keccak_256type) {
208 res = Keccak_HashInitialize(&self->hash_state, 1088, 512, 256, 0x01);
209 } else if (type == &Keccak_384type) {
210 res = Keccak_HashInitialize(&self->hash_state, 832, 768, 384, 0x01);
211 } else if (type == &Keccak_512type) {
212 res = Keccak_HashInitialize(&self->hash_state, 576, 1024, 512, 0x01);
213 #endif
214 } else if (type == &SHAKE128type) {
215 res = Keccak_HashInitialize_SHAKE128(&self->hash_state);
216 } else if (type == &SHAKE256type) {
217 res = Keccak_HashInitialize_SHAKE256(&self->hash_state);
218 } else {
219 PyErr_BadInternalCall();
220 goto error;
221 }
222
223 if (data) {
224 GET_BUFFER_VIEW_OR_ERROR(data, &buf, goto error);
225 if (buf.len >= HASHLIB_GIL_MINSIZE) {
226 /* invariant: New objects can't be accessed by other code yet,
227 * thus it's safe to release the GIL without locking the object.
228 */
229 Py_BEGIN_ALLOW_THREADS
230 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
231 Py_END_ALLOW_THREADS
232 }
233 else {
234 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
235 }
236 if (res != SUCCESS) {
237 PyErr_SetString(PyExc_RuntimeError,
238 "internal error in SHA3 Update()");
239 goto error;
240 }
241 PyBuffer_Release(&buf);
242 }
243
244 return (PyObject *)self;
245
246 error:
247 if (self) {
248 Py_DECREF(self);
249 }
250 if (data && buf.obj) {
251 PyBuffer_Release(&buf);
252 }
253 return NULL;
254 }
255
256
257 /* Internal methods for a hash object */
258
259 static void
SHA3_dealloc(SHA3object * self)260 SHA3_dealloc(SHA3object *self)
261 {
262 if (self->lock) {
263 PyThread_free_lock(self->lock);
264 }
265 PyObject_Del(self);
266 }
267
268
269 /* External methods for a hash object */
270
271
272 /*[clinic input]
273 _sha3.sha3_224.copy
274
275 Return a copy of the hash object.
276 [clinic start generated code]*/
277
278 static PyObject *
_sha3_sha3_224_copy_impl(SHA3object * self)279 _sha3_sha3_224_copy_impl(SHA3object *self)
280 /*[clinic end generated code: output=6c537411ecdcda4c input=93a44aaebea51ba8]*/
281 {
282 SHA3object *newobj;
283
284 if ((newobj = newSHA3object(Py_TYPE(self))) == NULL) {
285 return NULL;
286 }
287 ENTER_HASHLIB(self);
288 SHA3_copystate(newobj->hash_state, self->hash_state);
289 LEAVE_HASHLIB(self);
290 return (PyObject *)newobj;
291 }
292
293
294 /*[clinic input]
295 _sha3.sha3_224.digest
296
297 Return the digest value as a bytes object.
298 [clinic start generated code]*/
299
300 static PyObject *
_sha3_sha3_224_digest_impl(SHA3object * self)301 _sha3_sha3_224_digest_impl(SHA3object *self)
302 /*[clinic end generated code: output=fd531842e20b2d5b input=5b2a659536bbd248]*/
303 {
304 unsigned char digest[SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE];
305 SHA3_state temp;
306 HashReturn res;
307
308 ENTER_HASHLIB(self);
309 SHA3_copystate(temp, self->hash_state);
310 LEAVE_HASHLIB(self);
311 res = SHA3_done(&temp, digest);
312 if (res != SUCCESS) {
313 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Final()");
314 return NULL;
315 }
316 return PyBytes_FromStringAndSize((const char *)digest,
317 self->hash_state.fixedOutputLength / 8);
318 }
319
320
321 /*[clinic input]
322 _sha3.sha3_224.hexdigest
323
324 Return the digest value as a string of hexadecimal digits.
325 [clinic start generated code]*/
326
327 static PyObject *
_sha3_sha3_224_hexdigest_impl(SHA3object * self)328 _sha3_sha3_224_hexdigest_impl(SHA3object *self)
329 /*[clinic end generated code: output=75ad03257906918d input=2d91bb6e0d114ee3]*/
330 {
331 unsigned char digest[SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE];
332 SHA3_state temp;
333 HashReturn res;
334
335 /* Get the raw (binary) digest value */
336 ENTER_HASHLIB(self);
337 SHA3_copystate(temp, self->hash_state);
338 LEAVE_HASHLIB(self);
339 res = SHA3_done(&temp, digest);
340 if (res != SUCCESS) {
341 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Final()");
342 return NULL;
343 }
344 return _Py_strhex((const char *)digest,
345 self->hash_state.fixedOutputLength / 8);
346 }
347
348
349 /*[clinic input]
350 _sha3.sha3_224.update
351
352 data: object
353 /
354
355 Update this hash object's state with the provided bytes-like object.
356 [clinic start generated code]*/
357
358 static PyObject *
_sha3_sha3_224_update(SHA3object * self,PyObject * data)359 _sha3_sha3_224_update(SHA3object *self, PyObject *data)
360 /*[clinic end generated code: output=d3223352286ed357 input=a887f54dcc4ae227]*/
361 {
362 Py_buffer buf;
363 HashReturn res;
364
365 GET_BUFFER_VIEW_OR_ERROUT(data, &buf);
366
367 /* add new data, the function takes the length in bits not bytes */
368 if (self->lock == NULL && buf.len >= HASHLIB_GIL_MINSIZE) {
369 self->lock = PyThread_allocate_lock();
370 }
371 /* Once a lock exists all code paths must be synchronized. We have to
372 * release the GIL even for small buffers as acquiring the lock may take
373 * an unlimited amount of time when another thread updates this object
374 * with lots of data. */
375 if (self->lock) {
376 Py_BEGIN_ALLOW_THREADS
377 PyThread_acquire_lock(self->lock, 1);
378 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
379 PyThread_release_lock(self->lock);
380 Py_END_ALLOW_THREADS
381 }
382 else {
383 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
384 }
385
386 if (res != SUCCESS) {
387 PyBuffer_Release(&buf);
388 PyErr_SetString(PyExc_RuntimeError,
389 "internal error in SHA3 Update()");
390 return NULL;
391 }
392
393 PyBuffer_Release(&buf);
394 Py_RETURN_NONE;
395 }
396
397
398 static PyMethodDef SHA3_methods[] = {
399 _SHA3_SHA3_224_COPY_METHODDEF
400 _SHA3_SHA3_224_DIGEST_METHODDEF
401 _SHA3_SHA3_224_HEXDIGEST_METHODDEF
402 _SHA3_SHA3_224_UPDATE_METHODDEF
403 {NULL, NULL} /* sentinel */
404 };
405
406
407 static PyObject *
SHA3_get_block_size(SHA3object * self,void * closure)408 SHA3_get_block_size(SHA3object *self, void *closure)
409 {
410 int rate = self->hash_state.sponge.rate;
411 return PyLong_FromLong(rate / 8);
412 }
413
414
415 static PyObject *
SHA3_get_name(SHA3object * self,void * closure)416 SHA3_get_name(SHA3object *self, void *closure)
417 {
418 PyTypeObject *type = Py_TYPE(self);
419 if (type == &SHA3_224type) {
420 return PyUnicode_FromString("sha3_224");
421 } else if (type == &SHA3_256type) {
422 return PyUnicode_FromString("sha3_256");
423 } else if (type == &SHA3_384type) {
424 return PyUnicode_FromString("sha3_384");
425 } else if (type == &SHA3_512type) {
426 return PyUnicode_FromString("sha3_512");
427 #ifdef PY_WITH_KECCAK
428 } else if (type == &Keccak_224type) {
429 return PyUnicode_FromString("keccak_224");
430 } else if (type == &Keccak_256type) {
431 return PyUnicode_FromString("keccak_256");
432 } else if (type == &Keccak_384type) {
433 return PyUnicode_FromString("keccak_384");
434 } else if (type == &Keccak_512type) {
435 return PyUnicode_FromString("keccak_512");
436 #endif
437 } else if (type == &SHAKE128type) {
438 return PyUnicode_FromString("shake_128");
439 } else if (type == &SHAKE256type) {
440 return PyUnicode_FromString("shake_256");
441 } else {
442 PyErr_BadInternalCall();
443 return NULL;
444 }
445 }
446
447
448 static PyObject *
SHA3_get_digest_size(SHA3object * self,void * closure)449 SHA3_get_digest_size(SHA3object *self, void *closure)
450 {
451 return PyLong_FromLong(self->hash_state.fixedOutputLength / 8);
452 }
453
454
455 static PyObject *
SHA3_get_capacity_bits(SHA3object * self,void * closure)456 SHA3_get_capacity_bits(SHA3object *self, void *closure)
457 {
458 int capacity = 1600 - self->hash_state.sponge.rate;
459 return PyLong_FromLong(capacity);
460 }
461
462
463 static PyObject *
SHA3_get_rate_bits(SHA3object * self,void * closure)464 SHA3_get_rate_bits(SHA3object *self, void *closure)
465 {
466 unsigned int rate = self->hash_state.sponge.rate;
467 return PyLong_FromLong(rate);
468 }
469
470 static PyObject *
SHA3_get_suffix(SHA3object * self,void * closure)471 SHA3_get_suffix(SHA3object *self, void *closure)
472 {
473 unsigned char suffix[2];
474 suffix[0] = self->hash_state.delimitedSuffix;
475 suffix[1] = 0;
476 return PyBytes_FromStringAndSize((const char *)suffix, 1);
477 }
478
479
480 static PyGetSetDef SHA3_getseters[] = {
481 {"block_size", (getter)SHA3_get_block_size, NULL, NULL, NULL},
482 {"name", (getter)SHA3_get_name, NULL, NULL, NULL},
483 {"digest_size", (getter)SHA3_get_digest_size, NULL, NULL, NULL},
484 {"_capacity_bits", (getter)SHA3_get_capacity_bits, NULL, NULL, NULL},
485 {"_rate_bits", (getter)SHA3_get_rate_bits, NULL, NULL, NULL},
486 {"_suffix", (getter)SHA3_get_suffix, NULL, NULL, NULL},
487 {NULL} /* Sentinel */
488 };
489
490
491 #define SHA3_TYPE(type_obj, type_name, type_doc, type_methods) \
492 static PyTypeObject type_obj = { \
493 PyVarObject_HEAD_INIT(NULL, 0) \
494 type_name, /* tp_name */ \
495 sizeof(SHA3object), /* tp_basicsize */ \
496 0, /* tp_itemsize */ \
497 /* methods */ \
498 (destructor)SHA3_dealloc, /* tp_dealloc */ \
499 0, /* tp_vectorcall_offset */ \
500 0, /* tp_getattr */ \
501 0, /* tp_setattr */ \
502 0, /* tp_as_async */ \
503 0, /* tp_repr */ \
504 0, /* tp_as_number */ \
505 0, /* tp_as_sequence */ \
506 0, /* tp_as_mapping */ \
507 0, /* tp_hash */ \
508 0, /* tp_call */ \
509 0, /* tp_str */ \
510 0, /* tp_getattro */ \
511 0, /* tp_setattro */ \
512 0, /* tp_as_buffer */ \
513 Py_TPFLAGS_DEFAULT, /* tp_flags */ \
514 type_doc, /* tp_doc */ \
515 0, /* tp_traverse */ \
516 0, /* tp_clear */ \
517 0, /* tp_richcompare */ \
518 0, /* tp_weaklistoffset */ \
519 0, /* tp_iter */ \
520 0, /* tp_iternext */ \
521 type_methods, /* tp_methods */ \
522 NULL, /* tp_members */ \
523 SHA3_getseters, /* tp_getset */ \
524 0, /* tp_base */ \
525 0, /* tp_dict */ \
526 0, /* tp_descr_get */ \
527 0, /* tp_descr_set */ \
528 0, /* tp_dictoffset */ \
529 0, /* tp_init */ \
530 0, /* tp_alloc */ \
531 py_sha3_new, /* tp_new */ \
532 }
533
534 PyDoc_STRVAR(sha3_224__doc__,
535 "sha3_224([data], *, usedforsecurity=True) -> SHA3 object\n\
536 \n\
537 Return a new SHA3 hash object with a hashbit length of 28 bytes.");
538
539 PyDoc_STRVAR(sha3_256__doc__,
540 "sha3_256([data], *, usedforsecurity=True) -> SHA3 object\n\
541 \n\
542 Return a new SHA3 hash object with a hashbit length of 32 bytes.");
543
544 PyDoc_STRVAR(sha3_384__doc__,
545 "sha3_384([data], *, usedforsecurity=True) -> SHA3 object\n\
546 \n\
547 Return a new SHA3 hash object with a hashbit length of 48 bytes.");
548
549 PyDoc_STRVAR(sha3_512__doc__,
550 "sha3_512([data], *, usedforsecurity=True) -> SHA3 object\n\
551 \n\
552 Return a new SHA3 hash object with a hashbit length of 64 bytes.");
553
554 SHA3_TYPE(SHA3_224type, "_sha3.sha3_224", sha3_224__doc__, SHA3_methods);
555 SHA3_TYPE(SHA3_256type, "_sha3.sha3_256", sha3_256__doc__, SHA3_methods);
556 SHA3_TYPE(SHA3_384type, "_sha3.sha3_384", sha3_384__doc__, SHA3_methods);
557 SHA3_TYPE(SHA3_512type, "_sha3.sha3_512", sha3_512__doc__, SHA3_methods);
558
559 #ifdef PY_WITH_KECCAK
560 PyDoc_STRVAR(keccak_224__doc__,
561 "keccak_224([data], *, usedforsecurity=True) -> Keccak object\n\
562 \n\
563 Return a new Keccak hash object with a hashbit length of 28 bytes.");
564
565 PyDoc_STRVAR(keccak_256__doc__,
566 "keccak_256([data], *, usedforsecurity=True) -> Keccak object\n\
567 \n\
568 Return a new Keccak hash object with a hashbit length of 32 bytes.");
569
570 PyDoc_STRVAR(keccak_384__doc__,
571 "keccak_384([data], *, usedforsecurity=True) -> Keccak object\n\
572 \n\
573 Return a new Keccak hash object with a hashbit length of 48 bytes.");
574
575 PyDoc_STRVAR(keccak_512__doc__,
576 "keccak_512([data], *, usedforsecurity=True) -> Keccak object\n\
577 \n\
578 Return a new Keccak hash object with a hashbit length of 64 bytes.");
579
580 SHA3_TYPE(Keccak_224type, "_sha3.keccak_224", keccak_224__doc__, SHA3_methods);
581 SHA3_TYPE(Keccak_256type, "_sha3.keccak_256", keccak_256__doc__, SHA3_methods);
582 SHA3_TYPE(Keccak_384type, "_sha3.keccak_384", keccak_384__doc__, SHA3_methods);
583 SHA3_TYPE(Keccak_512type, "_sha3.keccak_512", keccak_512__doc__, SHA3_methods);
584 #endif
585
586
587 static PyObject *
_SHAKE_digest(SHA3object * self,unsigned long digestlen,int hex)588 _SHAKE_digest(SHA3object *self, unsigned long digestlen, int hex)
589 {
590 unsigned char *digest = NULL;
591 SHA3_state temp;
592 int res;
593 PyObject *result = NULL;
594
595 if (digestlen >= (1 << 29)) {
596 PyErr_SetString(PyExc_ValueError, "length is too large");
597 return NULL;
598 }
599 /* ExtractLane needs at least SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE and
600 * SHA3_LANESIZE extra space.
601 */
602 digest = (unsigned char*)PyMem_Malloc(digestlen + SHA3_LANESIZE);
603 if (digest == NULL) {
604 return PyErr_NoMemory();
605 }
606
607 /* Get the raw (binary) digest value */
608 ENTER_HASHLIB(self);
609 SHA3_copystate(temp, self->hash_state);
610 LEAVE_HASHLIB(self);
611 res = SHA3_done(&temp, NULL);
612 if (res != SUCCESS) {
613 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 done()");
614 goto error;
615 }
616 res = SHA3_squeeze(&temp, digest, digestlen * 8);
617 if (res != SUCCESS) {
618 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Squeeze()");
619 return NULL;
620 }
621 if (hex) {
622 result = _Py_strhex((const char *)digest, digestlen);
623 } else {
624 result = PyBytes_FromStringAndSize((const char *)digest,
625 digestlen);
626 }
627 error:
628 if (digest != NULL) {
629 PyMem_Free(digest);
630 }
631 return result;
632 }
633
634
635 /*[clinic input]
636 _sha3.shake_128.digest
637
638 length: unsigned_long
639 /
640
641 Return the digest value as a bytes object.
642 [clinic start generated code]*/
643
644 static PyObject *
_sha3_shake_128_digest_impl(SHA3object * self,unsigned long length)645 _sha3_shake_128_digest_impl(SHA3object *self, unsigned long length)
646 /*[clinic end generated code: output=2313605e2f87bb8f input=418ef6a36d2e6082]*/
647 {
648 return _SHAKE_digest(self, length, 0);
649 }
650
651
652 /*[clinic input]
653 _sha3.shake_128.hexdigest
654
655 length: unsigned_long
656 /
657
658 Return the digest value as a string of hexadecimal digits.
659 [clinic start generated code]*/
660
661 static PyObject *
_sha3_shake_128_hexdigest_impl(SHA3object * self,unsigned long length)662 _sha3_shake_128_hexdigest_impl(SHA3object *self, unsigned long length)
663 /*[clinic end generated code: output=bf8e2f1e490944a8 input=69fb29b0926ae321]*/
664 {
665 return _SHAKE_digest(self, length, 1);
666 }
667
668
669 static PyMethodDef SHAKE_methods[] = {
670 _SHA3_SHA3_224_COPY_METHODDEF
671 _SHA3_SHAKE_128_DIGEST_METHODDEF
672 _SHA3_SHAKE_128_HEXDIGEST_METHODDEF
673 _SHA3_SHA3_224_UPDATE_METHODDEF
674 {NULL, NULL} /* sentinel */
675 };
676
677 PyDoc_STRVAR(shake_128__doc__,
678 "shake_128([data], *, usedforsecurity=True) -> SHAKE object\n\
679 \n\
680 Return a new SHAKE hash object.");
681
682 PyDoc_STRVAR(shake_256__doc__,
683 "shake_256([data], *, usedforsecurity=True) -> SHAKE object\n\
684 \n\
685 Return a new SHAKE hash object.");
686
687 SHA3_TYPE(SHAKE128type, "_sha3.shake_128", shake_128__doc__, SHAKE_methods);
688 SHA3_TYPE(SHAKE256type, "_sha3.shake_256", shake_256__doc__, SHAKE_methods);
689
690
691 /* Initialize this module. */
692 static struct PyModuleDef _SHA3module = {
693 PyModuleDef_HEAD_INIT,
694 "_sha3",
695 NULL,
696 -1,
697 NULL,
698 NULL,
699 NULL,
700 NULL,
701 NULL
702 };
703
704
705 PyMODINIT_FUNC
PyInit__sha3(void)706 PyInit__sha3(void)
707 {
708 PyObject *m = NULL;
709
710 if ((m = PyModule_Create(&_SHA3module)) == NULL) {
711 return NULL;
712 }
713
714 #define init_sha3type(name, type) \
715 do { \
716 Py_SET_TYPE(type, &PyType_Type); \
717 if (PyType_Ready(type) < 0) { \
718 goto error; \
719 } \
720 Py_INCREF((PyObject *)type); \
721 if (PyModule_AddObject(m, name, (PyObject *)type) < 0) { \
722 goto error; \
723 } \
724 } while(0)
725
726 init_sha3type("sha3_224", &SHA3_224type);
727 init_sha3type("sha3_256", &SHA3_256type);
728 init_sha3type("sha3_384", &SHA3_384type);
729 init_sha3type("sha3_512", &SHA3_512type);
730 #ifdef PY_WITH_KECCAK
731 init_sha3type("keccak_224", &Keccak_224type);
732 init_sha3type("keccak_256", &Keccak_256type);
733 init_sha3type("keccak_384", &Keccak_384type);
734 init_sha3type("keccak_512", &Keccak_512type);
735 #endif
736 init_sha3type("shake_128", &SHAKE128type);
737 init_sha3type("shake_256", &SHAKE256type);
738
739 #undef init_sha3type
740
741 if (PyModule_AddIntConstant(m, "keccakopt", KeccakOpt) < 0) {
742 goto error;
743 }
744 if (PyModule_AddStringConstant(m, "implementation",
745 KeccakP1600_implementation) < 0) {
746 goto error;
747 }
748
749 return m;
750 error:
751 Py_DECREF(m);
752 return NULL;
753 }
754