blob: 46c1ff1538524df886c7128a66d70edca9198be6 [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
Christian Heimes6fe2a752016-09-07 11:58:24 +0200173static PyObject *
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300174py_sha3_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
Christian Heimes6fe2a752016-09-07 11:58:24 +0200175{
176 SHA3object *self = NULL;
177 Py_buffer buf = {NULL, NULL};
178 HashReturn res;
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300179 PyObject *data = NULL;
180
181 if (!_PyArg_NoKeywords(_PyType_Name(type), kwargs)) {
182 return NULL;
183 }
184 if (!PyArg_UnpackTuple(args, _PyType_Name(type), 0, 1, &data)) {
185 return NULL;
186 }
Christian Heimes6fe2a752016-09-07 11:58:24 +0200187
188 self = newSHA3object(type);
189 if (self == NULL) {
190 goto error;
191 }
192
193 if (type == &SHA3_224type) {
194 res = Keccak_HashInitialize_SHA3_224(&self->hash_state);
195 } else if (type == &SHA3_256type) {
196 res = Keccak_HashInitialize_SHA3_256(&self->hash_state);
197 } else if (type == &SHA3_384type) {
198 res = Keccak_HashInitialize_SHA3_384(&self->hash_state);
199 } else if (type == &SHA3_512type) {
200 res = Keccak_HashInitialize_SHA3_512(&self->hash_state);
201#ifdef PY_WITH_KECCAK
202 } else if (type == &Keccak_224type) {
203 res = Keccak_HashInitialize(&self->hash_state, 1152, 448, 224, 0x01);
204 } else if (type == &Keccak_256type) {
205 res = Keccak_HashInitialize(&self->hash_state, 1088, 512, 256, 0x01);
206 } else if (type == &Keccak_384type) {
207 res = Keccak_HashInitialize(&self->hash_state, 832, 768, 384, 0x01);
208 } else if (type == &Keccak_512type) {
209 res = Keccak_HashInitialize(&self->hash_state, 576, 1024, 512, 0x01);
210#endif
211 } else if (type == &SHAKE128type) {
212 res = Keccak_HashInitialize_SHAKE128(&self->hash_state);
213 } else if (type == &SHAKE256type) {
214 res = Keccak_HashInitialize_SHAKE256(&self->hash_state);
215 } else {
216 PyErr_BadInternalCall();
217 goto error;
218 }
219
220 if (data) {
221 GET_BUFFER_VIEW_OR_ERROR(data, &buf, goto error);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200222 if (buf.len >= HASHLIB_GIL_MINSIZE) {
223 /* invariant: New objects can't be accessed by other code yet,
224 * thus it's safe to release the GIL without locking the object.
225 */
226 Py_BEGIN_ALLOW_THREADS
227 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
228 Py_END_ALLOW_THREADS
229 }
230 else {
231 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
232 }
Christian Heimes6fe2a752016-09-07 11:58:24 +0200233 if (res != SUCCESS) {
234 PyErr_SetString(PyExc_RuntimeError,
235 "internal error in SHA3 Update()");
236 goto error;
237 }
238 PyBuffer_Release(&buf);
239 }
240
241 return (PyObject *)self;
242
243 error:
244 if (self) {
245 Py_DECREF(self);
246 }
247 if (data && buf.obj) {
248 PyBuffer_Release(&buf);
249 }
250 return NULL;
251}
252
253
254/* Internal methods for a hash object */
255
256static void
257SHA3_dealloc(SHA3object *self)
258{
Christian Heimes6fe2a752016-09-07 11:58:24 +0200259 if (self->lock) {
260 PyThread_free_lock(self->lock);
261 }
Christian Heimes6fe2a752016-09-07 11:58:24 +0200262 PyObject_Del(self);
263}
264
265
266/* External methods for a hash object */
267
268
269/*[clinic input]
270_sha3.sha3_224.copy
271
272Return a copy of the hash object.
273[clinic start generated code]*/
274
275static PyObject *
276_sha3_sha3_224_copy_impl(SHA3object *self)
277/*[clinic end generated code: output=6c537411ecdcda4c input=93a44aaebea51ba8]*/
278{
279 SHA3object *newobj;
280
281 if ((newobj = newSHA3object(Py_TYPE(self))) == NULL) {
282 return NULL;
283 }
284 ENTER_HASHLIB(self);
285 SHA3_copystate(newobj->hash_state, self->hash_state);
286 LEAVE_HASHLIB(self);
287 return (PyObject *)newobj;
288}
289
290
291/*[clinic input]
292_sha3.sha3_224.digest
293
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300294Return the digest value as a bytes object.
Christian Heimes6fe2a752016-09-07 11:58:24 +0200295[clinic start generated code]*/
296
297static PyObject *
298_sha3_sha3_224_digest_impl(SHA3object *self)
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300299/*[clinic end generated code: output=fd531842e20b2d5b input=5b2a659536bbd248]*/
Christian Heimes6fe2a752016-09-07 11:58:24 +0200300{
Christian Heimescf45ee12016-09-08 13:35:00 +0200301 unsigned char digest[SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE];
Christian Heimes6fe2a752016-09-07 11:58:24 +0200302 SHA3_state temp;
303 HashReturn res;
304
305 ENTER_HASHLIB(self);
306 SHA3_copystate(temp, self->hash_state);
307 LEAVE_HASHLIB(self);
308 res = SHA3_done(&temp, digest);
309 if (res != SUCCESS) {
310 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Final()");
311 return NULL;
312 }
313 return PyBytes_FromStringAndSize((const char *)digest,
314 self->hash_state.fixedOutputLength / 8);
315}
316
317
318/*[clinic input]
319_sha3.sha3_224.hexdigest
320
321Return the digest value as a string of hexadecimal digits.
322[clinic start generated code]*/
323
324static PyObject *
325_sha3_sha3_224_hexdigest_impl(SHA3object *self)
326/*[clinic end generated code: output=75ad03257906918d input=2d91bb6e0d114ee3]*/
327{
Christian Heimescf45ee12016-09-08 13:35:00 +0200328 unsigned char digest[SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE];
Christian Heimes6fe2a752016-09-07 11:58:24 +0200329 SHA3_state temp;
330 HashReturn res;
331
332 /* Get the raw (binary) digest value */
333 ENTER_HASHLIB(self);
334 SHA3_copystate(temp, self->hash_state);
335 LEAVE_HASHLIB(self);
336 res = SHA3_done(&temp, digest);
337 if (res != SUCCESS) {
338 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Final()");
339 return NULL;
340 }
341 return _Py_strhex((const char *)digest,
342 self->hash_state.fixedOutputLength / 8);
343}
344
345
346/*[clinic input]
347_sha3.sha3_224.update
348
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300349 data: object
Christian Heimes6fe2a752016-09-07 11:58:24 +0200350 /
351
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300352Update this hash object's state with the provided bytes-like object.
Christian Heimes6fe2a752016-09-07 11:58:24 +0200353[clinic start generated code]*/
354
355static PyObject *
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300356_sha3_sha3_224_update(SHA3object *self, PyObject *data)
357/*[clinic end generated code: output=d3223352286ed357 input=a887f54dcc4ae227]*/
Christian Heimes6fe2a752016-09-07 11:58:24 +0200358{
359 Py_buffer buf;
360 HashReturn res;
361
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300362 GET_BUFFER_VIEW_OR_ERROUT(data, &buf);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200363
364 /* add new data, the function takes the length in bits not bytes */
Christian Heimes6fe2a752016-09-07 11:58:24 +0200365 if (self->lock == NULL && buf.len >= HASHLIB_GIL_MINSIZE) {
366 self->lock = PyThread_allocate_lock();
367 }
368 /* Once a lock exists all code paths must be synchronized. We have to
369 * release the GIL even for small buffers as acquiring the lock may take
370 * an unlimited amount of time when another thread updates this object
371 * with lots of data. */
372 if (self->lock) {
373 Py_BEGIN_ALLOW_THREADS
374 PyThread_acquire_lock(self->lock, 1);
375 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
376 PyThread_release_lock(self->lock);
377 Py_END_ALLOW_THREADS
378 }
379 else {
380 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
381 }
Christian Heimes6fe2a752016-09-07 11:58:24 +0200382
383 if (res != SUCCESS) {
384 PyBuffer_Release(&buf);
385 PyErr_SetString(PyExc_RuntimeError,
386 "internal error in SHA3 Update()");
387 return NULL;
388 }
389
390 PyBuffer_Release(&buf);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200391 Py_RETURN_NONE;
Christian Heimes6fe2a752016-09-07 11:58:24 +0200392}
393
394
395static PyMethodDef SHA3_methods[] = {
396 _SHA3_SHA3_224_COPY_METHODDEF
397 _SHA3_SHA3_224_DIGEST_METHODDEF
398 _SHA3_SHA3_224_HEXDIGEST_METHODDEF
399 _SHA3_SHA3_224_UPDATE_METHODDEF
400 {NULL, NULL} /* sentinel */
401};
402
403
404static PyObject *
405SHA3_get_block_size(SHA3object *self, void *closure)
406{
407 int rate = self->hash_state.sponge.rate;
408 return PyLong_FromLong(rate / 8);
409}
410
411
412static PyObject *
413SHA3_get_name(SHA3object *self, void *closure)
414{
415 PyTypeObject *type = Py_TYPE(self);
416 if (type == &SHA3_224type) {
417 return PyUnicode_FromString("sha3_224");
418 } else if (type == &SHA3_256type) {
419 return PyUnicode_FromString("sha3_256");
420 } else if (type == &SHA3_384type) {
421 return PyUnicode_FromString("sha3_384");
422 } else if (type == &SHA3_512type) {
423 return PyUnicode_FromString("sha3_512");
424#ifdef PY_WITH_KECCAK
425 } else if (type == &Keccak_224type) {
426 return PyUnicode_FromString("keccak_224");
427 } else if (type == &Keccak_256type) {
428 return PyUnicode_FromString("keccak_256");
429 } else if (type == &Keccak_384type) {
430 return PyUnicode_FromString("keccak_384");
431 } else if (type == &Keccak_512type) {
432 return PyUnicode_FromString("keccak_512");
433#endif
434 } else if (type == &SHAKE128type) {
435 return PyUnicode_FromString("shake_128");
436 } else if (type == &SHAKE256type) {
437 return PyUnicode_FromString("shake_256");
438 } else {
439 PyErr_BadInternalCall();
440 return NULL;
441 }
442}
443
444
445static PyObject *
446SHA3_get_digest_size(SHA3object *self, void *closure)
447{
448 return PyLong_FromLong(self->hash_state.fixedOutputLength / 8);
449}
450
451
452static PyObject *
453SHA3_get_capacity_bits(SHA3object *self, void *closure)
454{
455 int capacity = 1600 - self->hash_state.sponge.rate;
456 return PyLong_FromLong(capacity);
457}
458
459
460static PyObject *
461SHA3_get_rate_bits(SHA3object *self, void *closure)
462{
463 unsigned int rate = self->hash_state.sponge.rate;
464 return PyLong_FromLong(rate);
465}
466
467static PyObject *
468SHA3_get_suffix(SHA3object *self, void *closure)
469{
470 unsigned char suffix[2];
471 suffix[0] = self->hash_state.delimitedSuffix;
472 suffix[1] = 0;
473 return PyBytes_FromStringAndSize((const char *)suffix, 1);
474}
475
476
477static PyGetSetDef SHA3_getseters[] = {
478 {"block_size", (getter)SHA3_get_block_size, NULL, NULL, NULL},
479 {"name", (getter)SHA3_get_name, NULL, NULL, NULL},
480 {"digest_size", (getter)SHA3_get_digest_size, NULL, NULL, NULL},
481 {"_capacity_bits", (getter)SHA3_get_capacity_bits, NULL, NULL, NULL},
482 {"_rate_bits", (getter)SHA3_get_rate_bits, NULL, NULL, NULL},
483 {"_suffix", (getter)SHA3_get_suffix, NULL, NULL, NULL},
484 {NULL} /* Sentinel */
485};
486
487
488#define SHA3_TYPE(type_obj, type_name, type_doc, type_methods) \
489 static PyTypeObject type_obj = { \
490 PyVarObject_HEAD_INIT(NULL, 0) \
491 type_name, /* tp_name */ \
Peter Eisentraut0e0bc4e2018-09-10 18:46:08 +0200492 sizeof(SHA3object), /* tp_basicsize */ \
Christian Heimes6fe2a752016-09-07 11:58:24 +0200493 0, /* tp_itemsize */ \
494 /* methods */ \
495 (destructor)SHA3_dealloc, /* tp_dealloc */ \
496 0, /* tp_print */ \
497 0, /* tp_getattr */ \
498 0, /* tp_setattr */ \
499 0, /* tp_reserved */ \
500 0, /* tp_repr */ \
501 0, /* tp_as_number */ \
502 0, /* tp_as_sequence */ \
503 0, /* tp_as_mapping */ \
504 0, /* tp_hash */ \
505 0, /* tp_call */ \
506 0, /* tp_str */ \
507 0, /* tp_getattro */ \
508 0, /* tp_setattro */ \
509 0, /* tp_as_buffer */ \
510 Py_TPFLAGS_DEFAULT, /* tp_flags */ \
511 type_doc, /* tp_doc */ \
512 0, /* tp_traverse */ \
513 0, /* tp_clear */ \
514 0, /* tp_richcompare */ \
515 0, /* tp_weaklistoffset */ \
516 0, /* tp_iter */ \
517 0, /* tp_iternext */ \
518 type_methods, /* tp_methods */ \
519 NULL, /* tp_members */ \
520 SHA3_getseters, /* tp_getset */ \
521 0, /* tp_base */ \
522 0, /* tp_dict */ \
523 0, /* tp_descr_get */ \
524 0, /* tp_descr_set */ \
525 0, /* tp_dictoffset */ \
526 0, /* tp_init */ \
527 0, /* tp_alloc */ \
528 py_sha3_new, /* tp_new */ \
529 }
530
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300531PyDoc_STRVAR(sha3_224__doc__,
532"sha3_224([data]) -> SHA3 object\n\
533\n\
534Return a new SHA3 hash object with a hashbit length of 28 bytes.");
535
Christian Heimes6fe2a752016-09-07 11:58:24 +0200536PyDoc_STRVAR(sha3_256__doc__,
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300537"sha3_256([data]) -> SHA3 object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200538\n\
539Return a new SHA3 hash object with a hashbit length of 32 bytes.");
540
541PyDoc_STRVAR(sha3_384__doc__,
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300542"sha3_384([data]) -> SHA3 object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200543\n\
544Return a new SHA3 hash object with a hashbit length of 48 bytes.");
545
546PyDoc_STRVAR(sha3_512__doc__,
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300547"sha3_512([data]) -> SHA3 object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200548\n\
549Return a new SHA3 hash object with a hashbit length of 64 bytes.");
550
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300551SHA3_TYPE(SHA3_224type, "_sha3.sha3_224", sha3_224__doc__, SHA3_methods);
Christian Heimes6fe2a752016-09-07 11:58:24 +0200552SHA3_TYPE(SHA3_256type, "_sha3.sha3_256", sha3_256__doc__, SHA3_methods);
553SHA3_TYPE(SHA3_384type, "_sha3.sha3_384", sha3_384__doc__, SHA3_methods);
554SHA3_TYPE(SHA3_512type, "_sha3.sha3_512", sha3_512__doc__, SHA3_methods);
555
556#ifdef PY_WITH_KECCAK
557PyDoc_STRVAR(keccak_224__doc__,
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300558"keccak_224([data]) -> Keccak object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200559\n\
560Return a new Keccak hash object with a hashbit length of 28 bytes.");
561
562PyDoc_STRVAR(keccak_256__doc__,
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300563"keccak_256([data]) -> Keccak object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200564\n\
565Return a new Keccak hash object with a hashbit length of 32 bytes.");
566
567PyDoc_STRVAR(keccak_384__doc__,
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300568"keccak_384([data]) -> Keccak object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200569\n\
570Return a new Keccak hash object with a hashbit length of 48 bytes.");
571
572PyDoc_STRVAR(keccak_512__doc__,
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300573"keccak_512([data]) -> Keccak object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200574\n\
575Return a new Keccak hash object with a hashbit length of 64 bytes.");
576
577SHA3_TYPE(Keccak_224type, "_sha3.keccak_224", keccak_224__doc__, SHA3_methods);
578SHA3_TYPE(Keccak_256type, "_sha3.keccak_256", keccak_256__doc__, SHA3_methods);
579SHA3_TYPE(Keccak_384type, "_sha3.keccak_384", keccak_384__doc__, SHA3_methods);
580SHA3_TYPE(Keccak_512type, "_sha3.keccak_512", keccak_512__doc__, SHA3_methods);
581#endif
582
583
584static PyObject *
585_SHAKE_digest(SHA3object *self, unsigned long digestlen, int hex)
586{
587 unsigned char *digest = NULL;
588 SHA3_state temp;
589 int res;
590 PyObject *result = NULL;
591
Christian Heimescf45ee12016-09-08 13:35:00 +0200592 /* ExtractLane needs at least SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE and
593 * SHA3_LANESIZE extra space.
594 */
Christian Heimesc71ec8a2016-09-08 15:04:38 +0200595 digest = (unsigned char*)PyMem_Malloc(digestlen + SHA3_LANESIZE);
Christian Heimescf45ee12016-09-08 13:35:00 +0200596 if (digest == NULL) {
Christian Heimes6fe2a752016-09-07 11:58:24 +0200597 return PyErr_NoMemory();
598 }
599
600 /* Get the raw (binary) digest value */
601 ENTER_HASHLIB(self);
602 SHA3_copystate(temp, self->hash_state);
603 LEAVE_HASHLIB(self);
604 res = SHA3_done(&temp, NULL);
605 if (res != SUCCESS) {
606 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 done()");
607 goto error;
608 }
609 res = SHA3_squeeze(&temp, digest, digestlen * 8);
610 if (res != SUCCESS) {
611 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Squeeze()");
612 return NULL;
613 }
614 if (hex) {
615 result = _Py_strhex((const char *)digest, digestlen);
616 } else {
617 result = PyBytes_FromStringAndSize((const char *)digest,
618 digestlen);
619 }
620 error:
621 if (digest != NULL) {
622 PyMem_Free(digest);
623 }
624 return result;
625}
626
627
628/*[clinic input]
629_sha3.shake_128.digest
630
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300631 length: unsigned_long
632 /
Christian Heimes6fe2a752016-09-07 11:58:24 +0200633
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300634Return the digest value as a bytes object.
Christian Heimes6fe2a752016-09-07 11:58:24 +0200635[clinic start generated code]*/
636
637static PyObject *
638_sha3_shake_128_digest_impl(SHA3object *self, unsigned long length)
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300639/*[clinic end generated code: output=2313605e2f87bb8f input=418ef6a36d2e6082]*/
Christian Heimes6fe2a752016-09-07 11:58:24 +0200640{
641 return _SHAKE_digest(self, length, 0);
642}
643
644
645/*[clinic input]
646_sha3.shake_128.hexdigest
647
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300648 length: unsigned_long
649 /
Christian Heimes6fe2a752016-09-07 11:58:24 +0200650
651Return the digest value as a string of hexadecimal digits.
652[clinic start generated code]*/
653
654static PyObject *
655_sha3_shake_128_hexdigest_impl(SHA3object *self, unsigned long length)
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300656/*[clinic end generated code: output=bf8e2f1e490944a8 input=69fb29b0926ae321]*/
Christian Heimes6fe2a752016-09-07 11:58:24 +0200657{
658 return _SHAKE_digest(self, length, 1);
659}
660
661
662static PyMethodDef SHAKE_methods[] = {
663 _SHA3_SHA3_224_COPY_METHODDEF
664 _SHA3_SHAKE_128_DIGEST_METHODDEF
665 _SHA3_SHAKE_128_HEXDIGEST_METHODDEF
666 _SHA3_SHA3_224_UPDATE_METHODDEF
667 {NULL, NULL} /* sentinel */
668};
669
670PyDoc_STRVAR(shake_128__doc__,
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300671"shake_128([data]) -> SHAKE object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200672\n\
673Return a new SHAKE hash object.");
674
675PyDoc_STRVAR(shake_256__doc__,
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300676"shake_256([data]) -> SHAKE object\n\
Christian Heimes6fe2a752016-09-07 11:58:24 +0200677\n\
678Return a new SHAKE hash object.");
679
680SHA3_TYPE(SHAKE128type, "_sha3.shake_128", shake_128__doc__, SHAKE_methods);
681SHA3_TYPE(SHAKE256type, "_sha3.shake_256", shake_256__doc__, SHAKE_methods);
682
683
684/* Initialize this module. */
685static struct PyModuleDef _SHA3module = {
686 PyModuleDef_HEAD_INIT,
687 "_sha3",
688 NULL,
689 -1,
690 NULL,
691 NULL,
692 NULL,
693 NULL,
694 NULL
695};
696
697
698PyMODINIT_FUNC
699PyInit__sha3(void)
700{
701 PyObject *m = NULL;
702
Christian Heimescf45ee12016-09-08 13:35:00 +0200703 if ((m = PyModule_Create(&_SHA3module)) == NULL) {
704 return NULL;
705 }
Christian Heimes6fe2a752016-09-07 11:58:24 +0200706
707#define init_sha3type(name, type) \
708 do { \
709 Py_TYPE(type) = &PyType_Type; \
710 if (PyType_Ready(type) < 0) { \
711 goto error; \
712 } \
713 Py_INCREF((PyObject *)type); \
714 if (PyModule_AddObject(m, name, (PyObject *)type) < 0) { \
715 goto error; \
716 } \
717 } while(0)
718
719 init_sha3type("sha3_224", &SHA3_224type);
720 init_sha3type("sha3_256", &SHA3_256type);
721 init_sha3type("sha3_384", &SHA3_384type);
722 init_sha3type("sha3_512", &SHA3_512type);
723#ifdef PY_WITH_KECCAK
724 init_sha3type("keccak_224", &Keccak_224type);
725 init_sha3type("keccak_256", &Keccak_256type);
726 init_sha3type("keccak_384", &Keccak_384type);
727 init_sha3type("keccak_512", &Keccak_512type);
728#endif
729 init_sha3type("shake_128", &SHAKE128type);
730 init_sha3type("shake_256", &SHAKE256type);
731
732#undef init_sha3type
733
734 if (PyModule_AddIntConstant(m, "keccakopt", KeccakOpt) < 0) {
735 goto error;
736 }
737 if (PyModule_AddStringConstant(m, "implementation",
738 KeccakP1600_implementation) < 0) {
739 goto error;
740 }
741
742 return m;
743 error:
744 Py_DECREF(m);
745 return NULL;
746}