Navigation

This module implements a common interface to many different secure hash and
message digest algorithms. Included are the FIPS secure hash algorithms SHA1,
SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA’s MD5
algorithm (defined in Internet RFC 1321). The terms “secure hash” and
“message digest” are interchangeable. Older algorithms were called message
digests. The modern term is secure hash.

Note

If you want the adler32 or crc32 hash functions, they are available in
the zlib module.

Warning

Some algorithms have known hash collision weaknesses, refer to the “See
also” section at the end.

There is one constructor method named for each type of hash. All return
a hash object with the same simple interface. For example: use sha256() to
create a SHA-256 hash object. You can now feed this object with bytes-like
objects (normally bytes) using the update() method.
At any point you can ask it for the digest of the
concatenation of the data fed to it so far using the digest() or
hexdigest() methods.

Note

For better multithreading performance, the Python GIL is released for
data larger than 2047 bytes at object creation or on update.

Note

Feeding string objects into update() is not supported, as hashes work
on bytes, not on characters.

Constructors for hash algorithms that are always present in this module are
sha1(), sha224(), sha256(), sha384(),
sha512(), blake2b(), and blake2s().
md5() is normally available as well, though it
may be missing if you are using a rare “FIPS compliant” build of Python.
Additional algorithms may also be available depending upon the OpenSSL
library that Python uses on your platform. On most platforms the
sha3_224(), sha3_256(), sha3_384(), sha3_512(),
shake_128(), shake_256() are also available.

Is a generic constructor that takes the string name of the desired
algorithm as its first parameter. It also exists to allow access to the
above listed hashes as well as any other algorithms that your OpenSSL
library may offer. The named constructors are much faster than new()
and should be preferred.

A set containing the names of the hash algorithms guaranteed to be supported
by this module on all platforms. Note that ‘md5’ is in this list despite
some upstream vendors offering an odd “FIPS compliant” Python build that
excludes it.

A set containing the names of the hash algorithms that are available in the
running Python interpreter. These names will be recognized when passed to
new(). algorithms_guaranteed will always be a subset. The
same algorithm may appear multiple times in this set under different names
(thanks to OpenSSL).

New in version 3.2.

The following values are provided as constant attributes of the hash objects
returned by the constructors:

Like digest() except the digest is returned as a string object of
double length, containing only hexadecimal digits. This may be used to
exchange the value safely in email or other non-binary environments.

The shake_128() and shake_256() algorithms provide variable
length digests with length_in_bits//2 up to 128 or 256 bits of security.
As such, their digest methods require a length. Maximum length is not limited
by the SHAKE algorithm.

Like digest() except the digest is returned as a string object of
double length, containing only hexadecimal digits. This may be used to
exchange the value safely in email or other non-binary environments.

Key derivation and key stretching algorithms are designed for secure password
hashing. Naive algorithms such as sha1(password) are not resistant against
brute-force attacks. A good password hashing function must be tunable, slow, and
include a salt.

The string hash_name is the desired name of the hash digest algorithm for
HMAC, e.g. ‘sha1’ or ‘sha256’. password and salt are interpreted as
buffers of bytes. Applications and libraries should limit password to
a sensible length (e.g. 1024). salt should be about 16 or more bytes from
a proper source, e.g. os.urandom().

The number of iterations should be chosen based on the hash algorithm and
computing power. As of 2013, at least 100,000 iterations of SHA-256 are
suggested.

dklen is the length of the derived key. If dklen is None then the
digest size of the hash algorithm hash_name is used, e.g. 64 for SHA-512.

password and salt must be bytes-like objects. Applications and libraries should limit password
to a sensible length (e.g. 1024). salt should be about 16 or more
bytes from a proper source, e.g. os.urandom().

These functions return the corresponding hash objects for calculating
BLAKE2b or BLAKE2s. They optionally take these general parameters:

data: initial chunk of data to hash, which must be
bytes-like object. It can be passed only as positional argument.

digest_size: size of output digest in bytes.

key: key for keyed hashing (up to 64 bytes for BLAKE2b, up to 32 bytes for
BLAKE2s).

