This module implements a common interface to many different hash algorithms.
Included are the FIPS secure hash algorithms SHA224, SHA256, SHA384, SHA512,
(defined in the FIPS 180-4 standard), the SHA-3 series (defined in the FIPS
202 standard) as well as the legacy algorithms SHA1 (formerly part of FIPS)
and the MD5 algorithm (defined in internet RFC 1321).
Note
If you want the adler32 or crc32 hash functions, they are available in
the zlib module.
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.
To allow multithreading, the Python GIL is released while computing a
hash supplied more than 2047 bytes of data at once in its constructor or
.update method.
Any of these may nonetheless be missing or blocked in unusual environments,
such as a rare “FIPS compliant” build of Python or when OpenSSL’s “FIPS mode”
is configured to exclude some algorithms from its default provider. Calling
the constructor of an algorithm that is unavailable raises ValueError.
Additional algorithms may also be available if your Python distribution’s
hashlib was linked against a build of OpenSSL that provides others.
Others are not guaranteed available on all installations and will only be
accessible by name via new(). See algorithms_available.
Changed in version 3.9: All hashlib constructors take a keyword-only argument usedforsecurity
with default value True. A false value allows the use of insecure and
blocked hashing algorithms in restricted environments. False indicates
that the hashing algorithm is not used in a security context, e.g. as a
non-cryptographic one-way compression function.
Changed in version 3.9: Hashlib now uses SHA3 and SHAKE from OpenSSL if it provides it.
Changed in version 3.12: For any of the MD5, SHA1, SHA2, or SHA3 algorithms that the linked
OpenSSL does not provide we fall back to a verified implementation from
the HACL* project.
Deprecated since version 3.15, will be removed in version 3.19: The undocumented string keyword parameter in _hashlib.new()
and hash-named constructors such as _md5.md5() is deprecated.
Prefer passing the initial data as a positional argument for maximum
backwards compatibility.
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.
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).
The canonical name of this hash, always lowercase and always suitable as a
parameter to new() to create another hash of this type.
Changed in version 3.4: The name attribute has been present in CPython since its inception, but
until Python 3.4 was not formally specified, so may not exist on some
platforms.
Update the hash object with the bytes-like object.
Repeated calls are equivalent to a single call with the
concatenation of all the arguments: m.update(a);m.update(b) is
equivalent to m.update(a+b).
Return the digest of the data passed to the update() method so far.
This is a bytes object of size digest_size which may contain bytes in
the whole range from 0 to 255.
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.
Return the digest of the data passed to the update() method so far.
This is a bytes object of size length which may contain bytes in
the whole range from 0 to 255.
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 in email or other non-binary environments.
Example use:
>>> h=hashlib.shake_256(b'Nobody inspects the spammish repetition')>>> h.hexdigest(20)'44709d6fcb83d92a76dcb0b668c98e1b1d3dafe7'
Return a digest object that has been updated with contents of file object.
fileobj must be a file-like object opened for reading in binary mode.
It accepts file objects from builtin open(), BytesIO
instances, SocketIO objects from socket.socket.makefile(), and
similar. fileobj must be opened in blocking mode, otherwise a
BlockingIOError may be raised.
The function may bypass Python’s I/O and use the file descriptor
from fileno() directly. fileobj must be assumed to be
in an unknown state after this function returns or raises. It is up to
the caller to close fileobj.
digest must either be a hash algorithm name as a str, a hash
constructor, or a callable that returns a hash object.
Changed in version 3.14: Now raises a BlockingIOError if the file is opened in non-blocking
mode. Previously, spurious null bytes were added to the digest.
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 function provides PKCS#5 password-based key derivation function 2. It
uses HMAC as pseudorandom function.
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 2022, hundreds of thousands of iterations of SHA-256
are suggested. For rationale as to why and how to choose what is best for
your application, read Appendix A.2.2 of NIST-SP-800-132. The answers
on the stackexchange pbkdf2 iterations question explain in detail.
dklen is the length of the derived key in bytes. If dklen is None then the
digest size of the hash algorithm hash_name is used, e.g. 64 for SHA-512.
Function only available when Python is compiled with OpenSSL.
Added in version 3.4.
Changed in version 3.12: Function now only available when Python is built with OpenSSL. The slow
pure Python implementation has been removed.
hashlib.scrypt(password, *, salt, n, r, p, maxmem=0, dklen=64)¶
The function provides scrypt password-based key derivation function as
defined in RFC 7914.
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().
n is the CPU/Memory cost factor, r the block size, p parallelization
factor and maxmem limits memory (OpenSSL 1.1.0 defaults to 32 MiB).
dklen is the length of the derived key in bytes.
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.)
These sizes are available as module constants described below.
Constructor functions also accept the following tree hashing parameters:
fanout: fanout (0 to 255, 0 if unlimited, 1 in sequential mode).
depth: maximal depth of tree (1 to 255, 255 if unlimited, 1 in
sequential mode).
leaf_size: maximal byte length of leaf (0 to 2**32-1, 0 if unlimited or in
sequential mode).
node_offset: node offset (0 to 2**64-1 for BLAKE2b, 0 to 2**48-1 for
BLAKE2s, 0 for the first, leftmost, leaf, or in sequential mode).
node_depth: node depth (0 to 255, 0 for leaves, or in sequential mode).
inner_size: inner digest size (0 to 64 for BLAKE2b, 0 to 32 for
BLAKE2s, 0 in sequential mode).
last_node: boolean indicating whether the processed node is the last
one (False for sequential mode).
See section 2.10 in BLAKE2 specification for comprehensive review of tree
hashing.
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:
>>> fromhashlibimportblake2b>>> h=blake2b(digest_size=20)>>> h.update(b'Replacing SHA1 with the more secure function')>>> h.hexdigest()'d24f26cf8de66472d58d4e1b1774b4c9158b1f4c'>>> h.digest_size20>>> len(h.digest())20
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.
In BLAKE2 the salt is processed as a one-time input to the hash function during
initialization, rather than as an input to each compression function.
Warning
Salted hashing (or just hashing) with BLAKE2 or any other general-purpose
cryptographic hash function, such as SHA-256, is not suitable for hashing
passwords. See BLAKE2 FAQ for more
information.
>>> importos>>> fromhashlibimportblake2b>>> msg=b'some message'>>> # Calculate the first hash with a random salt.>>> salt1=os.urandom(blake2b.SALT_SIZE)>>> h1=blake2b(salt=salt1)>>> h1.update(msg)>>> # Calculate the second hash with a different random salt.>>> salt2=os.urandom(blake2b.SALT_SIZE)>>> h2=blake2b(salt=salt2)>>> h2.update(msg)>>> # The digests are different.>>> h1.digest()!=h2.digest()True
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.
The following people have helped with development or contributed their changes
to the project and the public domain according to the Creative Commons Public
Domain Dedication 1.0 Universal:
The Python Software Foundation is a non-profit corporation.
Please donate.
Last updated on Nov 12, 2026 (08:53 UTC).
Found a bug?
Created using Sphinx 9.1.1.
You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.