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