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