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 && defined(PY_UINT64_T)
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 && defined(PY_UINT64_T)
52   /* 64bit platforms with unsigned int64 */
53   typedef PY_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 
173 static PyObject *
py_sha3_new(PyTypeObject * type,PyObject * args,PyObject * kwargs)174 py_sha3_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
175 {
176     SHA3object *self = NULL;
177     Py_buffer buf = {NULL, NULL};
178     HashReturn res;
179     PyObject *data = NULL;
180 
181     if (!_PyArg_NoKeywords(_PyType_Name(type), kwargs)) {
182         return NULL;
183     }
184     if (!PyArg_UnpackTuple(args, _PyType_Name(type), 0, 1, &data)) {
185         return NULL;
186     }
187 
188     self = newSHA3object(type);
189     if (self == NULL) {
190         goto error;
191     }
192 
193     if (type == &SHA3_224type) {
194         res = Keccak_HashInitialize_SHA3_224(&self->hash_state);
195     } else if (type == &SHA3_256type) {
196         res = Keccak_HashInitialize_SHA3_256(&self->hash_state);
197     } else if (type == &SHA3_384type) {
198         res = Keccak_HashInitialize_SHA3_384(&self->hash_state);
199     } else if (type == &SHA3_512type) {
200         res = Keccak_HashInitialize_SHA3_512(&self->hash_state);
201 #ifdef PY_WITH_KECCAK
202     } else if (type == &Keccak_224type) {
203         res = Keccak_HashInitialize(&self->hash_state, 1152, 448, 224, 0x01);
204     } else if (type == &Keccak_256type) {
205         res = Keccak_HashInitialize(&self->hash_state, 1088, 512, 256, 0x01);
206     } else if (type == &Keccak_384type) {
207         res = Keccak_HashInitialize(&self->hash_state, 832, 768, 384, 0x01);
208     } else if (type == &Keccak_512type) {
209         res = Keccak_HashInitialize(&self->hash_state, 576, 1024, 512, 0x01);
210 #endif
211     } else if (type == &SHAKE128type) {
212         res = Keccak_HashInitialize_SHAKE128(&self->hash_state);
213     } else if (type == &SHAKE256type) {
214         res = Keccak_HashInitialize_SHAKE256(&self->hash_state);
215     } else {
216         PyErr_BadInternalCall();
217         goto error;
218     }
219 
220     if (data) {
221         GET_BUFFER_VIEW_OR_ERROR(data, &buf, goto error);
222         if (buf.len >= HASHLIB_GIL_MINSIZE) {
223             /* invariant: New objects can't be accessed by other code yet,
224              * thus it's safe to release the GIL without locking the object.
225              */
226             Py_BEGIN_ALLOW_THREADS
227             res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
228             Py_END_ALLOW_THREADS
229         }
230         else {
231             res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
232         }
233         if (res != SUCCESS) {
234             PyErr_SetString(PyExc_RuntimeError,
235                             "internal error in SHA3 Update()");
236             goto error;
237         }
238         PyBuffer_Release(&buf);
239     }
240 
241     return (PyObject *)self;
242 
243   error:
244     if (self) {
245         Py_DECREF(self);
246     }
247     if (data && buf.obj) {
248         PyBuffer_Release(&buf);
249     }
250     return NULL;
251 }
252 
253 
254 /* Internal methods for a hash object */
255 
256 static void
SHA3_dealloc(SHA3object * self)257 SHA3_dealloc(SHA3object *self)
258 {
259     if (self->lock) {
260         PyThread_free_lock(self->lock);
261     }
262     PyObject_Del(self);
263 }
264 
265 
266 /* External methods for a hash object */
267 
268 
269 /*[clinic input]
270 _sha3.sha3_224.copy
271 
272 Return a copy of the hash object.
273 [clinic start generated code]*/
274 
275 static PyObject *
_sha3_sha3_224_copy_impl(SHA3object * self)276 _sha3_sha3_224_copy_impl(SHA3object *self)
277 /*[clinic end generated code: output=6c537411ecdcda4c input=93a44aaebea51ba8]*/
278 {
279     SHA3object *newobj;
280 
281     if ((newobj = newSHA3object(Py_TYPE(self))) == NULL) {
282         return NULL;
283     }
284     ENTER_HASHLIB(self);
285     SHA3_copystate(newobj->hash_state, self->hash_state);
286     LEAVE_HASHLIB(self);
287     return (PyObject *)newobj;
288 }
289 
290 
291 /*[clinic input]
292 _sha3.sha3_224.digest
293 
294 Return the digest value as a bytes object.
295 [clinic start generated code]*/
296 
297 static PyObject *
_sha3_sha3_224_digest_impl(SHA3object * self)298 _sha3_sha3_224_digest_impl(SHA3object *self)
299 /*[clinic end generated code: output=fd531842e20b2d5b input=5b2a659536bbd248]*/
300 {
301     unsigned char digest[SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE];
302     SHA3_state temp;
303     HashReturn res;
304 
305     ENTER_HASHLIB(self);
306     SHA3_copystate(temp, self->hash_state);
307     LEAVE_HASHLIB(self);
308     res = SHA3_done(&temp, digest);
309     if (res != SUCCESS) {
310         PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Final()");
311         return NULL;
312     }
313     return PyBytes_FromStringAndSize((const char *)digest,
314                                       self->hash_state.fixedOutputLength / 8);
315 }
316 
317 
318 /*[clinic input]
319 _sha3.sha3_224.hexdigest
320 
321 Return the digest value as a string of hexadecimal digits.
322 [clinic start generated code]*/
323 
324 static PyObject *
_sha3_sha3_224_hexdigest_impl(SHA3object * self)325 _sha3_sha3_224_hexdigest_impl(SHA3object *self)
326 /*[clinic end generated code: output=75ad03257906918d input=2d91bb6e0d114ee3]*/
327 {
328     unsigned char digest[SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE];
329     SHA3_state temp;
330     HashReturn res;
331 
332     /* Get the raw (binary) digest value */
333     ENTER_HASHLIB(self);
334     SHA3_copystate(temp, self->hash_state);
335     LEAVE_HASHLIB(self);
336     res = SHA3_done(&temp, digest);
337     if (res != SUCCESS) {
338         PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Final()");
339         return NULL;
340     }
341     return _Py_strhex((const char *)digest,
342                       self->hash_state.fixedOutputLength / 8);
343 }
344 
345 
346 /*[clinic input]
347 _sha3.sha3_224.update
348 
349     data: object
350     /
351 
352 Update this hash object's state with the provided bytes-like object.
353 [clinic start generated code]*/
354 
355 static PyObject *
_sha3_sha3_224_update(SHA3object * self,PyObject * data)356 _sha3_sha3_224_update(SHA3object *self, PyObject *data)
357 /*[clinic end generated code: output=d3223352286ed357 input=a887f54dcc4ae227]*/
358 {
359     Py_buffer buf;
360     HashReturn res;
361 
362     GET_BUFFER_VIEW_OR_ERROUT(data, &buf);
363 
364     /* add new data, the function takes the length in bits not bytes */
365     if (self->lock == NULL && buf.len >= HASHLIB_GIL_MINSIZE) {
366         self->lock = PyThread_allocate_lock();
367     }
368     /* Once a lock exists all code paths must be synchronized. We have to
369      * release the GIL even for small buffers as acquiring the lock may take
370      * an unlimited amount of time when another thread updates this object
371      * with lots of data. */
372     if (self->lock) {
373         Py_BEGIN_ALLOW_THREADS
374         PyThread_acquire_lock(self->lock, 1);
375         res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
376         PyThread_release_lock(self->lock);
377         Py_END_ALLOW_THREADS
378     }
379     else {
380         res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
381     }
382 
383     if (res != SUCCESS) {
384         PyBuffer_Release(&buf);
385         PyErr_SetString(PyExc_RuntimeError,
386                         "internal error in SHA3 Update()");
387         return NULL;
388     }
389 
390     PyBuffer_Release(&buf);
391     Py_RETURN_NONE;
392 }
393 
394 
395 static PyMethodDef SHA3_methods[] = {
396     _SHA3_SHA3_224_COPY_METHODDEF
397     _SHA3_SHA3_224_DIGEST_METHODDEF
398     _SHA3_SHA3_224_HEXDIGEST_METHODDEF
399     _SHA3_SHA3_224_UPDATE_METHODDEF
400     {NULL,        NULL}         /* sentinel */
401 };
402 
403 
404 static PyObject *
SHA3_get_block_size(SHA3object * self,void * closure)405 SHA3_get_block_size(SHA3object *self, void *closure)
406 {
407     int rate = self->hash_state.sponge.rate;
408     return PyLong_FromLong(rate / 8);
409 }
410 
411 
412 static PyObject *
SHA3_get_name(SHA3object * self,void * closure)413 SHA3_get_name(SHA3object *self, void *closure)
414 {
415     PyTypeObject *type = Py_TYPE(self);
416     if (type == &SHA3_224type) {
417         return PyUnicode_FromString("sha3_224");
418     } else if (type == &SHA3_256type) {
419         return PyUnicode_FromString("sha3_256");
420     } else if (type == &SHA3_384type) {
421         return PyUnicode_FromString("sha3_384");
422     } else if (type == &SHA3_512type) {
423         return PyUnicode_FromString("sha3_512");
424 #ifdef PY_WITH_KECCAK
425     } else if (type == &Keccak_224type) {
426         return PyUnicode_FromString("keccak_224");
427     } else if (type == &Keccak_256type) {
428         return PyUnicode_FromString("keccak_256");
429     } else if (type == &Keccak_384type) {
430         return PyUnicode_FromString("keccak_384");
431     } else if (type == &Keccak_512type) {
432         return PyUnicode_FromString("keccak_512");
433 #endif
434     } else if (type == &SHAKE128type) {
435         return PyUnicode_FromString("shake_128");
436     } else if (type == &SHAKE256type) {
437         return PyUnicode_FromString("shake_256");
438     } else {
439         PyErr_BadInternalCall();
440         return NULL;
441     }
442 }
443 
444 
445 static PyObject *
SHA3_get_digest_size(SHA3object * self,void * closure)446 SHA3_get_digest_size(SHA3object *self, void *closure)
447 {
448     return PyLong_FromLong(self->hash_state.fixedOutputLength / 8);
449 }
450 
451 
452 static PyObject *
SHA3_get_capacity_bits(SHA3object * self,void * closure)453 SHA3_get_capacity_bits(SHA3object *self, void *closure)
454 {
455     int capacity = 1600 - self->hash_state.sponge.rate;
456     return PyLong_FromLong(capacity);
457 }
458 
459 
460 static PyObject *
SHA3_get_rate_bits(SHA3object * self,void * closure)461 SHA3_get_rate_bits(SHA3object *self, void *closure)
462 {
463     unsigned int rate = self->hash_state.sponge.rate;
464     return PyLong_FromLong(rate);
465 }
466 
467 static PyObject *
SHA3_get_suffix(SHA3object * self,void * closure)468 SHA3_get_suffix(SHA3object *self, void *closure)
469 {
470     unsigned char suffix[2];
471     suffix[0] = self->hash_state.delimitedSuffix;
472     suffix[1] = 0;
473     return PyBytes_FromStringAndSize((const char *)suffix, 1);
474 }
475 
476 
477 static PyGetSetDef SHA3_getseters[] = {
478     {"block_size", (getter)SHA3_get_block_size, NULL, NULL, NULL},
479     {"name", (getter)SHA3_get_name, NULL, NULL, NULL},
480     {"digest_size", (getter)SHA3_get_digest_size, NULL, NULL, NULL},
481     {"_capacity_bits", (getter)SHA3_get_capacity_bits, NULL, NULL, NULL},
482     {"_rate_bits", (getter)SHA3_get_rate_bits, NULL, NULL, NULL},
483     {"_suffix", (getter)SHA3_get_suffix, NULL, NULL, NULL},
484     {NULL}  /* Sentinel */
485 };
486 
487 
488 #define SHA3_TYPE(type_obj, type_name, type_doc, type_methods) \
489     static PyTypeObject type_obj = { \
490         PyVarObject_HEAD_INIT(NULL, 0) \
491         type_name,          /* tp_name */ \
492         sizeof(SHA3object), /* tp_basicsize */ \
493         0,                  /* tp_itemsize */ \
494         /*  methods  */ \
495         (destructor)SHA3_dealloc, /* tp_dealloc */ \
496         0,                  /* tp_vectorcall_offset */ \
497         0,                  /* tp_getattr */ \
498         0,                  /* tp_setattr */ \
499         0,                  /* tp_as_async */ \
500         0,                  /* tp_repr */ \
501         0,                  /* tp_as_number */ \
502         0,                  /* tp_as_sequence */ \
503         0,                  /* tp_as_mapping */ \
504         0,                  /* tp_hash */ \
505         0,                  /* tp_call */ \
506         0,                  /* tp_str */ \
507         0,                  /* tp_getattro */ \
508         0,                  /* tp_setattro */ \
509         0,                  /* tp_as_buffer */ \
510         Py_TPFLAGS_DEFAULT, /* tp_flags */ \
511         type_doc,           /* tp_doc */ \
512         0,                  /* tp_traverse */ \
513         0,                  /* tp_clear */ \
514         0,                  /* tp_richcompare */ \
515         0,                  /* tp_weaklistoffset */ \
516         0,                  /* tp_iter */ \
517         0,                  /* tp_iternext */ \
518         type_methods,       /* tp_methods */ \
519         NULL,               /* tp_members */ \
520         SHA3_getseters,     /* tp_getset */ \
521         0,                  /* tp_base */ \
522         0,                  /* tp_dict */ \
523         0,                  /* tp_descr_get */ \
524         0,                  /* tp_descr_set */ \
525         0,                  /* tp_dictoffset */ \
526         0,                  /* tp_init */ \
527         0,                  /* tp_alloc */ \
528         py_sha3_new,        /* tp_new */ \
529     }
530 
531 PyDoc_STRVAR(sha3_224__doc__,
532 "sha3_224([data]) -> SHA3 object\n\
533 \n\
534 Return a new SHA3 hash object with a hashbit length of 28 bytes.");
535 
536 PyDoc_STRVAR(sha3_256__doc__,
537 "sha3_256([data]) -> SHA3 object\n\
538 \n\
539 Return a new SHA3 hash object with a hashbit length of 32 bytes.");
540 
541 PyDoc_STRVAR(sha3_384__doc__,
542 "sha3_384([data]) -> SHA3 object\n\
543 \n\
544 Return a new SHA3 hash object with a hashbit length of 48 bytes.");
545 
546 PyDoc_STRVAR(sha3_512__doc__,
547 "sha3_512([data]) -> SHA3 object\n\
548 \n\
549 Return a new SHA3 hash object with a hashbit length of 64 bytes.");
550 
551 SHA3_TYPE(SHA3_224type, "_sha3.sha3_224", sha3_224__doc__, SHA3_methods);
552 SHA3_TYPE(SHA3_256type, "_sha3.sha3_256", sha3_256__doc__, SHA3_methods);
553 SHA3_TYPE(SHA3_384type, "_sha3.sha3_384", sha3_384__doc__, SHA3_methods);
554 SHA3_TYPE(SHA3_512type, "_sha3.sha3_512", sha3_512__doc__, SHA3_methods);
555 
556 #ifdef PY_WITH_KECCAK
557 PyDoc_STRVAR(keccak_224__doc__,
558 "keccak_224([data]) -> Keccak object\n\
559 \n\
560 Return a new Keccak hash object with a hashbit length of 28 bytes.");
561 
562 PyDoc_STRVAR(keccak_256__doc__,
563 "keccak_256([data]) -> Keccak object\n\
564 \n\
565 Return a new Keccak hash object with a hashbit length of 32 bytes.");
566 
567 PyDoc_STRVAR(keccak_384__doc__,
568 "keccak_384([data]) -> Keccak object\n\
569 \n\
570 Return a new Keccak hash object with a hashbit length of 48 bytes.");
571 
572 PyDoc_STRVAR(keccak_512__doc__,
573 "keccak_512([data]) -> Keccak object\n\
574 \n\
575 Return a new Keccak hash object with a hashbit length of 64 bytes.");
576 
577 SHA3_TYPE(Keccak_224type, "_sha3.keccak_224", keccak_224__doc__, SHA3_methods);
578 SHA3_TYPE(Keccak_256type, "_sha3.keccak_256", keccak_256__doc__, SHA3_methods);
579 SHA3_TYPE(Keccak_384type, "_sha3.keccak_384", keccak_384__doc__, SHA3_methods);
580 SHA3_TYPE(Keccak_512type, "_sha3.keccak_512", keccak_512__doc__, SHA3_methods);
581 #endif
582 
583 
584 static PyObject *
_SHAKE_digest(SHA3object * self,unsigned long digestlen,int hex)585 _SHAKE_digest(SHA3object *self, unsigned long digestlen, int hex)
586 {
587     unsigned char *digest = NULL;
588     SHA3_state temp;
589     int res;
590     PyObject *result = NULL;
591 
592     if (digestlen >= (1 << 29)) {
593         PyErr_SetString(PyExc_ValueError, "length is too large");
594         return NULL;
595     }
596     /* ExtractLane needs at least SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE and
597      * SHA3_LANESIZE extra space.
598      */
599     digest = (unsigned char*)PyMem_Malloc(digestlen + SHA3_LANESIZE);
600     if (digest == NULL) {
601         return PyErr_NoMemory();
602     }
603 
604     /* Get the raw (binary) digest value */
605     ENTER_HASHLIB(self);
606     SHA3_copystate(temp, self->hash_state);
607     LEAVE_HASHLIB(self);
608     res = SHA3_done(&temp, NULL);
609     if (res != SUCCESS) {
610         PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 done()");
611         goto error;
612     }
613     res = SHA3_squeeze(&temp, digest, digestlen * 8);
614     if (res != SUCCESS) {
615         PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Squeeze()");
616         return NULL;
617     }
618     if (hex) {
619          result = _Py_strhex((const char *)digest, digestlen);
620     } else {
621         result = PyBytes_FromStringAndSize((const char *)digest,
622                                            digestlen);
623     }
624   error:
625     if (digest != NULL) {
626         PyMem_Free(digest);
627     }
628     return result;
629 }
630 
631 
632 /*[clinic input]
633 _sha3.shake_128.digest
634 
635     length: unsigned_long
636     /
637 
638 Return the digest value as a bytes object.
639 [clinic start generated code]*/
640 
641 static PyObject *
_sha3_shake_128_digest_impl(SHA3object * self,unsigned long length)642 _sha3_shake_128_digest_impl(SHA3object *self, unsigned long length)
643 /*[clinic end generated code: output=2313605e2f87bb8f input=418ef6a36d2e6082]*/
644 {
645     return _SHAKE_digest(self, length, 0);
646 }
647 
648 
649 /*[clinic input]
650 _sha3.shake_128.hexdigest
651 
652     length: unsigned_long
653     /
654 
655 Return the digest value as a string of hexadecimal digits.
656 [clinic start generated code]*/
657 
658 static PyObject *
_sha3_shake_128_hexdigest_impl(SHA3object * self,unsigned long length)659 _sha3_shake_128_hexdigest_impl(SHA3object *self, unsigned long length)
660 /*[clinic end generated code: output=bf8e2f1e490944a8 input=69fb29b0926ae321]*/
661 {
662     return _SHAKE_digest(self, length, 1);
663 }
664 
665 
666 static PyMethodDef SHAKE_methods[] = {
667     _SHA3_SHA3_224_COPY_METHODDEF
668     _SHA3_SHAKE_128_DIGEST_METHODDEF
669     _SHA3_SHAKE_128_HEXDIGEST_METHODDEF
670     _SHA3_SHA3_224_UPDATE_METHODDEF
671     {NULL,        NULL}         /* sentinel */
672 };
673 
674 PyDoc_STRVAR(shake_128__doc__,
675 "shake_128([data]) -> SHAKE object\n\
676 \n\
677 Return a new SHAKE hash object.");
678 
679 PyDoc_STRVAR(shake_256__doc__,
680 "shake_256([data]) -> SHAKE object\n\
681 \n\
682 Return a new SHAKE hash object.");
683 
684 SHA3_TYPE(SHAKE128type, "_sha3.shake_128", shake_128__doc__, SHAKE_methods);
685 SHA3_TYPE(SHAKE256type, "_sha3.shake_256", shake_256__doc__, SHAKE_methods);
686 
687 
688 /* Initialize this module. */
689 static struct PyModuleDef _SHA3module = {
690         PyModuleDef_HEAD_INIT,
691         "_sha3",
692         NULL,
693         -1,
694         NULL,
695         NULL,
696         NULL,
697         NULL,
698         NULL
699 };
700 
701 
702 PyMODINIT_FUNC
PyInit__sha3(void)703 PyInit__sha3(void)
704 {
705     PyObject *m = NULL;
706 
707     if ((m = PyModule_Create(&_SHA3module)) == NULL) {
708         return NULL;
709     }
710 
711 #define init_sha3type(name, type)     \
712     do {                              \
713         Py_TYPE(type) = &PyType_Type; \
714         if (PyType_Ready(type) < 0) { \
715             goto error;               \
716         }                             \
717         Py_INCREF((PyObject *)type);  \
718         if (PyModule_AddObject(m, name, (PyObject *)type) < 0) { \
719             goto error;               \
720         }                             \
721     } while(0)
722 
723     init_sha3type("sha3_224", &SHA3_224type);
724     init_sha3type("sha3_256", &SHA3_256type);
725     init_sha3type("sha3_384", &SHA3_384type);
726     init_sha3type("sha3_512", &SHA3_512type);
727 #ifdef PY_WITH_KECCAK
728     init_sha3type("keccak_224", &Keccak_224type);
729     init_sha3type("keccak_256", &Keccak_256type);
730     init_sha3type("keccak_384", &Keccak_384type);
731     init_sha3type("keccak_512", &Keccak_512type);
732 #endif
733     init_sha3type("shake_128", &SHAKE128type);
734     init_sha3type("shake_256", &SHAKE256type);
735 
736 #undef init_sha3type
737 
738     if (PyModule_AddIntConstant(m, "keccakopt", KeccakOpt) < 0) {
739         goto error;
740     }
741     if (PyModule_AddStringConstant(m, "implementation",
742                                    KeccakP1600_implementation) < 0) {
743         goto error;
744     }
745 
746     return m;
747   error:
748     Py_DECREF(m);
749     return NULL;
750 }
751