blob: 27f69385cc3eb0f8f387e7578d9dd3deebb3b84a [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
Victor Stinner1a1bd2e2020-04-17 19:13:06 +020043#elif SIZEOF_VOID_P == 8
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
Victor Stinner1a1bd2e2020-04-17 19:13:06 +020051#if KeccakOpt == 64
Christian Heimes6fe2a752016-09-07 11:58:24 +020052 /* 64bit platforms with unsigned int64 */
Victor Stinner1a1bd2e2020-04-17 19:13:06 +020053 typedef uint64_t UINT64;
Christian Heimes6fe2a752016-09-07 11:58:24 +020054 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
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500125typedef struct {
126 PyTypeObject *sha3_224_type;
127 PyTypeObject *sha3_256_type;
128 PyTypeObject *sha3_384_type;
129 PyTypeObject *sha3_512_type;
130#ifdef PY_WITH_KECCAK
131 PyTypeObject *keccak_224_type;
132 PyTypeObject *keccak_256_type;
133 PyTypeObject *keccak_384_type;
134 PyTypeObject *keccak_512_type;
135#endif
136 PyTypeObject *shake_128_type;
137 PyTypeObject *shake_256_type;
138} SHA3State;
139
140static inline SHA3State*
141sha3_get_state(PyObject *module)
142{
143 void *state = PyModule_GetState(module);
144 assert(state != NULL);
145 return (SHA3State *)state;
146}
Christian Heimes6fe2a752016-09-07 11:58:24 +0200147
148/*[clinic input]
149module _sha3
150class _sha3.sha3_224 "SHA3object *" "&SHA3_224typ"
151class _sha3.sha3_256 "SHA3object *" "&SHA3_256typ"
152class _sha3.sha3_384 "SHA3object *" "&SHA3_384typ"
153class _sha3.sha3_512 "SHA3object *" "&SHA3_512typ"
154class _sha3.shake_128 "SHA3object *" "&SHAKE128type"
155class _sha3.shake_256 "SHA3object *" "&SHAKE256type"
156[clinic start generated code]*/
157/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b8a53680f370285a]*/
158
159/* The structure for storing SHA3 info */
160
Christian Heimes6fe2a752016-09-07 11:58:24 +0200161typedef struct {
162 PyObject_HEAD
163 SHA3_state hash_state;
Christian Heimes6fe2a752016-09-07 11:58:24 +0200164 PyThread_type_lock lock;
Christian Heimes6fe2a752016-09-07 11:58:24 +0200165} SHA3object;
166
Christian Heimes6fe2a752016-09-07 11:58:24 +0200167#include "clinic/sha3module.c.h"
168
169static SHA3object *
170newSHA3object(PyTypeObject *type)
171{
172 SHA3object *newobj;
173 newobj = (SHA3object *)PyObject_New(SHA3object, type);
174 if (newobj == NULL) {
175 return NULL;
176 }
Christian Heimes6fe2a752016-09-07 11:58:24 +0200177 newobj->lock = NULL;
Christian Heimes6fe2a752016-09-07 11:58:24 +0200178 return newobj;
179}
180
Christian Heimes7cad53e2019-09-13 02:30:00 +0200181/*[clinic input]
182@classmethod
183_sha3.sha3_224.__new__ as py_sha3_new
184 data: object(c_default="NULL") = b''
185 /
186 *
187 usedforsecurity: bool = True
188
189Return a new BLAKE2b hash object.
190[clinic start generated code]*/
Christian Heimes6fe2a752016-09-07 11:58:24 +0200191
Christian Heimes6fe2a752016-09-07 11:58:24 +0200192static PyObject *
Christian Heimes7cad53e2019-09-13 02:30:00 +0200193py_sha3_new_impl(PyTypeObject *type, PyObject *data, int usedforsecurity)
194/*[clinic end generated code: output=90409addc5d5e8b0 input=bcfcdf2e4368347a]*/
Christian Heimes6fe2a752016-09-07 11:58:24 +0200195{
Christian Heimesaa6da322021-04-18 08:39:39 +0200196 HashReturn res;
197 Py_buffer buf = {NULL, NULL};
198 SHA3State *state = PyType_GetModuleState(type);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500199 SHA3object *self = newSHA3object(type);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200200 if (self == NULL) {
201 goto error;
202 }
203
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500204 assert(state != NULL);
205
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500206 if (type == state->sha3_224_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200207 res = Keccak_HashInitialize_SHA3_224(&self->hash_state);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500208 } else if (type == state->sha3_256_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200209 res = Keccak_HashInitialize_SHA3_256(&self->hash_state);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500210 } else if (type == state->sha3_384_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200211 res = Keccak_HashInitialize_SHA3_384(&self->hash_state);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500212 } else if (type == state->sha3_512_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200213 res = Keccak_HashInitialize_SHA3_512(&self->hash_state);
214#ifdef PY_WITH_KECCAK
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500215 } else if (type == state->keccak_224_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200216 res = Keccak_HashInitialize(&self->hash_state, 1152, 448, 224, 0x01);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500217 } else if (type == state->keccak_256_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200218 res = Keccak_HashInitialize(&self->hash_state, 1088, 512, 256, 0x01);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500219 } else if (type == state->keccak_384_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200220 res = Keccak_HashInitialize(&self->hash_state, 832, 768, 384, 0x01);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500221 } else if (type == state->keccak_512_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200222 res = Keccak_HashInitialize(&self->hash_state, 576, 1024, 512, 0x01);
223#endif
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500224 } else if (type == state->shake_128_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200225 res = Keccak_HashInitialize_SHAKE128(&self->hash_state);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500226 } else if (type == state->shake_256_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200227 res = Keccak_HashInitialize_SHAKE256(&self->hash_state);
228 } else {
229 PyErr_BadInternalCall();
230 goto error;
231 }
232
Christian Heimesaa6da322021-04-18 08:39:39 +0200233 if (res != SUCCESS) {
234 PyErr_SetString(PyExc_RuntimeError,
235 "internal error in SHA3 initialize()");
236 goto error;
237 }
238
Christian Heimes6fe2a752016-09-07 11:58:24 +0200239 if (data) {
240 GET_BUFFER_VIEW_OR_ERROR(data, &buf, goto error);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200241 if (buf.len >= HASHLIB_GIL_MINSIZE) {
242 /* invariant: New objects can't be accessed by other code yet,
243 * thus it's safe to release the GIL without locking the object.
244 */
245 Py_BEGIN_ALLOW_THREADS
246 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
247 Py_END_ALLOW_THREADS
248 }
249 else {
250 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
251 }
Christian Heimes6fe2a752016-09-07 11:58:24 +0200252 if (res != SUCCESS) {
253 PyErr_SetString(PyExc_RuntimeError,
254 "internal error in SHA3 Update()");
255 goto error;
256 }
257 PyBuffer_Release(&buf);
258 }
259
260 return (PyObject *)self;
261
262 error:
263 if (self) {
264 Py_DECREF(self);
265 }
266 if (data && buf.obj) {
267 PyBuffer_Release(&buf);
268 }
269 return NULL;
270}
271
272
273/* Internal methods for a hash object */
274
275static void
276SHA3_dealloc(SHA3object *self)
277{
Christian Heimes6fe2a752016-09-07 11:58:24 +0200278 if (self->lock) {
279 PyThread_free_lock(self->lock);
280 }
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500281
282 PyTypeObject *tp = Py_TYPE(self);
Victor Stinner32bd68c2020-12-01 10:37:39 +0100283 PyObject_Free(self);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500284 Py_DECREF(tp);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200285}
286
287
288/* External methods for a hash object */
289
290
291/*[clinic input]
292_sha3.sha3_224.copy
293
294Return a copy of the hash object.
295[clinic start generated code]*/
296
297static PyObject *
298_sha3_sha3_224_copy_impl(SHA3object *self)
299/*[clinic end generated code: output=6c537411ecdcda4c input=93a44aaebea51ba8]*/
300{
301 SHA3object *newobj;
302
303 if ((newobj = newSHA3object(Py_TYPE(self))) == NULL) {
304 return NULL;
305 }
306 ENTER_HASHLIB(self);
307 SHA3_copystate(newobj->hash_state, self->hash_state);
308 LEAVE_HASHLIB(self);
309 return (PyObject *)newobj;
310}
311
312
313/*[clinic input]
314_sha3.sha3_224.digest
315
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300316Return the digest value as a bytes object.
Christian Heimes6fe2a752016-09-07 11:58:24 +0200317[clinic start generated code]*/
318
319static PyObject *
320_sha3_sha3_224_digest_impl(SHA3object *self)
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300321/*[clinic end generated code: output=fd531842e20b2d5b input=5b2a659536bbd248]*/
Christian Heimes6fe2a752016-09-07 11:58:24 +0200322{
Christian Heimescf45ee12016-09-08 13:35:00 +0200323 unsigned char digest[SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE];
Christian Heimes6fe2a752016-09-07 11:58:24 +0200324 SHA3_state temp;
325 HashReturn res;
326
327 ENTER_HASHLIB(self);
328 SHA3_copystate(temp, self->hash_state);
329 LEAVE_HASHLIB(self);
330 res = SHA3_done(&temp, digest);
331 if (res != SUCCESS) {
332 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Final()");
333 return NULL;
334 }
335 return PyBytes_FromStringAndSize((const char *)digest,
336 self->hash_state.fixedOutputLength / 8);
337}
338
339
340/*[clinic input]
341_sha3.sha3_224.hexdigest
342
343Return the digest value as a string of hexadecimal digits.
344[clinic start generated code]*/
345
346static PyObject *
347_sha3_sha3_224_hexdigest_impl(SHA3object *self)
348/*[clinic end generated code: output=75ad03257906918d input=2d91bb6e0d114ee3]*/
349{
Christian Heimescf45ee12016-09-08 13:35:00 +0200350 unsigned char digest[SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE];
Christian Heimes6fe2a752016-09-07 11:58:24 +0200351 SHA3_state temp;
352 HashReturn res;
353
354 /* Get the raw (binary) digest value */
355 ENTER_HASHLIB(self);
356 SHA3_copystate(temp, self->hash_state);
357 LEAVE_HASHLIB(self);
358 res = SHA3_done(&temp, digest);
359 if (res != SUCCESS) {
360 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Final()");
361 return NULL;
362 }
363 return _Py_strhex((const char *)digest,
364 self->hash_state.fixedOutputLength / 8);
365}
366
367
368/*[clinic input]
369_sha3.sha3_224.update
370
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300371 data: object
Christian Heimes6fe2a752016-09-07 11:58:24 +0200372 /
373
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300374Update this hash object's state with the provided bytes-like object.
Christian Heimes6fe2a752016-09-07 11:58:24 +0200375[clinic start generated code]*/
376
377static PyObject *
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300378_sha3_sha3_224_update(SHA3object *self, PyObject *data)
379/*[clinic end generated code: output=d3223352286ed357 input=a887f54dcc4ae227]*/
Christian Heimes6fe2a752016-09-07 11:58:24 +0200380{
381 Py_buffer buf;
382 HashReturn res;
383
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300384 GET_BUFFER_VIEW_OR_ERROUT(data, &buf);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200385
386 /* add new data, the function takes the length in bits not bytes */
Christian Heimes6fe2a752016-09-07 11:58:24 +0200387 if (self->lock == NULL && buf.len >= HASHLIB_GIL_MINSIZE) {
388 self->lock = PyThread_allocate_lock();
389 }
390 /* Once a lock exists all code paths must be synchronized. We have to
391 * release the GIL even for small buffers as acquiring the lock may take
392 * an unlimited amount of time when another thread updates this object
393 * with lots of data. */
394 if (self->lock) {
395 Py_BEGIN_ALLOW_THREADS
396 PyThread_acquire_lock(self->lock, 1);
397 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
398 PyThread_release_lock(self->lock);
399 Py_END_ALLOW_THREADS
400 }
401 else {
402 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
403 }
Christian Heimes6fe2a752016-09-07 11:58:24 +0200404
405 if (res != SUCCESS) {
406 PyBuffer_Release(&buf);
407 PyErr_SetString(PyExc_RuntimeError,
408 "internal error in SHA3 Update()");
409 return NULL;
410 }
411
412 PyBuffer_Release(&buf);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200413 Py_RETURN_NONE;
Christian Heimes6fe2a752016-09-07 11:58:24 +0200414}
415
416
417static PyMethodDef SHA3_methods[] = {
418 _SHA3_SHA3_224_COPY_METHODDEF
419 _SHA3_SHA3_224_DIGEST_METHODDEF
420 _SHA3_SHA3_224_HEXDIGEST_METHODDEF
421 _SHA3_SHA3_224_UPDATE_METHODDEF
422 {NULL, NULL} /* sentinel */
423};
424
425
426static PyObject *
427SHA3_get_block_size(SHA3object *self, void *closure)
428{
429 int rate = self->hash_state.sponge.rate;
430 return PyLong_FromLong(rate / 8);
431}
432
433
434static PyObject *
435SHA3_get_name(SHA3object *self, void *closure)
436{
437 PyTypeObject *type = Py_TYPE(self);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500438
439 SHA3State *state = PyType_GetModuleState(type);
440 assert(state != NULL);
441
442 if (type == state->sha3_224_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200443 return PyUnicode_FromString("sha3_224");
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500444 } else if (type == state->sha3_256_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200445 return PyUnicode_FromString("sha3_256");
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500446 } else if (type == state->sha3_384_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200447 return PyUnicode_FromString("sha3_384");
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500448 } else if (type == state->sha3_512_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200449 return PyUnicode_FromString("sha3_512");
450#ifdef PY_WITH_KECCAK
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500451 } else if (type == state->keccak_224_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200452 return PyUnicode_FromString("keccak_224");
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500453 } else if (type == state->keccak_256_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200454 return PyUnicode_FromString("keccak_256");
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500455 } else if (type == state->keccak_384_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200456 return PyUnicode_FromString("keccak_384");
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500457 } else if (type == state->keccak_512_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200458 return PyUnicode_FromString("keccak_512");
459#endif
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500460 } else if (type == state->shake_128_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200461 return PyUnicode_FromString("shake_128");
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500462 } else if (type == state->shake_256_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200463 return PyUnicode_FromString("shake_256");
464 } else {
465 PyErr_BadInternalCall();
466 return NULL;
467 }
468}
469
470
471static PyObject *
472SHA3_get_digest_size(SHA3object *self, void *closure)
473{
474 return PyLong_FromLong(self->hash_state.fixedOutputLength / 8);
475}
476
477
478static PyObject *
479SHA3_get_capacity_bits(SHA3object *self, void *closure)
480{
481 int capacity = 1600 - self->hash_state.sponge.rate;
482 return PyLong_FromLong(capacity);
483}
484
485
486static PyObject *
487SHA3_get_rate_bits(SHA3object *self, void *closure)
488{
489 unsigned int rate = self->hash_state.sponge.rate;
490 return PyLong_FromLong(rate);
491}
492
493static PyObject *
494SHA3_get_suffix(SHA3object *self, void *closure)
495{
496 unsigned char suffix[2];
497 suffix[0] = self->hash_state.delimitedSuffix;
498 suffix[1] = 0;
499 return PyBytes_FromStringAndSize((const char *)suffix, 1);
500}
501
Christian Heimes6fe2a752016-09-07 11:58:24 +0200502static PyGetSetDef SHA3_getseters[] = {
503 {"block_size", (getter)SHA3_get_block_size, NULL, NULL, NULL},
504 {"name", (getter)SHA3_get_name, NULL, NULL, NULL},
505 {"digest_size", (getter)SHA3_get_digest_size, NULL, NULL, NULL},
506 {"_capacity_bits", (getter)SHA3_get_capacity_bits, NULL, NULL, NULL},
507 {"_rate_bits", (getter)SHA3_get_rate_bits, NULL, NULL, NULL},
508 {"_suffix", (getter)SHA3_get_suffix, NULL, NULL, NULL},
509 {NULL} /* Sentinel */
510};
511
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500512#define SHA3_TYPE_SLOTS(type_slots_obj, type_doc, type_methods) \
513 static PyType_Slot type_slots_obj[] = { \
514 {Py_tp_dealloc, SHA3_dealloc}, \
515 {Py_tp_doc, (char*)type_doc}, \
516 {Py_tp_methods, type_methods}, \
517 {Py_tp_getset, SHA3_getseters}, \
518 {Py_tp_new, py_sha3_new}, \
519 {0,0} \
520 }
Christian Heimes6fe2a752016-09-07 11:58:24 +0200521
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500522// Using PyType_GetModuleState() on these types is safe since they
523// cannot be subclassed: it does not have the Py_TPFLAGS_BASETYPE flag.
524#define SHA3_TYPE_SPEC(type_spec_obj, type_name, type_slots) \
525 static PyType_Spec type_spec_obj = { \
526 .name = "_sha3." type_name, \
527 .basicsize = sizeof(SHA3object), \
528 .flags = Py_TPFLAGS_DEFAULT, \
529 .slots = type_slots \
Christian Heimes6fe2a752016-09-07 11:58:24 +0200530 }
531
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300532PyDoc_STRVAR(sha3_224__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200533"sha3_224([data], *, usedforsecurity=True) -> SHA3 object\n\
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300534\n\
535Return a new SHA3 hash object with a hashbit length of 28 bytes.");
536
Christian Heimes6fe2a752016-09-07 11:58:24 +0200537PyDoc_STRVAR(sha3_256__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200538"sha3_256([data], *, usedforsecurity=True) -> SHA3 object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200539\n\
540Return a new SHA3 hash object with a hashbit length of 32 bytes.");
541
542PyDoc_STRVAR(sha3_384__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200543"sha3_384([data], *, usedforsecurity=True) -> SHA3 object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200544\n\
545Return a new SHA3 hash object with a hashbit length of 48 bytes.");
546
547PyDoc_STRVAR(sha3_512__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200548"sha3_512([data], *, usedforsecurity=True) -> SHA3 object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200549\n\
550Return a new SHA3 hash object with a hashbit length of 64 bytes.");
551
Christian Heimes6fe2a752016-09-07 11:58:24 +0200552#ifdef PY_WITH_KECCAK
553PyDoc_STRVAR(keccak_224__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200554"keccak_224([data], *, usedforsecurity=True) -> Keccak object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200555\n\
556Return a new Keccak hash object with a hashbit length of 28 bytes.");
557
558PyDoc_STRVAR(keccak_256__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200559"keccak_256([data], *, usedforsecurity=True) -> Keccak object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200560\n\
561Return a new Keccak hash object with a hashbit length of 32 bytes.");
562
563PyDoc_STRVAR(keccak_384__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200564"keccak_384([data], *, usedforsecurity=True) -> Keccak object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200565\n\
566Return a new Keccak hash object with a hashbit length of 48 bytes.");
567
568PyDoc_STRVAR(keccak_512__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200569"keccak_512([data], *, usedforsecurity=True) -> Keccak object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200570\n\
571Return a new Keccak hash object with a hashbit length of 64 bytes.");
572
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500573#endif
574
575SHA3_TYPE_SLOTS(sha3_224_slots, sha3_224__doc__, SHA3_methods);
576SHA3_TYPE_SPEC(sha3_224_spec, "sha3_224", sha3_224_slots);
577
578SHA3_TYPE_SLOTS(sha3_256_slots, sha3_256__doc__, SHA3_methods);
579SHA3_TYPE_SPEC(sha3_256_spec, "sha3_256", sha3_256_slots);
580
581SHA3_TYPE_SLOTS(sha3_384_slots, sha3_384__doc__, SHA3_methods);
582SHA3_TYPE_SPEC(sha3_384_spec, "sha3_384", sha3_384_slots);
583
584SHA3_TYPE_SLOTS(sha3_512_slots, sha3_512__doc__, SHA3_methods);
585SHA3_TYPE_SPEC(sha3_512_spec, "sha3_512", sha3_512_slots);
586
587#ifdef PY_WITH_KECCAK
588SHA3_TYPE_SLOTS(Keccak_224_slots, keccak_224__doc__, SHA3_methods);
589SHA3_TYPE_SPEC(Keccak_224_spec, "keccak_224", Keccak_224_slots);
590
591SHA3_TYPE_SLOTS(Keccak_256_slots, keccak_256__doc__, SHA3_methods);
592SHA3_TYPE_SPEC(Keccak_256_spec, "keccak_256", Keccak_256_slots);
593
594SHA3_TYPE_SLOTS(Keccak_384_slots, keccak_384__doc__, SHA3_methods);
595SHA3_TYPE_SPEC(Keccak_384_spec, "keccak_384", Keccak_384_slots);
596
597SHA3_TYPE_SLOTS(Keccak_512_slots, keccak_512__doc__, SHA3_methods);
598SHA3_TYPE_SPEC(Keccak_512_spec, "keccak_512", Keccak_512_slots);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200599#endif
600
601
602static PyObject *
603_SHAKE_digest(SHA3object *self, unsigned long digestlen, int hex)
604{
605 unsigned char *digest = NULL;
606 SHA3_state temp;
607 int res;
608 PyObject *result = NULL;
609
Serhiy Storchaka9b8c2e72018-10-11 07:41:00 +0300610 if (digestlen >= (1 << 29)) {
611 PyErr_SetString(PyExc_ValueError, "length is too large");
612 return NULL;
613 }
Christian Heimescf45ee12016-09-08 13:35:00 +0200614 /* ExtractLane needs at least SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE and
615 * SHA3_LANESIZE extra space.
616 */
Christian Heimesc71ec8a2016-09-08 15:04:38 +0200617 digest = (unsigned char*)PyMem_Malloc(digestlen + SHA3_LANESIZE);
Christian Heimescf45ee12016-09-08 13:35:00 +0200618 if (digest == NULL) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200619 return PyErr_NoMemory();
620 }
621
622 /* Get the raw (binary) digest value */
623 ENTER_HASHLIB(self);
624 SHA3_copystate(temp, self->hash_state);
625 LEAVE_HASHLIB(self);
626 res = SHA3_done(&temp, NULL);
627 if (res != SUCCESS) {
628 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 done()");
629 goto error;
630 }
631 res = SHA3_squeeze(&temp, digest, digestlen * 8);
632 if (res != SUCCESS) {
633 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Squeeze()");
634 return NULL;
635 }
636 if (hex) {
637 result = _Py_strhex((const char *)digest, digestlen);
638 } else {
639 result = PyBytes_FromStringAndSize((const char *)digest,
640 digestlen);
641 }
642 error:
643 if (digest != NULL) {
644 PyMem_Free(digest);
645 }
646 return result;
647}
648
649
650/*[clinic input]
651_sha3.shake_128.digest
652
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300653 length: unsigned_long
654 /
Christian Heimes6fe2a752016-09-07 11:58:24 +0200655
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300656Return the digest value as a bytes object.
Christian Heimes6fe2a752016-09-07 11:58:24 +0200657[clinic start generated code]*/
658
659static PyObject *
660_sha3_shake_128_digest_impl(SHA3object *self, unsigned long length)
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300661/*[clinic end generated code: output=2313605e2f87bb8f input=418ef6a36d2e6082]*/
Christian Heimes6fe2a752016-09-07 11:58:24 +0200662{
663 return _SHAKE_digest(self, length, 0);
664}
665
666
667/*[clinic input]
668_sha3.shake_128.hexdigest
669
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300670 length: unsigned_long
671 /
Christian Heimes6fe2a752016-09-07 11:58:24 +0200672
673Return the digest value as a string of hexadecimal digits.
674[clinic start generated code]*/
675
676static PyObject *
677_sha3_shake_128_hexdigest_impl(SHA3object *self, unsigned long length)
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300678/*[clinic end generated code: output=bf8e2f1e490944a8 input=69fb29b0926ae321]*/
Christian Heimes6fe2a752016-09-07 11:58:24 +0200679{
680 return _SHAKE_digest(self, length, 1);
681}
682
683
684static PyMethodDef SHAKE_methods[] = {
685 _SHA3_SHA3_224_COPY_METHODDEF
686 _SHA3_SHAKE_128_DIGEST_METHODDEF
687 _SHA3_SHAKE_128_HEXDIGEST_METHODDEF
688 _SHA3_SHA3_224_UPDATE_METHODDEF
689 {NULL, NULL} /* sentinel */
690};
691
692PyDoc_STRVAR(shake_128__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200693"shake_128([data], *, usedforsecurity=True) -> SHAKE object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200694\n\
695Return a new SHAKE hash object.");
696
697PyDoc_STRVAR(shake_256__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200698"shake_256([data], *, usedforsecurity=True) -> SHAKE object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200699\n\
700Return a new SHAKE hash object.");
701
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500702SHA3_TYPE_SLOTS(SHAKE128slots, shake_128__doc__, SHAKE_methods);
703SHA3_TYPE_SPEC(SHAKE128_spec, "shake_128", SHAKE128slots);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200704
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500705SHA3_TYPE_SLOTS(SHAKE256slots, shake_256__doc__, SHAKE_methods);
706SHA3_TYPE_SPEC(SHAKE256_spec, "shake_256", SHAKE256slots);
707
708
709static int
710_sha3_traverse(PyObject *module, visitproc visit, void *arg)
711{
712 SHA3State *state = sha3_get_state(module);
713 Py_VISIT(state->sha3_224_type);
714 Py_VISIT(state->sha3_256_type);
715 Py_VISIT(state->sha3_384_type);
716 Py_VISIT(state->sha3_512_type);
717#ifdef PY_WITH_KECCAK
718 Py_VISIT(state->keccak_224_type);
719 Py_VISIT(state->keccak_256_type);
720 Py_VISIT(state->keccak_384_type);
721 Py_VISIT(state->keccak_512_type);
722#endif
723 Py_VISIT(state->shake_128_type);
724 Py_VISIT(state->shake_256_type);
725 return 0;
726}
727
728static int
729_sha3_clear(PyObject *module)
730{
731 SHA3State *state = sha3_get_state(module);
732 Py_CLEAR(state->sha3_224_type);
733 Py_CLEAR(state->sha3_256_type);
734 Py_CLEAR(state->sha3_384_type);
735 Py_CLEAR(state->sha3_512_type);
736#ifdef PY_WITH_KECCAK
737 Py_CLEAR(state->keccak_224_type);
738 Py_CLEAR(state->keccak_256_type);
739 Py_CLEAR(state->keccak_384_type);
740 Py_CLEAR(state->keccak_512_type);
741#endif
742 Py_CLEAR(state->shake_128_type);
743 Py_CLEAR(state->shake_256_type);
744 return 0;
745}
746
747static void
748_sha3_free(void *module)
749{
750 _sha3_clear((PyObject *)module);
751}
752
753static int
754_sha3_exec(PyObject *m)
755{
756 SHA3State *st = sha3_get_state(m);
757
758#define init_sha3type(type, typespec) \
759 do { \
760 st->type = (PyTypeObject *)PyType_FromModuleAndSpec( \
761 m, &typespec, NULL); \
762 if (st->type == NULL) { \
763 return -1; \
764 } \
765 if (PyModule_AddType(m, st->type) < 0) { \
766 return -1; \
767 } \
768 } while(0)
769
770 init_sha3type(sha3_224_type, sha3_224_spec);
771 init_sha3type(sha3_256_type, sha3_256_spec);
772 init_sha3type(sha3_384_type, sha3_384_spec);
773 init_sha3type(sha3_512_type, sha3_512_spec);
774#ifdef PY_WITH_KECCAK
775 init_sha3type(keccak_224_type, Keccak_224_spec);
776 init_sha3type(keccak_256_type, Keccak_256_spec);
777 init_sha3type(keccak_384_type, Keccak_384_spec);
778 init_sha3type(keccak_512_type, Keccak_512_spec);
779#endif
780 init_sha3type(shake_128_type, SHAKE128_spec);
781 init_sha3type(shake_256_type, SHAKE256_spec);
782#undef init_sha3type
783
784 if (PyModule_AddIntConstant(m, "keccakopt", KeccakOpt) < 0) {
785 return -1;
786 }
787 if (PyModule_AddStringConstant(m, "implementation",
788 KeccakP1600_implementation) < 0) {
789 return -1;
790 }
791
792 return 0;
793}
794
795static PyModuleDef_Slot _sha3_slots[] = {
796 {Py_mod_exec, _sha3_exec},
797 {0, NULL}
798};
Christian Heimes6fe2a752016-09-07 11:58:24 +0200799
800/* Initialize this module. */
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500801static struct PyModuleDef _sha3module = {
802 PyModuleDef_HEAD_INIT,
803 .m_name = "_sha3",
804 .m_size = sizeof(SHA3State),
805 .m_slots = _sha3_slots,
806 .m_traverse = _sha3_traverse,
807 .m_clear = _sha3_clear,
808 .m_free = _sha3_free,
Christian Heimes6fe2a752016-09-07 11:58:24 +0200809};
810
811
812PyMODINIT_FUNC
813PyInit__sha3(void)
814{
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500815 return PyModuleDef_Init(&_sha3module);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200816}