1:mod:`hashlib` --- Secure hashes and message digests 2==================================================== 3 4.. module:: hashlib 5 :synopsis: Secure hash and message digest algorithms. 6 7.. moduleauthor:: Gregory P. Smith <greg@krypto.org> 8.. sectionauthor:: Gregory P. Smith <greg@krypto.org> 9 10**Source code:** :source:`Lib/hashlib.py` 11 12.. index:: 13 single: message digest, MD5 14 single: secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512 15 16.. testsetup:: 17 18 import hashlib 19 20 21-------------- 22 23This module implements a common interface to many different secure hash and 24message digest algorithms. Included are the FIPS secure hash algorithms SHA1, 25SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA's MD5 26algorithm (defined in internet :rfc:`1321`). The terms "secure hash" and 27"message digest" are interchangeable. Older algorithms were called message 28digests. The modern term is secure hash. 29 30.. note:: 31 32 If you want the adler32 or crc32 hash functions, they are available in 33 the :mod:`zlib` module. 34 35.. warning:: 36 37 Some algorithms have known hash collision weaknesses, refer to the "See 38 also" section at the end. 39 40 41.. _hash-algorithms: 42 43Hash algorithms 44--------------- 45 46There is one constructor method named for each type of :dfn:`hash`. All return 47a hash object with the same simple interface. For example: use :func:`sha256` to 48create a SHA-256 hash object. You can now feed this object with :term:`bytes-like 49objects <bytes-like object>` (normally :class:`bytes`) using the :meth:`update` method. 50At any point you can ask it for the :dfn:`digest` of the 51concatenation of the data fed to it so far using the :meth:`digest` or 52:meth:`hexdigest` methods. 53 54.. note:: 55 56 For better multithreading performance, the Python :term:`GIL` is released for 57 data larger than 2047 bytes at object creation or on update. 58 59.. note:: 60 61 Feeding string objects into :meth:`update` is not supported, as hashes work 62 on bytes, not on characters. 63 64.. index:: single: OpenSSL; (use in module hashlib) 65 66Constructors for hash algorithms that are always present in this module are 67:func:`sha1`, :func:`sha224`, :func:`sha256`, :func:`sha384`, 68:func:`sha512`, :func:`blake2b`, and :func:`blake2s`. 69:func:`md5` is normally available as well, though it 70may be missing or blocked if you are using a rare "FIPS compliant" build of Python. 71Additional algorithms may also be available depending upon the OpenSSL 72library that Python uses on your platform. On most platforms the 73:func:`sha3_224`, :func:`sha3_256`, :func:`sha3_384`, :func:`sha3_512`, 74:func:`shake_128`, :func:`shake_256` are also available. 75 76.. versionadded:: 3.6 77 SHA3 (Keccak) and SHAKE constructors :func:`sha3_224`, :func:`sha3_256`, 78 :func:`sha3_384`, :func:`sha3_512`, :func:`shake_128`, :func:`shake_256`. 79 80.. versionadded:: 3.6 81 :func:`blake2b` and :func:`blake2s` were added. 82 83.. _hashlib-usedforsecurity: 84 85.. versionchanged:: 3.9 86 All hashlib constructors take a keyword-only argument *usedforsecurity* 87 with default value ``True``. A false value allows the use of insecure and 88 blocked hashing algorithms in restricted environments. ``False`` indicates 89 that the hashing algorithm is not used in a security context, e.g. as a 90 non-cryptographic one-way compression function. 91 92 Hashlib now uses SHA3 and SHAKE from OpenSSL 1.1.1 and newer. 93 94For example, to obtain the digest of the byte string ``b'Nobody inspects the 95spammish repetition'``:: 96 97 >>> import hashlib 98 >>> m = hashlib.sha256() 99 >>> m.update(b"Nobody inspects") 100 >>> m.update(b" the spammish repetition") 101 >>> m.digest() 102 b'\x03\x1e\xdd}Ae\x15\x93\xc5\xfe\\\x00o\xa5u+7\xfd\xdf\xf7\xbcN\x84:\xa6\xaf\x0c\x95\x0fK\x94\x06' 103 >>> m.digest_size 104 32 105 >>> m.block_size 106 64 107 108More condensed: 109 110 >>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest() 111 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2' 112 113.. function:: new(name[, data], *, usedforsecurity=True) 114 115 Is a generic constructor that takes the string *name* of the desired 116 algorithm as its first parameter. It also exists to allow access to the 117 above listed hashes as well as any other algorithms that your OpenSSL 118 library may offer. The named constructors are much faster than :func:`new` 119 and should be preferred. 120 121Using :func:`new` with an algorithm provided by OpenSSL: 122 123 >>> h = hashlib.new('sha512_256') 124 >>> h.update(b"Nobody inspects the spammish repetition") 125 >>> h.hexdigest() 126 '19197dc4d03829df858011c6c87600f994a858103bbc19005f20987aa19a97e2' 127 128Hashlib provides the following constant attributes: 129 130.. data:: algorithms_guaranteed 131 132 A set containing the names of the hash algorithms guaranteed to be supported 133 by this module on all platforms. Note that 'md5' is in this list despite 134 some upstream vendors offering an odd "FIPS compliant" Python build that 135 excludes it. 136 137 .. versionadded:: 3.2 138 139.. data:: algorithms_available 140 141 A set containing the names of the hash algorithms that are available in the 142 running Python interpreter. These names will be recognized when passed to 143 :func:`new`. :attr:`algorithms_guaranteed` will always be a subset. The 144 same algorithm may appear multiple times in this set under different names 145 (thanks to OpenSSL). 146 147 .. versionadded:: 3.2 148 149The following values are provided as constant attributes of the hash objects 150returned by the constructors: 151 152 153.. data:: hash.digest_size 154 155 The size of the resulting hash in bytes. 156 157.. data:: hash.block_size 158 159 The internal block size of the hash algorithm in bytes. 160 161A hash object has the following attributes: 162 163.. attribute:: hash.name 164 165 The canonical name of this hash, always lowercase and always suitable as a 166 parameter to :func:`new` to create another hash of this type. 167 168 .. versionchanged:: 3.4 169 The name attribute has been present in CPython since its inception, but 170 until Python 3.4 was not formally specified, so may not exist on some 171 platforms. 172 173A hash object has the following methods: 174 175 176.. method:: hash.update(data) 177 178 Update the hash object with the :term:`bytes-like object`. 179 Repeated calls are equivalent to a single call with the 180 concatenation of all the arguments: ``m.update(a); m.update(b)`` is 181 equivalent to ``m.update(a+b)``. 182 183 .. versionchanged:: 3.1 184 The Python GIL is released to allow other threads to run while hash 185 updates on data larger than 2047 bytes is taking place when using hash 186 algorithms supplied by OpenSSL. 187 188 189.. method:: hash.digest() 190 191 Return the digest of the data passed to the :meth:`update` method so far. 192 This is a bytes object of size :attr:`digest_size` which may contain bytes in 193 the whole range from 0 to 255. 194 195 196.. method:: hash.hexdigest() 197 198 Like :meth:`digest` except the digest is returned as a string object of 199 double length, containing only hexadecimal digits. This may be used to 200 exchange the value safely in email or other non-binary environments. 201 202 203.. method:: hash.copy() 204 205 Return a copy ("clone") of the hash object. This can be used to efficiently 206 compute the digests of data sharing a common initial substring. 207 208 209SHAKE variable length digests 210----------------------------- 211 212The :func:`shake_128` and :func:`shake_256` algorithms provide variable 213length digests with length_in_bits//2 up to 128 or 256 bits of security. 214As such, their digest methods require a length. Maximum length is not limited 215by the SHAKE algorithm. 216 217.. method:: shake.digest(length) 218 219 Return the digest of the data passed to the :meth:`update` method so far. 220 This is a bytes object of size *length* which may contain bytes in 221 the whole range from 0 to 255. 222 223 224.. method:: shake.hexdigest(length) 225 226 Like :meth:`digest` except the digest is returned as a string object of 227 double length, containing only hexadecimal digits. This may be used to 228 exchange the value safely in email or other non-binary environments. 229 230 231Key derivation 232-------------- 233 234Key derivation and key stretching algorithms are designed for secure password 235hashing. Naive algorithms such as ``sha1(password)`` are not resistant against 236brute-force attacks. A good password hashing function must be tunable, slow, and 237include a `salt <https://en.wikipedia.org/wiki/Salt_%28cryptography%29>`_. 238 239 240.. function:: pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None) 241 242 The function provides PKCS#5 password-based key derivation function 2. It 243 uses HMAC as pseudorandom function. 244 245 The string *hash_name* is the desired name of the hash digest algorithm for 246 HMAC, e.g. 'sha1' or 'sha256'. *password* and *salt* are interpreted as 247 buffers of bytes. Applications and libraries should limit *password* to 248 a sensible length (e.g. 1024). *salt* should be about 16 or more bytes from 249 a proper source, e.g. :func:`os.urandom`. 250 251 The number of *iterations* should be chosen based on the hash algorithm and 252 computing power. As of 2013, at least 100,000 iterations of SHA-256 are 253 suggested. 254 255 *dklen* is the length of the derived key. If *dklen* is ``None`` then the 256 digest size of the hash algorithm *hash_name* is used, e.g. 64 for SHA-512. 257 258 >>> import hashlib 259 >>> dk = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000) 260 >>> dk.hex() 261 '0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5' 262 263 .. versionadded:: 3.4 264 265 .. note:: 266 267 A fast implementation of *pbkdf2_hmac* is available with OpenSSL. The 268 Python implementation uses an inline version of :mod:`hmac`. It is about 269 three times slower and doesn't release the GIL. 270 271 .. deprecated:: 3.10 272 273 Slow Python implementation of *pbkdf2_hmac* is deprecated. In the 274 future the function will only be available when Python is compiled 275 with OpenSSL. 276 277.. function:: scrypt(password, *, salt, n, r, p, maxmem=0, dklen=64) 278 279 The function provides scrypt password-based key derivation function as 280 defined in :rfc:`7914`. 281 282 *password* and *salt* must be :term:`bytes-like objects 283 <bytes-like object>`. Applications and libraries should limit *password* 284 to a sensible length (e.g. 1024). *salt* should be about 16 or more 285 bytes from a proper source, e.g. :func:`os.urandom`. 286 287 *n* is the CPU/Memory cost factor, *r* the block size, *p* parallelization 288 factor and *maxmem* limits memory (OpenSSL 1.1.0 defaults to 32 MiB). 289 *dklen* is the length of the derived key. 290 291 .. versionadded:: 3.6 292 293 294BLAKE2 295------ 296 297.. sectionauthor:: Dmitry Chestnykh 298 299.. index:: 300 single: blake2b, blake2s 301 302BLAKE2_ is a cryptographic hash function defined in :rfc:`7693` that comes in two 303flavors: 304 305* **BLAKE2b**, optimized for 64-bit platforms and produces digests of any size 306 between 1 and 64 bytes, 307 308* **BLAKE2s**, optimized for 8- to 32-bit platforms and produces digests of any 309 size between 1 and 32 bytes. 310 311BLAKE2 supports **keyed mode** (a faster and simpler replacement for HMAC_), 312**salted hashing**, **personalization**, and **tree hashing**. 313 314Hash objects from this module follow the API of standard library's 315:mod:`hashlib` objects. 316 317 318Creating hash objects 319^^^^^^^^^^^^^^^^^^^^^ 320 321New hash objects are created by calling constructor functions: 322 323 324.. function:: blake2b(data=b'', *, digest_size=64, key=b'', salt=b'', \ 325 person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, \ 326 node_depth=0, inner_size=0, last_node=False, \ 327 usedforsecurity=True) 328 329.. function:: blake2s(data=b'', *, digest_size=32, key=b'', salt=b'', \ 330 person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, \ 331 node_depth=0, inner_size=0, last_node=False, \ 332 usedforsecurity=True) 333 334 335These functions return the corresponding hash objects for calculating 336BLAKE2b or BLAKE2s. They optionally take these general parameters: 337 338* *data*: initial chunk of data to hash, which must be 339 :term:`bytes-like object`. It can be passed only as positional argument. 340 341* *digest_size*: size of output digest in bytes. 342 343* *key*: key for keyed hashing (up to 64 bytes for BLAKE2b, up to 32 bytes for 344 BLAKE2s). 345 346* *salt*: salt for randomized hashing (up to 16 bytes for BLAKE2b, up to 8 347 bytes for BLAKE2s). 348 349* *person*: personalization string (up to 16 bytes for BLAKE2b, up to 8 bytes 350 for BLAKE2s). 351 352The following table shows limits for general parameters (in bytes): 353 354======= =========== ======== ========= =========== 355Hash digest_size len(key) len(salt) len(person) 356======= =========== ======== ========= =========== 357BLAKE2b 64 64 16 16 358BLAKE2s 32 32 8 8 359======= =========== ======== ========= =========== 360 361.. note:: 362 363 BLAKE2 specification defines constant lengths for salt and personalization 364 parameters, however, for convenience, this implementation accepts byte 365 strings of any size up to the specified length. If the length of the 366 parameter is less than specified, it is padded with zeros, thus, for 367 example, ``b'salt'`` and ``b'salt\x00'`` is the same value. (This is not 368 the case for *key*.) 369 370These sizes are available as module `constants`_ described below. 371 372Constructor functions also accept the following tree hashing parameters: 373 374* *fanout*: fanout (0 to 255, 0 if unlimited, 1 in sequential mode). 375 376* *depth*: maximal depth of tree (1 to 255, 255 if unlimited, 1 in 377 sequential mode). 378 379* *leaf_size*: maximal byte length of leaf (0 to ``2**32-1``, 0 if unlimited or in 380 sequential mode). 381 382* *node_offset*: node offset (0 to ``2**64-1`` for BLAKE2b, 0 to ``2**48-1`` for 383 BLAKE2s, 0 for the first, leftmost, leaf, or in sequential mode). 384 385* *node_depth*: node depth (0 to 255, 0 for leaves, or in sequential mode). 386 387* *inner_size*: inner digest size (0 to 64 for BLAKE2b, 0 to 32 for 388 BLAKE2s, 0 in sequential mode). 389 390* *last_node*: boolean indicating whether the processed node is the last 391 one (`False` for sequential mode). 392 393.. figure:: hashlib-blake2-tree.png 394 :alt: Explanation of tree mode parameters. 395 396See section 2.10 in `BLAKE2 specification 397<https://blake2.net/blake2_20130129.pdf>`_ for comprehensive review of tree 398hashing. 399 400 401Constants 402^^^^^^^^^ 403 404.. data:: blake2b.SALT_SIZE 405.. data:: blake2s.SALT_SIZE 406 407Salt length (maximum length accepted by constructors). 408 409 410.. data:: blake2b.PERSON_SIZE 411.. data:: blake2s.PERSON_SIZE 412 413Personalization string length (maximum length accepted by constructors). 414 415 416.. data:: blake2b.MAX_KEY_SIZE 417.. data:: blake2s.MAX_KEY_SIZE 418 419Maximum key size. 420 421 422.. data:: blake2b.MAX_DIGEST_SIZE 423.. data:: blake2s.MAX_DIGEST_SIZE 424 425Maximum digest size that the hash function can output. 426 427 428Examples 429^^^^^^^^ 430 431Simple hashing 432"""""""""""""" 433 434To calculate hash of some data, you should first construct a hash object by 435calling the appropriate constructor function (:func:`blake2b` or 436:func:`blake2s`), then update it with the data by calling :meth:`update` on the 437object, and, finally, get the digest out of the object by calling 438:meth:`digest` (or :meth:`hexdigest` for hex-encoded string). 439 440 >>> from hashlib import blake2b 441 >>> h = blake2b() 442 >>> h.update(b'Hello world') 443 >>> h.hexdigest() 444 '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183' 445 446 447As a shortcut, you can pass the first chunk of data to update directly to the 448constructor as the positional argument: 449 450 >>> from hashlib import blake2b 451 >>> blake2b(b'Hello world').hexdigest() 452 '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183' 453 454You can call :meth:`hash.update` as many times as you need to iteratively 455update the hash: 456 457 >>> from hashlib import blake2b 458 >>> items = [b'Hello', b' ', b'world'] 459 >>> h = blake2b() 460 >>> for item in items: 461 ... h.update(item) 462 >>> h.hexdigest() 463 '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183' 464 465 466Using different digest sizes 467"""""""""""""""""""""""""""" 468 469BLAKE2 has configurable size of digests up to 64 bytes for BLAKE2b and up to 32 470bytes for BLAKE2s. For example, to replace SHA-1 with BLAKE2b without changing 471the size of output, we can tell BLAKE2b to produce 20-byte digests: 472 473 >>> from hashlib import blake2b 474 >>> h = blake2b(digest_size=20) 475 >>> h.update(b'Replacing SHA1 with the more secure function') 476 >>> h.hexdigest() 477 'd24f26cf8de66472d58d4e1b1774b4c9158b1f4c' 478 >>> h.digest_size 479 20 480 >>> len(h.digest()) 481 20 482 483Hash objects with different digest sizes have completely different outputs 484(shorter hashes are *not* prefixes of longer hashes); BLAKE2b and BLAKE2s 485produce different outputs even if the output length is the same: 486 487 >>> from hashlib import blake2b, blake2s 488 >>> blake2b(digest_size=10).hexdigest() 489 '6fa1d8fcfd719046d762' 490 >>> blake2b(digest_size=11).hexdigest() 491 'eb6ec15daf9546254f0809' 492 >>> blake2s(digest_size=10).hexdigest() 493 '1bf21a98c78a1c376ae9' 494 >>> blake2s(digest_size=11).hexdigest() 495 '567004bf96e4a25773ebf4' 496 497 498Keyed hashing 499""""""""""""" 500 501Keyed hashing can be used for authentication as a faster and simpler 502replacement for `Hash-based message authentication code 503<https://en.wikipedia.org/wiki/HMAC>`_ (HMAC). 504BLAKE2 can be securely used in prefix-MAC mode thanks to the 505indifferentiability property inherited from BLAKE. 506 507This example shows how to get a (hex-encoded) 128-bit authentication code for 508message ``b'message data'`` with key ``b'pseudorandom key'``:: 509 510 >>> from hashlib import blake2b 511 >>> h = blake2b(key=b'pseudorandom key', digest_size=16) 512 >>> h.update(b'message data') 513 >>> h.hexdigest() 514 '3d363ff7401e02026f4a4687d4863ced' 515 516 517As a practical example, a web application can symmetrically sign cookies sent 518to users and later verify them to make sure they weren't tampered with:: 519 520 >>> from hashlib import blake2b 521 >>> from hmac import compare_digest 522 >>> 523 >>> SECRET_KEY = b'pseudorandomly generated server secret key' 524 >>> AUTH_SIZE = 16 525 >>> 526 >>> def sign(cookie): 527 ... h = blake2b(digest_size=AUTH_SIZE, key=SECRET_KEY) 528 ... h.update(cookie) 529 ... return h.hexdigest().encode('utf-8') 530 >>> 531 >>> def verify(cookie, sig): 532 ... good_sig = sign(cookie) 533 ... return compare_digest(good_sig, sig) 534 >>> 535 >>> cookie = b'user-alice' 536 >>> sig = sign(cookie) 537 >>> print("{0},{1}".format(cookie.decode('utf-8'), sig)) 538 user-alice,b'43b3c982cf697e0c5ab22172d1ca7421' 539 >>> verify(cookie, sig) 540 True 541 >>> verify(b'user-bob', sig) 542 False 543 >>> verify(cookie, b'0102030405060708090a0b0c0d0e0f00') 544 False 545 546Even though there's a native keyed hashing mode, BLAKE2 can, of course, be used 547in HMAC construction with :mod:`hmac` module:: 548 549 >>> import hmac, hashlib 550 >>> m = hmac.new(b'secret key', digestmod=hashlib.blake2s) 551 >>> m.update(b'message') 552 >>> m.hexdigest() 553 'e3c8102868d28b5ff85fc35dda07329970d1a01e273c37481326fe0c861c8142' 554 555 556Randomized hashing 557"""""""""""""""""" 558 559By setting *salt* parameter users can introduce randomization to the hash 560function. Randomized hashing is useful for protecting against collision attacks 561on the hash function used in digital signatures. 562 563 Randomized hashing is designed for situations where one party, the message 564 preparer, generates all or part of a message to be signed by a second 565 party, the message signer. If the message preparer is able to find 566 cryptographic hash function collisions (i.e., two messages producing the 567 same hash value), then they might prepare meaningful versions of the message 568 that would produce the same hash value and digital signature, but with 569 different results (e.g., transferring $1,000,000 to an account, rather than 570 $10). Cryptographic hash functions have been designed with collision 571 resistance as a major goal, but the current concentration on attacking 572 cryptographic hash functions may result in a given cryptographic hash 573 function providing less collision resistance than expected. Randomized 574 hashing offers the signer additional protection by reducing the likelihood 575 that a preparer can generate two or more messages that ultimately yield the 576 same hash value during the digital signature generation process --- even if 577 it is practical to find collisions for the hash function. However, the use 578 of randomized hashing may reduce the amount of security provided by a 579 digital signature when all portions of the message are prepared 580 by the signer. 581 582 (`NIST SP-800-106 "Randomized Hashing for Digital Signatures" 583 <https://csrc.nist.gov/publications/detail/sp/800-106/final>`_) 584 585In BLAKE2 the salt is processed as a one-time input to the hash function during 586initialization, rather than as an input to each compression function. 587 588.. warning:: 589 590 *Salted hashing* (or just hashing) with BLAKE2 or any other general-purpose 591 cryptographic hash function, such as SHA-256, is not suitable for hashing 592 passwords. See `BLAKE2 FAQ <https://blake2.net/#qa>`_ for more 593 information. 594.. 595 596 >>> import os 597 >>> from hashlib import blake2b 598 >>> msg = b'some message' 599 >>> # Calculate the first hash with a random salt. 600 >>> salt1 = os.urandom(blake2b.SALT_SIZE) 601 >>> h1 = blake2b(salt=salt1) 602 >>> h1.update(msg) 603 >>> # Calculate the second hash with a different random salt. 604 >>> salt2 = os.urandom(blake2b.SALT_SIZE) 605 >>> h2 = blake2b(salt=salt2) 606 >>> h2.update(msg) 607 >>> # The digests are different. 608 >>> h1.digest() != h2.digest() 609 True 610 611 612Personalization 613""""""""""""""" 614 615Sometimes it is useful to force hash function to produce different digests for 616the same input for different purposes. Quoting the authors of the Skein hash 617function: 618 619 We recommend that all application designers seriously consider doing this; 620 we have seen many protocols where a hash that is computed in one part of 621 the protocol can be used in an entirely different part because two hash 622 computations were done on similar or related data, and the attacker can 623 force the application to make the hash inputs the same. Personalizing each 624 hash function used in the protocol summarily stops this type of attack. 625 626 (`The Skein Hash Function Family 627 <http://www.skein-hash.info/sites/default/files/skein1.3.pdf>`_, 628 p. 21) 629 630BLAKE2 can be personalized by passing bytes to the *person* argument:: 631 632 >>> from hashlib import blake2b 633 >>> FILES_HASH_PERSON = b'MyApp Files Hash' 634 >>> BLOCK_HASH_PERSON = b'MyApp Block Hash' 635 >>> h = blake2b(digest_size=32, person=FILES_HASH_PERSON) 636 >>> h.update(b'the same content') 637 >>> h.hexdigest() 638 '20d9cd024d4fb086aae819a1432dd2466de12947831b75c5a30cf2676095d3b4' 639 >>> h = blake2b(digest_size=32, person=BLOCK_HASH_PERSON) 640 >>> h.update(b'the same content') 641 >>> h.hexdigest() 642 'cf68fb5761b9c44e7878bfb2c4c9aea52264a80b75005e65619778de59f383a3' 643 644Personalization together with the keyed mode can also be used to derive different 645keys from a single one. 646 647 >>> from hashlib import blake2s 648 >>> from base64 import b64decode, b64encode 649 >>> orig_key = b64decode(b'Rm5EPJai72qcK3RGBpW3vPNfZy5OZothY+kHY6h21KM=') 650 >>> enc_key = blake2s(key=orig_key, person=b'kEncrypt').digest() 651 >>> mac_key = blake2s(key=orig_key, person=b'kMAC').digest() 652 >>> print(b64encode(enc_key).decode('utf-8')) 653 rbPb15S/Z9t+agffno5wuhB77VbRi6F9Iv2qIxU7WHw= 654 >>> print(b64encode(mac_key).decode('utf-8')) 655 G9GtHFE1YluXY1zWPlYk1e/nWfu0WSEb0KRcjhDeP/o= 656 657Tree mode 658""""""""" 659 660Here's an example of hashing a minimal tree with two leaf nodes:: 661 662 10 663 / \ 664 00 01 665 666This example uses 64-byte internal digests, and returns the 32-byte final 667digest:: 668 669 >>> from hashlib import blake2b 670 >>> 671 >>> FANOUT = 2 672 >>> DEPTH = 2 673 >>> LEAF_SIZE = 4096 674 >>> INNER_SIZE = 64 675 >>> 676 >>> buf = bytearray(6000) 677 >>> 678 >>> # Left leaf 679 ... h00 = blake2b(buf[0:LEAF_SIZE], fanout=FANOUT, depth=DEPTH, 680 ... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE, 681 ... node_offset=0, node_depth=0, last_node=False) 682 >>> # Right leaf 683 ... h01 = blake2b(buf[LEAF_SIZE:], fanout=FANOUT, depth=DEPTH, 684 ... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE, 685 ... node_offset=1, node_depth=0, last_node=True) 686 >>> # Root node 687 ... h10 = blake2b(digest_size=32, fanout=FANOUT, depth=DEPTH, 688 ... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE, 689 ... node_offset=0, node_depth=1, last_node=True) 690 >>> h10.update(h00.digest()) 691 >>> h10.update(h01.digest()) 692 >>> h10.hexdigest() 693 '3ad2a9b37c6070e374c7a8c508fe20ca86b6ed54e286e93a0318e95e881db5aa' 694 695Credits 696^^^^^^^ 697 698BLAKE2_ was designed by *Jean-Philippe Aumasson*, *Samuel Neves*, *Zooko 699Wilcox-O'Hearn*, and *Christian Winnerlein* based on SHA-3_ finalist BLAKE_ 700created by *Jean-Philippe Aumasson*, *Luca Henzen*, *Willi Meier*, and 701*Raphael C.-W. Phan*. 702 703It uses core algorithm from ChaCha_ cipher designed by *Daniel J. Bernstein*. 704 705The stdlib implementation is based on pyblake2_ module. It was written by 706*Dmitry Chestnykh* based on C implementation written by *Samuel Neves*. The 707documentation was copied from pyblake2_ and written by *Dmitry Chestnykh*. 708 709The C code was partly rewritten for Python by *Christian Heimes*. 710 711The following public domain dedication applies for both C hash function 712implementation, extension code, and this documentation: 713 714 To the extent possible under law, the author(s) have dedicated all copyright 715 and related and neighboring rights to this software to the public domain 716 worldwide. This software is distributed without any warranty. 717 718 You should have received a copy of the CC0 Public Domain Dedication along 719 with this software. If not, see 720 https://creativecommons.org/publicdomain/zero/1.0/. 721 722The following people have helped with development or contributed their changes 723to the project and the public domain according to the Creative Commons Public 724Domain Dedication 1.0 Universal: 725 726* *Alexandr Sokolovskiy* 727 728.. _BLAKE2: https://blake2.net 729.. _HMAC: https://en.wikipedia.org/wiki/Hash-based_message_authentication_code 730.. _BLAKE: https://131002.net/blake/ 731.. _SHA-3: https://en.wikipedia.org/wiki/NIST_hash_function_competition 732.. _ChaCha: https://cr.yp.to/chacha.html 733.. _pyblake2: https://pythonhosted.org/pyblake2/ 734 735 736 737.. seealso:: 738 739 Module :mod:`hmac` 740 A module to generate message authentication codes using hashes. 741 742 Module :mod:`base64` 743 Another way to encode binary hashes for non-binary environments. 744 745 https://blake2.net 746 Official BLAKE2 website. 747 748 https://csrc.nist.gov/csrc/media/publications/fips/180/2/archive/2002-08-01/documents/fips180-2.pdf 749 The FIPS 180-2 publication on Secure Hash Algorithms. 750 751 https://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms 752 Wikipedia article with information on which algorithms have known issues and 753 what that means regarding their use. 754 755 https://www.ietf.org/rfc/rfc8018.txt 756 PKCS #5: Password-Based Cryptography Specification Version 2.1 757