blob: cae10f99d5b8df95e9b4c11d22c5acc7b479720f [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{
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500196 SHA3object *self = newSHA3object(type);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200197 if (self == NULL) {
198 goto error;
199 }
200
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500201 SHA3State *state = PyType_GetModuleState(type);
202 assert(state != NULL);
203
204 HashReturn res;
205 if (type == state->sha3_224_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200206 res = Keccak_HashInitialize_SHA3_224(&self->hash_state);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500207 } else if (type == state->sha3_256_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200208 res = Keccak_HashInitialize_SHA3_256(&self->hash_state);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500209 } else if (type == state->sha3_384_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200210 res = Keccak_HashInitialize_SHA3_384(&self->hash_state);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500211 } else if (type == state->sha3_512_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200212 res = Keccak_HashInitialize_SHA3_512(&self->hash_state);
213#ifdef PY_WITH_KECCAK
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500214 } else if (type == state->keccak_224_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200215 res = Keccak_HashInitialize(&self->hash_state, 1152, 448, 224, 0x01);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500216 } else if (type == state->keccak_256_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200217 res = Keccak_HashInitialize(&self->hash_state, 1088, 512, 256, 0x01);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500218 } else if (type == state->keccak_384_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200219 res = Keccak_HashInitialize(&self->hash_state, 832, 768, 384, 0x01);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500220 } else if (type == state->keccak_512_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200221 res = Keccak_HashInitialize(&self->hash_state, 576, 1024, 512, 0x01);
222#endif
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500223 } else if (type == state->shake_128_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200224 res = Keccak_HashInitialize_SHAKE128(&self->hash_state);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500225 } else if (type == state->shake_256_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200226 res = Keccak_HashInitialize_SHAKE256(&self->hash_state);
227 } else {
228 PyErr_BadInternalCall();
229 goto error;
230 }
231
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500232 Py_buffer buf = {NULL, NULL};
Christian Heimes6fe2a752016-09-07 11:58:24 +0200233 if (data) {
234 GET_BUFFER_VIEW_OR_ERROR(data, &buf, goto error);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200235 if (buf.len >= HASHLIB_GIL_MINSIZE) {
236 /* invariant: New objects can't be accessed by other code yet,
237 * thus it's safe to release the GIL without locking the object.
238 */
239 Py_BEGIN_ALLOW_THREADS
240 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
241 Py_END_ALLOW_THREADS
242 }
243 else {
244 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
245 }
Christian Heimes6fe2a752016-09-07 11:58:24 +0200246 if (res != SUCCESS) {
247 PyErr_SetString(PyExc_RuntimeError,
248 "internal error in SHA3 Update()");
249 goto error;
250 }
251 PyBuffer_Release(&buf);
252 }
253
254 return (PyObject *)self;
255
256 error:
257 if (self) {
258 Py_DECREF(self);
259 }
260 if (data && buf.obj) {
261 PyBuffer_Release(&buf);
262 }
263 return NULL;
264}
265
266
267/* Internal methods for a hash object */
268
269static void
270SHA3_dealloc(SHA3object *self)
271{
Christian Heimes6fe2a752016-09-07 11:58:24 +0200272 if (self->lock) {
273 PyThread_free_lock(self->lock);
274 }
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500275
276 PyTypeObject *tp = Py_TYPE(self);
Victor Stinner32bd68c2020-12-01 10:37:39 +0100277 PyObject_Free(self);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500278 Py_DECREF(tp);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200279}
280
281
282/* External methods for a hash object */
283
284
285/*[clinic input]
286_sha3.sha3_224.copy
287
288Return a copy of the hash object.
289[clinic start generated code]*/
290
291static PyObject *
292_sha3_sha3_224_copy_impl(SHA3object *self)
293/*[clinic end generated code: output=6c537411ecdcda4c input=93a44aaebea51ba8]*/
294{
295 SHA3object *newobj;
296
297 if ((newobj = newSHA3object(Py_TYPE(self))) == NULL) {
298 return NULL;
299 }
300 ENTER_HASHLIB(self);
301 SHA3_copystate(newobj->hash_state, self->hash_state);
302 LEAVE_HASHLIB(self);
303 return (PyObject *)newobj;
304}
305
306
307/*[clinic input]
308_sha3.sha3_224.digest
309
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300310Return the digest value as a bytes object.
Christian Heimes6fe2a752016-09-07 11:58:24 +0200311[clinic start generated code]*/
312
313static PyObject *
314_sha3_sha3_224_digest_impl(SHA3object *self)
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300315/*[clinic end generated code: output=fd531842e20b2d5b input=5b2a659536bbd248]*/
Christian Heimes6fe2a752016-09-07 11:58:24 +0200316{
Christian Heimescf45ee12016-09-08 13:35:00 +0200317 unsigned char digest[SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE];
Christian Heimes6fe2a752016-09-07 11:58:24 +0200318 SHA3_state temp;
319 HashReturn res;
320
321 ENTER_HASHLIB(self);
322 SHA3_copystate(temp, self->hash_state);
323 LEAVE_HASHLIB(self);
324 res = SHA3_done(&temp, digest);
325 if (res != SUCCESS) {
326 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Final()");
327 return NULL;
328 }
329 return PyBytes_FromStringAndSize((const char *)digest,
330 self->hash_state.fixedOutputLength / 8);
331}
332
333
334/*[clinic input]
335_sha3.sha3_224.hexdigest
336
337Return the digest value as a string of hexadecimal digits.
338[clinic start generated code]*/
339
340static PyObject *
341_sha3_sha3_224_hexdigest_impl(SHA3object *self)
342/*[clinic end generated code: output=75ad03257906918d input=2d91bb6e0d114ee3]*/
343{
Christian Heimescf45ee12016-09-08 13:35:00 +0200344 unsigned char digest[SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE];
Christian Heimes6fe2a752016-09-07 11:58:24 +0200345 SHA3_state temp;
346 HashReturn res;
347
348 /* Get the raw (binary) digest value */
349 ENTER_HASHLIB(self);
350 SHA3_copystate(temp, self->hash_state);
351 LEAVE_HASHLIB(self);
352 res = SHA3_done(&temp, digest);
353 if (res != SUCCESS) {
354 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Final()");
355 return NULL;
356 }
357 return _Py_strhex((const char *)digest,
358 self->hash_state.fixedOutputLength / 8);
359}
360
361
362/*[clinic input]
363_sha3.sha3_224.update
364
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300365 data: object
Christian Heimes6fe2a752016-09-07 11:58:24 +0200366 /
367
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300368Update this hash object's state with the provided bytes-like object.
Christian Heimes6fe2a752016-09-07 11:58:24 +0200369[clinic start generated code]*/
370
371static PyObject *
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300372_sha3_sha3_224_update(SHA3object *self, PyObject *data)
373/*[clinic end generated code: output=d3223352286ed357 input=a887f54dcc4ae227]*/
Christian Heimes6fe2a752016-09-07 11:58:24 +0200374{
375 Py_buffer buf;
376 HashReturn res;
377
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300378 GET_BUFFER_VIEW_OR_ERROUT(data, &buf);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200379
380 /* add new data, the function takes the length in bits not bytes */
Christian Heimes6fe2a752016-09-07 11:58:24 +0200381 if (self->lock == NULL && buf.len >= HASHLIB_GIL_MINSIZE) {
382 self->lock = PyThread_allocate_lock();
383 }
384 /* Once a lock exists all code paths must be synchronized. We have to
385 * release the GIL even for small buffers as acquiring the lock may take
386 * an unlimited amount of time when another thread updates this object
387 * with lots of data. */
388 if (self->lock) {
389 Py_BEGIN_ALLOW_THREADS
390 PyThread_acquire_lock(self->lock, 1);
391 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
392 PyThread_release_lock(self->lock);
393 Py_END_ALLOW_THREADS
394 }
395 else {
396 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
397 }
Christian Heimes6fe2a752016-09-07 11:58:24 +0200398
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);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200407 Py_RETURN_NONE;
Christian Heimes6fe2a752016-09-07 11:58:24 +0200408}
409
410
411static PyMethodDef SHA3_methods[] = {
412 _SHA3_SHA3_224_COPY_METHODDEF
413 _SHA3_SHA3_224_DIGEST_METHODDEF
414 _SHA3_SHA3_224_HEXDIGEST_METHODDEF
415 _SHA3_SHA3_224_UPDATE_METHODDEF
416 {NULL, NULL} /* sentinel */
417};
418
419
420static PyObject *
421SHA3_get_block_size(SHA3object *self, void *closure)
422{
423 int rate = self->hash_state.sponge.rate;
424 return PyLong_FromLong(rate / 8);
425}
426
427
428static PyObject *
429SHA3_get_name(SHA3object *self, void *closure)
430{
431 PyTypeObject *type = Py_TYPE(self);
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500432
433 SHA3State *state = PyType_GetModuleState(type);
434 assert(state != NULL);
435
436 if (type == state->sha3_224_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200437 return PyUnicode_FromString("sha3_224");
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500438 } else if (type == state->sha3_256_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200439 return PyUnicode_FromString("sha3_256");
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500440 } else if (type == state->sha3_384_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200441 return PyUnicode_FromString("sha3_384");
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500442 } else if (type == state->sha3_512_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200443 return PyUnicode_FromString("sha3_512");
444#ifdef PY_WITH_KECCAK
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500445 } else if (type == state->keccak_224_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200446 return PyUnicode_FromString("keccak_224");
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500447 } else if (type == state->keccak_256_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200448 return PyUnicode_FromString("keccak_256");
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500449 } else if (type == state->keccak_384_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200450 return PyUnicode_FromString("keccak_384");
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500451 } else if (type == state->keccak_512_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200452 return PyUnicode_FromString("keccak_512");
453#endif
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500454 } else if (type == state->shake_128_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200455 return PyUnicode_FromString("shake_128");
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500456 } else if (type == state->shake_256_type) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200457 return PyUnicode_FromString("shake_256");
458 } else {
459 PyErr_BadInternalCall();
460 return NULL;
461 }
462}
463
464
465static PyObject *
466SHA3_get_digest_size(SHA3object *self, void *closure)
467{
468 return PyLong_FromLong(self->hash_state.fixedOutputLength / 8);
469}
470
471
472static PyObject *
473SHA3_get_capacity_bits(SHA3object *self, void *closure)
474{
475 int capacity = 1600 - self->hash_state.sponge.rate;
476 return PyLong_FromLong(capacity);
477}
478
479
480static PyObject *
481SHA3_get_rate_bits(SHA3object *self, void *closure)
482{
483 unsigned int rate = self->hash_state.sponge.rate;
484 return PyLong_FromLong(rate);
485}
486
487static PyObject *
488SHA3_get_suffix(SHA3object *self, void *closure)
489{
490 unsigned char suffix[2];
491 suffix[0] = self->hash_state.delimitedSuffix;
492 suffix[1] = 0;
493 return PyBytes_FromStringAndSize((const char *)suffix, 1);
494}
495
Christian Heimes6fe2a752016-09-07 11:58:24 +0200496static PyGetSetDef SHA3_getseters[] = {
497 {"block_size", (getter)SHA3_get_block_size, NULL, NULL, NULL},
498 {"name", (getter)SHA3_get_name, NULL, NULL, NULL},
499 {"digest_size", (getter)SHA3_get_digest_size, NULL, NULL, NULL},
500 {"_capacity_bits", (getter)SHA3_get_capacity_bits, NULL, NULL, NULL},
501 {"_rate_bits", (getter)SHA3_get_rate_bits, NULL, NULL, NULL},
502 {"_suffix", (getter)SHA3_get_suffix, NULL, NULL, NULL},
503 {NULL} /* Sentinel */
504};
505
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500506#define SHA3_TYPE_SLOTS(type_slots_obj, type_doc, type_methods) \
507 static PyType_Slot type_slots_obj[] = { \
508 {Py_tp_dealloc, SHA3_dealloc}, \
509 {Py_tp_doc, (char*)type_doc}, \
510 {Py_tp_methods, type_methods}, \
511 {Py_tp_getset, SHA3_getseters}, \
512 {Py_tp_new, py_sha3_new}, \
513 {0,0} \
514 }
Christian Heimes6fe2a752016-09-07 11:58:24 +0200515
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500516// Using PyType_GetModuleState() on these types is safe since they
517// cannot be subclassed: it does not have the Py_TPFLAGS_BASETYPE flag.
518#define SHA3_TYPE_SPEC(type_spec_obj, type_name, type_slots) \
519 static PyType_Spec type_spec_obj = { \
520 .name = "_sha3." type_name, \
521 .basicsize = sizeof(SHA3object), \
522 .flags = Py_TPFLAGS_DEFAULT, \
523 .slots = type_slots \
Christian Heimes6fe2a752016-09-07 11:58:24 +0200524 }
525
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300526PyDoc_STRVAR(sha3_224__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200527"sha3_224([data], *, usedforsecurity=True) -> SHA3 object\n\
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300528\n\
529Return a new SHA3 hash object with a hashbit length of 28 bytes.");
530
Christian Heimes6fe2a752016-09-07 11:58:24 +0200531PyDoc_STRVAR(sha3_256__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200532"sha3_256([data], *, usedforsecurity=True) -> SHA3 object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200533\n\
534Return a new SHA3 hash object with a hashbit length of 32 bytes.");
535
536PyDoc_STRVAR(sha3_384__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200537"sha3_384([data], *, usedforsecurity=True) -> SHA3 object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200538\n\
539Return a new SHA3 hash object with a hashbit length of 48 bytes.");
540
541PyDoc_STRVAR(sha3_512__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200542"sha3_512([data], *, usedforsecurity=True) -> SHA3 object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200543\n\
544Return a new SHA3 hash object with a hashbit length of 64 bytes.");
545
Christian Heimes6fe2a752016-09-07 11:58:24 +0200546#ifdef PY_WITH_KECCAK
547PyDoc_STRVAR(keccak_224__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200548"keccak_224([data], *, usedforsecurity=True) -> Keccak object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200549\n\
550Return a new Keccak hash object with a hashbit length of 28 bytes.");
551
552PyDoc_STRVAR(keccak_256__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200553"keccak_256([data], *, usedforsecurity=True) -> Keccak object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200554\n\
555Return a new Keccak hash object with a hashbit length of 32 bytes.");
556
557PyDoc_STRVAR(keccak_384__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200558"keccak_384([data], *, usedforsecurity=True) -> Keccak object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200559\n\
560Return a new Keccak hash object with a hashbit length of 48 bytes.");
561
562PyDoc_STRVAR(keccak_512__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200563"keccak_512([data], *, usedforsecurity=True) -> Keccak object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200564\n\
565Return a new Keccak hash object with a hashbit length of 64 bytes.");
566
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500567#endif
568
569SHA3_TYPE_SLOTS(sha3_224_slots, sha3_224__doc__, SHA3_methods);
570SHA3_TYPE_SPEC(sha3_224_spec, "sha3_224", sha3_224_slots);
571
572SHA3_TYPE_SLOTS(sha3_256_slots, sha3_256__doc__, SHA3_methods);
573SHA3_TYPE_SPEC(sha3_256_spec, "sha3_256", sha3_256_slots);
574
575SHA3_TYPE_SLOTS(sha3_384_slots, sha3_384__doc__, SHA3_methods);
576SHA3_TYPE_SPEC(sha3_384_spec, "sha3_384", sha3_384_slots);
577
578SHA3_TYPE_SLOTS(sha3_512_slots, sha3_512__doc__, SHA3_methods);
579SHA3_TYPE_SPEC(sha3_512_spec, "sha3_512", sha3_512_slots);
580
581#ifdef PY_WITH_KECCAK
582SHA3_TYPE_SLOTS(Keccak_224_slots, keccak_224__doc__, SHA3_methods);
583SHA3_TYPE_SPEC(Keccak_224_spec, "keccak_224", Keccak_224_slots);
584
585SHA3_TYPE_SLOTS(Keccak_256_slots, keccak_256__doc__, SHA3_methods);
586SHA3_TYPE_SPEC(Keccak_256_spec, "keccak_256", Keccak_256_slots);
587
588SHA3_TYPE_SLOTS(Keccak_384_slots, keccak_384__doc__, SHA3_methods);
589SHA3_TYPE_SPEC(Keccak_384_spec, "keccak_384", Keccak_384_slots);
590
591SHA3_TYPE_SLOTS(Keccak_512_slots, keccak_512__doc__, SHA3_methods);
592SHA3_TYPE_SPEC(Keccak_512_spec, "keccak_512", Keccak_512_slots);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200593#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
Serhiy Storchaka9b8c2e72018-10-11 07:41:00 +0300604 if (digestlen >= (1 << 29)) {
605 PyErr_SetString(PyExc_ValueError, "length is too large");
606 return NULL;
607 }
Christian Heimescf45ee12016-09-08 13:35:00 +0200608 /* ExtractLane needs at least SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE and
609 * SHA3_LANESIZE extra space.
610 */
Christian Heimesc71ec8a2016-09-08 15:04:38 +0200611 digest = (unsigned char*)PyMem_Malloc(digestlen + SHA3_LANESIZE);
Christian Heimescf45ee12016-09-08 13:35:00 +0200612 if (digest == NULL) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200613 return PyErr_NoMemory();
614 }
615
616 /* Get the raw (binary) digest value */
617 ENTER_HASHLIB(self);
618 SHA3_copystate(temp, self->hash_state);
619 LEAVE_HASHLIB(self);
620 res = SHA3_done(&temp, NULL);
621 if (res != SUCCESS) {
622 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 done()");
623 goto error;
624 }
625 res = SHA3_squeeze(&temp, digest, digestlen * 8);
626 if (res != SUCCESS) {
627 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Squeeze()");
628 return NULL;
629 }
630 if (hex) {
631 result = _Py_strhex((const char *)digest, digestlen);
632 } else {
633 result = PyBytes_FromStringAndSize((const char *)digest,
634 digestlen);
635 }
636 error:
637 if (digest != NULL) {
638 PyMem_Free(digest);
639 }
640 return result;
641}
642
643
644/*[clinic input]
645_sha3.shake_128.digest
646
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300647 length: unsigned_long
648 /
Christian Heimes6fe2a752016-09-07 11:58:24 +0200649
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300650Return the digest value as a bytes object.
Christian Heimes6fe2a752016-09-07 11:58:24 +0200651[clinic start generated code]*/
652
653static PyObject *
654_sha3_shake_128_digest_impl(SHA3object *self, unsigned long length)
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300655/*[clinic end generated code: output=2313605e2f87bb8f input=418ef6a36d2e6082]*/
Christian Heimes6fe2a752016-09-07 11:58:24 +0200656{
657 return _SHAKE_digest(self, length, 0);
658}
659
660
661/*[clinic input]
662_sha3.shake_128.hexdigest
663
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300664 length: unsigned_long
665 /
Christian Heimes6fe2a752016-09-07 11:58:24 +0200666
667Return the digest value as a string of hexadecimal digits.
668[clinic start generated code]*/
669
670static PyObject *
671_sha3_shake_128_hexdigest_impl(SHA3object *self, unsigned long length)
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300672/*[clinic end generated code: output=bf8e2f1e490944a8 input=69fb29b0926ae321]*/
Christian Heimes6fe2a752016-09-07 11:58:24 +0200673{
674 return _SHAKE_digest(self, length, 1);
675}
676
677
678static PyMethodDef SHAKE_methods[] = {
679 _SHA3_SHA3_224_COPY_METHODDEF
680 _SHA3_SHAKE_128_DIGEST_METHODDEF
681 _SHA3_SHAKE_128_HEXDIGEST_METHODDEF
682 _SHA3_SHA3_224_UPDATE_METHODDEF
683 {NULL, NULL} /* sentinel */
684};
685
686PyDoc_STRVAR(shake_128__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200687"shake_128([data], *, usedforsecurity=True) -> SHAKE object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200688\n\
689Return a new SHAKE hash object.");
690
691PyDoc_STRVAR(shake_256__doc__,
Christian Heimes7cad53e2019-09-13 02:30:00 +0200692"shake_256([data], *, usedforsecurity=True) -> SHAKE object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200693\n\
694Return a new SHAKE hash object.");
695
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500696SHA3_TYPE_SLOTS(SHAKE128slots, shake_128__doc__, SHAKE_methods);
697SHA3_TYPE_SPEC(SHAKE128_spec, "shake_128", SHAKE128slots);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200698
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500699SHA3_TYPE_SLOTS(SHAKE256slots, shake_256__doc__, SHAKE_methods);
700SHA3_TYPE_SPEC(SHAKE256_spec, "shake_256", SHAKE256slots);
701
702
703static int
704_sha3_traverse(PyObject *module, visitproc visit, void *arg)
705{
706 SHA3State *state = sha3_get_state(module);
707 Py_VISIT(state->sha3_224_type);
708 Py_VISIT(state->sha3_256_type);
709 Py_VISIT(state->sha3_384_type);
710 Py_VISIT(state->sha3_512_type);
711#ifdef PY_WITH_KECCAK
712 Py_VISIT(state->keccak_224_type);
713 Py_VISIT(state->keccak_256_type);
714 Py_VISIT(state->keccak_384_type);
715 Py_VISIT(state->keccak_512_type);
716#endif
717 Py_VISIT(state->shake_128_type);
718 Py_VISIT(state->shake_256_type);
719 return 0;
720}
721
722static int
723_sha3_clear(PyObject *module)
724{
725 SHA3State *state = sha3_get_state(module);
726 Py_CLEAR(state->sha3_224_type);
727 Py_CLEAR(state->sha3_256_type);
728 Py_CLEAR(state->sha3_384_type);
729 Py_CLEAR(state->sha3_512_type);
730#ifdef PY_WITH_KECCAK
731 Py_CLEAR(state->keccak_224_type);
732 Py_CLEAR(state->keccak_256_type);
733 Py_CLEAR(state->keccak_384_type);
734 Py_CLEAR(state->keccak_512_type);
735#endif
736 Py_CLEAR(state->shake_128_type);
737 Py_CLEAR(state->shake_256_type);
738 return 0;
739}
740
741static void
742_sha3_free(void *module)
743{
744 _sha3_clear((PyObject *)module);
745}
746
747static int
748_sha3_exec(PyObject *m)
749{
750 SHA3State *st = sha3_get_state(m);
751
752#define init_sha3type(type, typespec) \
753 do { \
754 st->type = (PyTypeObject *)PyType_FromModuleAndSpec( \
755 m, &typespec, NULL); \
756 if (st->type == NULL) { \
757 return -1; \
758 } \
759 if (PyModule_AddType(m, st->type) < 0) { \
760 return -1; \
761 } \
762 } while(0)
763
764 init_sha3type(sha3_224_type, sha3_224_spec);
765 init_sha3type(sha3_256_type, sha3_256_spec);
766 init_sha3type(sha3_384_type, sha3_384_spec);
767 init_sha3type(sha3_512_type, sha3_512_spec);
768#ifdef PY_WITH_KECCAK
769 init_sha3type(keccak_224_type, Keccak_224_spec);
770 init_sha3type(keccak_256_type, Keccak_256_spec);
771 init_sha3type(keccak_384_type, Keccak_384_spec);
772 init_sha3type(keccak_512_type, Keccak_512_spec);
773#endif
774 init_sha3type(shake_128_type, SHAKE128_spec);
775 init_sha3type(shake_256_type, SHAKE256_spec);
776#undef init_sha3type
777
778 if (PyModule_AddIntConstant(m, "keccakopt", KeccakOpt) < 0) {
779 return -1;
780 }
781 if (PyModule_AddStringConstant(m, "implementation",
782 KeccakP1600_implementation) < 0) {
783 return -1;
784 }
785
786 return 0;
787}
788
789static PyModuleDef_Slot _sha3_slots[] = {
790 {Py_mod_exec, _sha3_exec},
791 {0, NULL}
792};
Christian Heimes6fe2a752016-09-07 11:58:24 +0200793
794/* Initialize this module. */
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500795static struct PyModuleDef _sha3module = {
796 PyModuleDef_HEAD_INIT,
797 .m_name = "_sha3",
798 .m_size = sizeof(SHA3State),
799 .m_slots = _sha3_slots,
800 .m_traverse = _sha3_traverse,
801 .m_clear = _sha3_clear,
802 .m_free = _sha3_free,
Christian Heimes6fe2a752016-09-07 11:58:24 +0200803};
804
805
806PyMODINIT_FUNC
807PyInit__sha3(void)
808{
Mohamed Koubaa93d50a62020-09-02 04:55:19 -0500809 return PyModuleDef_Init(&_sha3module);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200810}