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