Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(13989)

Side by Side Diff: Modules/_sha3/sha3module.c

Issue 16113: Add SHA-3 (Keccak) support
Patch Set: Created 3 years ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View unified diff | Download patch
« no previous file with comments | « Modules/_sha3/README.txt ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /* 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
40 #elif SIZEOF_VOID_P == 8 && defined(PY_UINT64_T)
41 /* opt64 works only for 64bit platforms with unsigned int64 */
42 #define KeccakOpt 64
43 #else
44 /* opt32 is used for the remaining 32 and 64bit platforms */
45 #define KeccakOpt 32
46 #endif
47
48 #if KeccakOpt == 64 && defined(PY_UINT64_T)
49 /* 64bit platforms with unsigned int64 */
50 typedef PY_UINT64_T UINT64;
51 typedef unsigned char UINT8;
52 #endif
53
54 /* replacement for brg_endian.h */
55 #define IS_LITTLE_ENDIAN 1234
56 #define IS_BIG_ENDIAN 4321
57 #if PY_LITTLE_ENDIAN
58 #define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
59 #endif
60 #if PY_BIG_ENDIAN
61 #define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
62 #endif
63
64 /* mangle names */
65 #define KeccakF1600_FastLoop_Absorb _PySHA3_KeccakF1600_FastLoop_Absorb
66 #define Keccak_HashFinal _PySHA3_Keccak_HashFinal
67 #define Keccak_HashInitialize _PySHA3_Keccak_HashInitialize
68 #define Keccak_HashSqueeze _PySHA3_Keccak_HashSqueeze
69 #define Keccak_HashUpdate _PySHA3_Keccak_HashUpdate
70 #define KeccakP1600_AddBytes _PySHA3_KeccakP1600_AddBytes
71 #define KeccakP1600_AddBytesInLane _PySHA3_KeccakP1600_AddBytesInLane
72 #define KeccakP1600_AddLanes _PySHA3_KeccakP1600_AddLanes
73 #define KeccakP1600_ExtractAndAddBytes _PySHA3_KeccakP1600_ExtractAndAddBytes
74 #define KeccakP1600_ExtractAndAddBytesInLane _PySHA3_KeccakP1600_ExtractAndAddBy tesInLane
75 #define KeccakP1600_ExtractAndAddLanes _PySHA3_KeccakP1600_ExtractAndAddLanes
76 #define KeccakP1600_ExtractBytes _PySHA3_KeccakP1600_ExtractBytes
77 #define KeccakP1600_ExtractBytesInLane _PySHA3_KeccakP1600_ExtractBytesInLane
78 #define KeccakP1600_ExtractLanes _PySHA3_KeccakP1600_ExtractLanes
79 #define KeccakP1600_Initialize _PySHA3_KeccakP1600_Initialize
80 #define KeccakP1600_OverwriteBytes _PySHA3_KeccakP1600_OverwriteBytes
81 #define KeccakP1600_OverwriteBytesInLane _PySHA3_KeccakP1600_OverwriteBytesInLan e
82 #define KeccakP1600_OverwriteLanes _PySHA3_KeccakP1600_OverwriteLanes
83 #define KeccakP1600_OverwriteWithZeroes _PySHA3_KeccakP1600_OverwriteWithZeroes
84 #define KeccakP1600_Permute_12rounds _PySHA3_KeccakP1600_Permute_12rounds
85 #define KeccakP1600_Permute_24rounds _PySHA3_KeccakP1600_Permute_24rounds
86 #define KeccakWidth1600_Sponge _PySHA3_KeccakWidth1600_Sponge
87 #define KeccakWidth1600_SpongeAbsorb _PySHA3_KeccakWidth1600_SpongeAbsorb
88 #define KeccakWidth1600_SpongeAbsorbLastFewBits _PySHA3_KeccakWidth1600_SpongeAb sorbLastFewBits
89 #define KeccakWidth1600_SpongeInitialize _PySHA3_KeccakWidth1600_SpongeInitializ e
90 #define KeccakWidth1600_SpongeSqueeze _PySHA3_KeccakWidth1600_SpongeSqueeze
91 #if KeccakOpt == 32
92 #define KeccakP1600_AddByte _PySHA3_KeccakP1600_AddByte
93 #define KeccakP1600_Permute_Nrounds _PySHA3_KeccakP1600_Permute_Nrounds
94 #define KeccakP1600_SetBytesInLaneToZero _PySHA3_KeccakP1600_SetBytesInLaneToZer o
95 #endif
96
97 /* we are only interested in KeccakP1600 */
98 #define KeccakP200_excluded 1
99 #define KeccakP400_excluded 1
100 #define KeccakP800_excluded 1
101
102 /* inline all Keccak dependencies */
103 #include "kcp/KeccakHash.h"
104 #include "kcp/KeccakSponge.h"
105 #include "kcp/KeccakHash.c"
106 #include "kcp/KeccakSponge.c"
107 #if KeccakOpt == 64
108 #include "kcp/KeccakP-1600-opt64.c"
109 #elif KeccakOpt == 32
110 #include "kcp/KeccakP-1600-inplace32BI.c"
111 #endif
112
113 #define SHA3_MAX_DIGESTSIZE 64 /* 64 Bytes (512 Bits) for 224 to 512 */
114 #define SHA3_state Keccak_HashInstance
115 #define SHA3_init Keccak_HashInitialize
116 #define SHA3_process Keccak_HashUpdate
117 #define SHA3_done Keccak_HashFinal
118 #define SHA3_squeeze Keccak_HashSqueeze
119 #define SHA3_copystate(dest, src) memcpy(&(dest), &(src), sizeof(SHA3_state))
120
121
122 /*[clinic input]
123 module _sha3
124 class _sha3.sha3_224 "SHA3object *" "&SHA3_224typ"
125 class _sha3.sha3_256 "SHA3object *" "&SHA3_256typ"
126 class _sha3.sha3_384 "SHA3object *" "&SHA3_384typ"
127 class _sha3.sha3_512 "SHA3object *" "&SHA3_512typ"
128 class _sha3.shake_128 "SHA3object *" "&SHAKE128type"
129 class _sha3.shake_256 "SHA3object *" "&SHAKE256type"
130 [clinic start generated code]*/
131 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=b8a53680f370285a]*/
132
133 /* The structure for storing SHA3 info */
134
135 #define PY_WITH_KECCAK 0
136
137 typedef struct {
138 PyObject_HEAD
139 SHA3_state hash_state;
140 #ifdef WITH_THREAD
141 PyThread_type_lock lock;
142 #endif
143 } SHA3object;
144
145 static PyTypeObject SHA3_224type;
146 static PyTypeObject SHA3_256type;
147 static PyTypeObject SHA3_384type;
148 static PyTypeObject SHA3_512type;
149 #ifdef PY_WITH_KECCAK
150 static PyTypeObject Keccak_224type;
151 static PyTypeObject Keccak_256type;
152 static PyTypeObject Keccak_384type;
153 static PyTypeObject Keccak_512type;
154 #endif
155 static PyTypeObject SHAKE128type;
156 static PyTypeObject SHAKE256type;
157
158 #include "clinic/sha3module.c.h"
159
160 static SHA3object *
161 newSHA3object(PyTypeObject *type)
162 {
163 SHA3object *newobj;
164 newobj = (SHA3object *)PyObject_New(SHA3object, type);
165 if (newobj == NULL) {
166 return NULL;
167 }
168 #ifdef WITH_THREAD
169 newobj->lock = NULL;
170 #endif
171 return newobj;
172 }
173
174
175 /*[clinic input]
176 @classmethod
177 _sha3.sha3_224.__new__ as py_sha3_new
178 string as data: object = NULL
179
180 Return a new SHA3 hash object with a hashbit length of 28 bytes.
181 [clinic start generated code]*/
182
183 static PyObject *
184 py_sha3_new_impl(PyTypeObject *type, PyObject *data)
185 /*[clinic end generated code: output=8d5c34279e69bf09 input=d7c582b950a858b6]*/
186 {
187 SHA3object *self = NULL;
188 Py_buffer buf = {NULL, NULL};
189 HashReturn res;
190
191 self = newSHA3object(type);
192 if (self == NULL) {
193 goto error;
194 }
195
196 if (type == &SHA3_224type) {
197 res = Keccak_HashInitialize_SHA3_224(&self->hash_state);
198 } else if (type == &SHA3_256type) {
199 res = Keccak_HashInitialize_SHA3_256(&self->hash_state);
200 } else if (type == &SHA3_384type) {
201 res = Keccak_HashInitialize_SHA3_384(&self->hash_state);
202 } else if (type == &SHA3_512type) {
203 res = Keccak_HashInitialize_SHA3_512(&self->hash_state);
204 #ifdef PY_WITH_KECCAK
205 } else if (type == &Keccak_224type) {
206 res = Keccak_HashInitialize(&self->hash_state, 1152, 448, 224, 0x01);
207 } else if (type == &Keccak_256type) {
208 res = Keccak_HashInitialize(&self->hash_state, 1088, 512, 256, 0x01);
209 } else if (type == &Keccak_384type) {
210 res = Keccak_HashInitialize(&self->hash_state, 832, 768, 384, 0x01);
211 } else if (type == &Keccak_512type) {
212 res = Keccak_HashInitialize(&self->hash_state, 576, 1024, 512, 0x01);
213 #endif
214 } else if (type == &SHAKE128type) {
215 res = Keccak_HashInitialize_SHAKE128(&self->hash_state);
216 } else if (type == &SHAKE256type) {
217 res = Keccak_HashInitialize_SHAKE256(&self->hash_state);
218 } else {
219 PyErr_BadInternalCall();
220 goto error;
221 }
222
223 if (data) {
224 GET_BUFFER_VIEW_OR_ERROR(data, &buf, goto error);
225 #ifdef WITH_THREAD
226 if (buf.len >= HASHLIB_GIL_MINSIZE) {
227 /* invariant: New objects can't be accessed by other code yet,
228 * thus it's safe to release the GIL without locking the object.
229 */
230 Py_BEGIN_ALLOW_THREADS
231 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
232 Py_END_ALLOW_THREADS
233 }
234 else {
235 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
236 }
237 #else
238 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
239 #endif
240 if (res != SUCCESS) {
241 PyErr_SetString(PyExc_RuntimeError,
242 "internal error in SHA3 Update()");
243 goto error;
244 }
245 PyBuffer_Release(&buf);
246 }
247
248 return (PyObject *)self;
249
250 error:
251 if (self) {
252 Py_DECREF(self);
253 }
254 if (data && buf.obj) {
255 PyBuffer_Release(&buf);
256 }
257 return NULL;
258 }
259
260
261 /* Internal methods for a hash object */
262
263 static void
264 SHA3_dealloc(SHA3object *self)
265 {
266 #ifdef WITH_THREAD
267 if (self->lock) {
268 PyThread_free_lock(self->lock);
269 }
270 #endif
271 PyObject_Del(self);
272 }
273
274
275 /* External methods for a hash object */
276
277
278 /*[clinic input]
279 _sha3.sha3_224.copy
280
281 Return a copy of the hash object.
282 [clinic start generated code]*/
283
284 static PyObject *
285 _sha3_sha3_224_copy_impl(SHA3object *self)
286 /*[clinic end generated code: output=6c537411ecdcda4c input=93a44aaebea51ba8]*/
287 {
288 SHA3object *newobj;
289
290 if ((newobj = newSHA3object(Py_TYPE(self))) == NULL) {
291 return NULL;
292 }
293 ENTER_HASHLIB(self);
294 SHA3_copystate(newobj->hash_state, self->hash_state);
295 LEAVE_HASHLIB(self);
296 return (PyObject *)newobj;
297 }
298
299
300 /*[clinic input]
301 _sha3.sha3_224.digest
302
303 Return the digest value as a string of binary data.
304 [clinic start generated code]*/
305
306 static PyObject *
307 _sha3_sha3_224_digest_impl(SHA3object *self)
308 /*[clinic end generated code: output=fd531842e20b2d5b input=a5807917d219b30e]*/
309 {
310 unsigned char digest[SHA3_MAX_DIGESTSIZE];
311 SHA3_state temp;
312 HashReturn res;
313
314 ENTER_HASHLIB(self);
315 SHA3_copystate(temp, self->hash_state);
316 LEAVE_HASHLIB(self);
317 res = SHA3_done(&temp, digest);
318 if (res != SUCCESS) {
319 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Final()");
320 return NULL;
321 }
322 return PyBytes_FromStringAndSize((const char *)digest,
323 self->hash_state.fixedOutputLength / 8);
324 }
325
326
327 /*[clinic input]
328 _sha3.sha3_224.hexdigest
329
330 Return the digest value as a string of hexadecimal digits.
331 [clinic start generated code]*/
332
333 static PyObject *
334 _sha3_sha3_224_hexdigest_impl(SHA3object *self)
335 /*[clinic end generated code: output=75ad03257906918d input=2d91bb6e0d114ee3]*/
336 {
337 unsigned char digest[SHA3_MAX_DIGESTSIZE];
338 SHA3_state temp;
339 HashReturn res;
340
341 /* Get the raw (binary) digest value */
342 ENTER_HASHLIB(self);
343 SHA3_copystate(temp, self->hash_state);
344 LEAVE_HASHLIB(self);
345 res = SHA3_done(&temp, digest);
346 if (res != SUCCESS) {
347 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Final()");
348 return NULL;
349 }
350 return _Py_strhex((const char *)digest,
351 self->hash_state.fixedOutputLength / 8);
352 }
353
354
355 /*[clinic input]
356 _sha3.sha3_224.update
357
358 obj: object
359 /
360
361 Update this hash object's state with the provided string.
362 [clinic start generated code]*/
363
364 static PyObject *
365 _sha3_sha3_224_update(SHA3object *self, PyObject *obj)
366 /*[clinic end generated code: output=06721d55b483e0af input=be44bf0d1c279791]*/
367 {
368 Py_buffer buf;
369 HashReturn res;
370
371 GET_BUFFER_VIEW_OR_ERROUT(obj, &buf);
372
373 /* add new data, the function takes the length in bits not bytes */
374 #ifdef WITH_THREAD
375 if (self->lock == NULL && buf.len >= HASHLIB_GIL_MINSIZE) {
376 self->lock = PyThread_allocate_lock();
377 }
378 /* Once a lock exists all code paths must be synchronized. We have to
379 * release the GIL even for small buffers as acquiring the lock may take
380 * an unlimited amount of time when another thread updates this object
381 * with lots of data. */
382 if (self->lock) {
383 Py_BEGIN_ALLOW_THREADS
384 PyThread_acquire_lock(self->lock, 1);
385 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
386 PyThread_release_lock(self->lock);
387 Py_END_ALLOW_THREADS
388 }
389 else {
390 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
391 }
392 #else
393 res = SHA3_process(&self->hash_state, buf.buf, buf.len * 8);
394 #endif
395
396 if (res != SUCCESS) {
397 PyBuffer_Release(&buf);
398 PyErr_SetString(PyExc_RuntimeError,
399 "internal error in SHA3 Update()");
400 return NULL;
401 }
402
403 PyBuffer_Release(&buf);
404 Py_INCREF(Py_None);
405 return Py_None;
406 }
407
408
409 static PyMethodDef SHA3_methods[] = {
410 _SHA3_SHA3_224_COPY_METHODDEF
411 _SHA3_SHA3_224_DIGEST_METHODDEF
412 _SHA3_SHA3_224_HEXDIGEST_METHODDEF
413 _SHA3_SHA3_224_UPDATE_METHODDEF
414 {NULL, NULL} /* sentinel */
415 };
416
417
418 static PyObject *
419 SHA3_get_block_size(SHA3object *self, void *closure)
420 {
421 int rate = self->hash_state.sponge.rate;
422 return PyLong_FromLong(rate / 8);
423 }
424
425
426 static PyObject *
427 SHA3_get_name(SHA3object *self, void *closure)
428 {
429 PyTypeObject *type = Py_TYPE(self);
430 if (type == &SHA3_224type) {
431 return PyUnicode_FromString("sha3_224");
432 } else if (type == &SHA3_256type) {
433 return PyUnicode_FromString("sha3_256");
434 } else if (type == &SHA3_384type) {
435 return PyUnicode_FromString("sha3_384");
436 } else if (type == &SHA3_512type) {
437 return PyUnicode_FromString("sha3_512");
438 #ifdef PY_WITH_KECCAK
439 } else if (type == &Keccak_224type) {
440 return PyUnicode_FromString("keccak_224");
441 } else if (type == &Keccak_256type) {
442 return PyUnicode_FromString("keccak_256");
443 } else if (type == &Keccak_384type) {
444 return PyUnicode_FromString("keccak_384");
445 } else if (type == &Keccak_512type) {
446 return PyUnicode_FromString("keccak_512");
447 #endif
448 } else if (type == &SHAKE128type) {
449 return PyUnicode_FromString("shake_128");
450 } else if (type == &SHAKE256type) {
451 return PyUnicode_FromString("shake_256");
452 } else {
453 PyErr_BadInternalCall();
454 return NULL;
455 }
456 }
457
458
459 static PyObject *
460 SHA3_get_digest_size(SHA3object *self, void *closure)
461 {
462 return PyLong_FromLong(self->hash_state.fixedOutputLength / 8);
463 }
464
465
466 static PyObject *
467 SHA3_get_capacity_bits(SHA3object *self, void *closure)
468 {
469 int capacity = 1600 - self->hash_state.sponge.rate;
470 return PyLong_FromLong(capacity);
471 }
472
473
474 static PyObject *
475 SHA3_get_rate_bits(SHA3object *self, void *closure)
476 {
477 unsigned int rate = self->hash_state.sponge.rate;
478 return PyLong_FromLong(rate);
479 }
480
481 static PyObject *
482 SHA3_get_suffix(SHA3object *self, void *closure)
483 {
484 unsigned char suffix[2];
485 suffix[0] = self->hash_state.delimitedSuffix;
486 suffix[1] = 0;
487 return PyBytes_FromStringAndSize((const char *)suffix, 1);
488 }
489
490
491 static PyGetSetDef SHA3_getseters[] = {
492 {"block_size", (getter)SHA3_get_block_size, NULL, NULL, NULL},
493 {"name", (getter)SHA3_get_name, NULL, NULL, NULL},
494 {"digest_size", (getter)SHA3_get_digest_size, NULL, NULL, NULL},
495 {"_capacity_bits", (getter)SHA3_get_capacity_bits, NULL, NULL, NULL},
496 {"_rate_bits", (getter)SHA3_get_rate_bits, NULL, NULL, NULL},
497 {"_suffix", (getter)SHA3_get_suffix, NULL, NULL, NULL},
498 {NULL} /* Sentinel */
499 };
500
501
502 #define SHA3_TYPE(type_obj, type_name, type_doc, type_methods) \
503 static PyTypeObject type_obj = { \
504 PyVarObject_HEAD_INIT(NULL, 0) \
505 type_name, /* tp_name */ \
506 sizeof(SHA3object), /* tp_size */ \
507 0, /* tp_itemsize */ \
508 /* methods */ \
509 (destructor)SHA3_dealloc, /* tp_dealloc */ \
510 0, /* tp_print */ \
511 0, /* tp_getattr */ \
512 0, /* tp_setattr */ \
513 0, /* tp_reserved */ \
514 0, /* tp_repr */ \
515 0, /* tp_as_number */ \
516 0, /* tp_as_sequence */ \
517 0, /* tp_as_mapping */ \
518 0, /* tp_hash */ \
519 0, /* tp_call */ \
520 0, /* tp_str */ \
521 0, /* tp_getattro */ \
522 0, /* tp_setattro */ \
523 0, /* tp_as_buffer */ \
524 Py_TPFLAGS_DEFAULT, /* tp_flags */ \
525 type_doc, /* tp_doc */ \
526 0, /* tp_traverse */ \
527 0, /* tp_clear */ \
528 0, /* tp_richcompare */ \
529 0, /* tp_weaklistoffset */ \
530 0, /* tp_iter */ \
531 0, /* tp_iternext */ \
532 type_methods, /* tp_methods */ \
533 NULL, /* tp_members */ \
534 SHA3_getseters, /* tp_getset */ \
535 0, /* tp_base */ \
536 0, /* tp_dict */ \
537 0, /* tp_descr_get */ \
538 0, /* tp_descr_set */ \
539 0, /* tp_dictoffset */ \
540 0, /* tp_init */ \
541 0, /* tp_alloc */ \
542 py_sha3_new, /* tp_new */ \
543 }
544
545 PyDoc_STRVAR(sha3_256__doc__,
546 "sha3_256([string]) -> SHA3 object\n\
547 \n\
548 Return a new SHA3 hash object with a hashbit length of 32 bytes.");
549
550 PyDoc_STRVAR(sha3_384__doc__,
551 "sha3_384([string]) -> SHA3 object\n\
552 \n\
553 Return a new SHA3 hash object with a hashbit length of 48 bytes.");
554
555 PyDoc_STRVAR(sha3_512__doc__,
556 "sha3_512([string]) -> SHA3 object\n\
557 \n\
558 Return a new SHA3 hash object with a hashbit length of 64 bytes.");
559
560 SHA3_TYPE(SHA3_224type, "_sha3.sha3_224", py_sha3_new__doc__, SHA3_methods);
561 SHA3_TYPE(SHA3_256type, "_sha3.sha3_256", sha3_256__doc__, SHA3_methods);
562 SHA3_TYPE(SHA3_384type, "_sha3.sha3_384", sha3_384__doc__, SHA3_methods);
563 SHA3_TYPE(SHA3_512type, "_sha3.sha3_512", sha3_512__doc__, SHA3_methods);
564
565 #ifdef PY_WITH_KECCAK
566 PyDoc_STRVAR(keccak_224__doc__,
567 "keccak_224([string]) -> Keccak object\n\
568 \n\
569 Return a new Keccak hash object with a hashbit length of 28 bytes.");
570
571 PyDoc_STRVAR(keccak_256__doc__,
572 "keccak_256([string]) -> Keccak object\n\
573 \n\
574 Return a new Keccak hash object with a hashbit length of 32 bytes.");
575
576 PyDoc_STRVAR(keccak_384__doc__,
577 "keccak_384([string]) -> Keccak object\n\
578 \n\
579 Return a new Keccak hash object with a hashbit length of 48 bytes.");
580
581 PyDoc_STRVAR(keccak_512__doc__,
582 "keccak_512([string]) -> Keccak object\n\
583 \n\
584 Return a new Keccak hash object with a hashbit length of 64 bytes.");
585
586 SHA3_TYPE(Keccak_224type, "_sha3.keccak_224", keccak_224__doc__, SHA3_methods);
587 SHA3_TYPE(Keccak_256type, "_sha3.keccak_256", keccak_256__doc__, SHA3_methods);
588 SHA3_TYPE(Keccak_384type, "_sha3.keccak_384", keccak_384__doc__, SHA3_methods);
589 SHA3_TYPE(Keccak_512type, "_sha3.keccak_512", keccak_512__doc__, SHA3_methods);
590 #endif
591
592
593 static PyObject *
594 _SHAKE_digest(SHA3object *self, unsigned long digestlen, int hex)
595 {
596 unsigned char *digest = NULL;
597 SHA3_state temp;
598 int res;
599 PyObject *result = NULL;
600
601 if ((digest = (unsigned char*)PyMem_Malloc(digestlen)) == NULL) {
602 return PyErr_NoMemory();
603 }
604
605 /* Get the raw (binary) digest value */
606 ENTER_HASHLIB(self);
607 SHA3_copystate(temp, self->hash_state);
608 LEAVE_HASHLIB(self);
609 res = SHA3_done(&temp, NULL);
610 if (res != SUCCESS) {
611 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 done()");
612 goto error;
613 }
614 res = SHA3_squeeze(&temp, digest, digestlen * 8);
615 if (res != SUCCESS) {
616 PyErr_SetString(PyExc_RuntimeError, "internal error in SHA3 Squeeze()");
617 return NULL;
618 }
619 if (hex) {
620 result = _Py_strhex((const char *)digest, digestlen);
621 } else {
622 result = PyBytes_FromStringAndSize((const char *)digest,
623 digestlen);
624 }
625 error:
626 if (digest != NULL) {
627 PyMem_Free(digest);
628 }
629 return result;
630 }
631
632
633 /*[clinic input]
634 _sha3.shake_128.digest
635
636 length: unsigned_long(bitwise=True)
637 \
638
639 Return the digest value as a string of binary data.
640 [clinic start generated code]*/
641
642 static PyObject *
643 _sha3_shake_128_digest_impl(SHA3object *self, unsigned long length)
644 /*[clinic end generated code: output=2313605e2f87bb8f input=608c8ca80ae9d115]*/
645 {
646 return _SHAKE_digest(self, length, 0);
647 }
648
649
650 /*[clinic input]
651 _sha3.shake_128.hexdigest
652
653 length: unsigned_long(bitwise=True)
654 \
655
656 Return the digest value as a string of hexadecimal digits.
657 [clinic start generated code]*/
658
659 static PyObject *
660 _sha3_shake_128_hexdigest_impl(SHA3object *self, unsigned long length)
661 /*[clinic end generated code: output=bf8e2f1e490944a8 input=64e56b4760db4573]*/
662 {
663 return _SHAKE_digest(self, length, 1);
664 }
665
666
667 static PyMethodDef SHAKE_methods[] = {
668 _SHA3_SHA3_224_COPY_METHODDEF
669 _SHA3_SHAKE_128_DIGEST_METHODDEF
670 _SHA3_SHAKE_128_HEXDIGEST_METHODDEF
671 _SHA3_SHA3_224_UPDATE_METHODDEF
672 {NULL, NULL} /* sentinel */
673 };
674
675 PyDoc_STRVAR(shake_128__doc__,
676 "shake_128([string]) -> SHAKE object\n\
677 \n\
678 Return a new SHAKE hash object.");
679
680 PyDoc_STRVAR(shake_256__doc__,
681 "shake_256([string]) -> SHAKE object\n\
682 \n\
683 Return a new SHAKE hash object.");
684
685 SHA3_TYPE(SHAKE128type, "_sha3.shake_128", shake_128__doc__, SHAKE_methods);
686 SHA3_TYPE(SHAKE256type, "_sha3.shake_256", shake_256__doc__, SHAKE_methods);
687
688
689 /* Initialize this module. */
690 static struct PyModuleDef _SHA3module = {
691 PyModuleDef_HEAD_INIT,
692 "_sha3",
693 NULL,
694 -1,
695 NULL,
696 NULL,
697 NULL,
698 NULL,
699 NULL
700 };
701
702
703 PyMODINIT_FUNC
704 PyInit__sha3(void)
705 {
706 PyObject *m = NULL;
707
708 m = PyModule_Create(&_SHA3module);
709
710 #define init_sha3type(name, type) \
711 do { \
712 Py_TYPE(type) = &PyType_Type; \
713 if (PyType_Ready(type) < 0) { \
714 goto error; \
715 } \
716 Py_INCREF((PyObject *)type); \
717 if (PyModule_AddObject(m, name, (PyObject *)type) < 0) { \
718 goto error; \
719 } \
720 } while(0)
721
722 init_sha3type("sha3_224", &SHA3_224type);
723 init_sha3type("sha3_256", &SHA3_256type);
724 init_sha3type("sha3_384", &SHA3_384type);
725 init_sha3type("sha3_512", &SHA3_512type);
726 #ifdef PY_WITH_KECCAK
727 init_sha3type("keccak_224", &Keccak_224type);
728 init_sha3type("keccak_256", &Keccak_256type);
729 init_sha3type("keccak_384", &Keccak_384type);
730 init_sha3type("keccak_512", &Keccak_512type);
731 #endif
732 init_sha3type("shake_128", &SHAKE128type);
733 init_sha3type("shake_256", &SHAKE256type);
734
735 #undef init_sha3type
736
737 if (PyModule_AddIntConstant(m, "keccakopt", KeccakOpt) < 0) {
738 goto error;
739 }
740 if (PyModule_AddStringConstant(m, "implementation",
741 KeccakP1600_implementation) < 0) {
742 goto error;
743 }
744
745 return m;
746 error:
747 Py_DECREF(m);
748 return NULL;
749 }
OLDNEW
« no previous file with comments | « Modules/_sha3/README.txt ('k') | no next file » | no next file with comments »

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+