salt: salt for randomized hashing (up to 16 bytes for BLAKE2b, up to 8
bytes for BLAKE2s).

person: personalization string (up to 16 bytes for BLAKE2b, up to 8 bytes
for BLAKE2s).

The following table shows limits for general parameters (in bytes):

Hash

digest_size

len(key)

len(salt)

len(person)

BLAKE2b

64

64

16

16

BLAKE2s

32

32

8

8

Note

BLAKE2 specification defines constant lengths for salt and personalization
parameters, however, for convenience, this implementation accepts byte
strings of any size up to the specified length. If the length of the
parameter is less than specified, it is padded with zeros, thus, for
example, b'salt' and b'salt\x00' is the same value. (This is not
the case for key.)

To calculate hash of some data, you should first construct a hash object by
calling the appropriate constructor function (blake2b() or
blake2s()), then update it with the data by calling update() on the
object, and, finally, get the digest out of the object by calling
digest() (or hexdigest() for hex-encoded string).

BLAKE2 has configurable size of digests up to 64 bytes for BLAKE2b and up to 32
bytes for BLAKE2s. For example, to replace SHA-1 with BLAKE2b without changing
the size of output, we can tell BLAKE2b to produce 20-byte digests:

Hash objects with different digest sizes have completely different outputs
(shorter hashes are not prefixes of longer hashes); BLAKE2b and BLAKE2s
produce different outputs even if the output length is the same:

Keyed hashing can be used for authentication as a faster and simpler
replacement for Hash-based message authentication code (HMAC).
BLAKE2 can be securely used in prefix-MAC mode thanks to the
indifferentiability property inherited from BLAKE.

This example shows how to get a (hex-encoded) 128-bit authentication code for
message b'messagedata' with key b'pseudorandomkey':

By setting salt parameter users can introduce randomization to the hash
function. Randomized hashing is useful for protecting against collision attacks
on the hash function used in digital signatures.

Randomized hashing is designed for situations where one party, the message
preparer, generates all or part of a message to be signed by a second
party, the message signer. If the message preparer is able to find
cryptographic hash function collisions (i.e., two messages producing the
same hash value), then they might prepare meaningful versions of the message
that would produce the same hash value and digital signature, but with
different results (e.g., transferring $1,000,000 to an account, rather than
$10). Cryptographic hash functions have been designed with collision
resistance as a major goal, but the current concentration on attacking
cryptographic hash functions may result in a given cryptographic hash
function providing less collision resistance than expected. Randomized
hashing offers the signer additional protection by reducing the likelihood
that a preparer can generate two or more messages that ultimately yield the
same hash value during the digital signature generation process — even if
it is practical to find collisions for the hash function. However, the use
of randomized hashing may reduce the amount of security provided by a
digital signature when all portions of the message are prepared
by the signer.

Sometimes it is useful to force hash function to produce different digests for
the same input for different purposes. Quoting the authors of the Skein hash
function:

We recommend that all application designers seriously consider doing this;
we have seen many protocols where a hash that is computed in one part of
the protocol can be used in an entirely different part because two hash
computations were done on similar or related data, and the attacker can
force the application to make the hash inputs the same. Personalizing each
hash function used in the protocol summarily stops this type of attack.

BLAKE2 was designed by Jean-Philippe Aumasson, Samuel Neves, Zooko
Wilcox-O’Hearn, and Christian Winnerlein based on SHA-3 finalist BLAKE
created by Jean-Philippe Aumasson, Luca Henzen, Willi Meier, and
Raphael C.-W. Phan.

It uses core algorithm from ChaCha cipher designed by Daniel J. Bernstein.

The stdlib implementation is based on pyblake2 module. It was written by
Dmitry Chestnykh based on C implementation written by Samuel Neves. The
documentation was copied from pyblake2 and written by Dmitry Chestnykh.

The C code was partly rewritten for Python by Christian Heimes.

The following public domain dedication applies for both C hash function
implementation, extension code, and this documentation:

To the extent possible under law, the author(s) have dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.