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