Most of the cryptography a network or security engineer writes is small: a checksum for a software image, a signature on a webhook, a token for an API, a key for a lab, a password that must be stored without being kept. 's standard library has a module for each job. hashlib computes digests, hmac computes keyed digests and compares them safely, and secrets produces randomness that an attacker cannot predict. This part of the Python series takes them in that order, from the library reference read on 27 October 2026, and runs every example on 3.13.16, a release on the 3.13 branch, which the Developer's Guide lists in its security phase until October 2029. Where a result can be checked elsewhere, it is checked against the site's hash tool and HMAC tool.
hashlib: one interface for many hash functions
The library reference describes hashlib as "a common interface to many different hash algorithms": the family of 180-4, the SHA-3 family of FIPS 202, and the legacy SHA-1 and . Every algorithm has a constructor that returns a hash object; you feed it bytes with update() and read the result with digest() or hexdigest(). The constructors for SHA-1, the SHA-2 and SHA-3 functions, SHAKE and BLAKE2 "are always present"; MD5 "is normally available as well, though it may be missing or blocked" in rare FIPS-compliant builds, and anything else depends on the the interpreter was linked against and is reached by name through hashlib.new(). Since 3.12, CPython falls back to "a verified implementation from the HACL* project" for MD5, SHA-1, SHA-2 and SHA-3 when OpenSSL does not provide them.
import hashlib # the standard library's hash functions
# One call: the data must be bytes, so text is encoded first.
print(hashlib.sha256("abc".encode("utf-8")).hexdigest())
# The same digest fed in pieces: update() calls concatenate.
h = hashlib.sha256() # an empty SHA-256 object
h.update(b"a") # first piece
h.update(b"bc") # second piece: same as update(b"abc")
print(h.hexdigest(), h.digest_size, "bytes")
# By name, for algorithms chosen at run time (from a config file, say).
print(hashlib.new("sha3_256", b"abc").hexdigest()[:16], "...")
# What every CPython has, and what this build's OpenSSL adds.
print(len(hashlib.algorithms_guaranteed), "guaranteed:", sorted(hashlib.algorithms_guaranteed)[:6], "...")
print(len(hashlib.algorithms_available), "available here")
# MD5 for a non-security job (a cache key, a duplicate check): say so explicitly.
print(hashlib.md5(b"show running-config", usedforsecurity=False).hexdigest())
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad 32 bytes
3a985da74fe225b2 ...
14 guaranteed: ['blake2b', 'blake2s', 'md5', 'sha1', 'sha224', 'sha256'] ...
19 available here
d064a73c32d00bf384204782a696a298
The SHA-256 of abc is the value the hash tool computes and keeps among its own test vectors, and the hashing article explains what the function guarantees. Two details matter in practice. A hash function works on bytes, so hashing text means choosing an encoding first, which is the subject of the bytes and text article of this series. And since Python 3.9 every constructor takes a keyword-only usedforsecurity argument: in the reference's words, a false value "allows the use of insecure and blocked hashing algorithms in restricted environments" and indicates "that the hashing algorithm is not used in a security context, e.g. as a non-cryptographic one-way compression function". It documents intent, which is why a FIPS-restricted build lets the last line run and why a code scanner treats an MD5 call without it differently, as the secure coding article shows. The reference also warns that MD5 and SHA-1 have "known hash collision weaknesses"; the hash families article says which ones to retire.
Hashing a file
A checksum on a download page is the commonest hash an engineer meets. Since Python 3.11, hashlib.file_digest() takes a file object opened in binary mode and returns the updated hash object, reading the file in blocks so that a large software image never has to sit in memory whole. The reference adds that the file must be in blocking mode, and from 3.13.4 a non-blocking one raises BlockingIOError instead of producing a wrong digest.
import hashlib # file_digest() is in hashlib from Python 3.11
from pathlib import Path # file paths
PUBLISHED = "19D6D9FAF9CE166ABEB8452FF274241877EB1C09580F7EF62FF77696A6BEE1FC" # as the download page prints it
def sha256_of(path: Path) -> str:
"""Hex SHA-256 of a file, read in blocks so a large image never sits in memory whole."""
with path.open("rb") as f: # binary mode: hashes work on bytes
return hashlib.file_digest(f, "sha256").hexdigest() # the helper reads and feeds the blocks
good = Path("lab-image.bin") # a stand-in for a downloaded software image
good.write_bytes(bytes(range(256)) * 40_000) # 10,240,000 bytes of test data
bad = Path("lab-image-copy.bin") # the same file with one bit changed in transit
data = bytearray(good.read_bytes()) # a mutable copy of the good image
data[5_000_000] ^= 0x01 # flip one bit in the middle
bad.write_bytes(data) # save the damaged copy
for path in (good, bad): # check both files against the published value
digest = sha256_of(path) # 64 lower-case hex digits
print(f"{path.name:<19} {digest[:16]}... match={digest == PUBLISHED.lower()}") # hex is case-insensitive: normalise
lab-image.bin 19d6d9faf9ce166a... match=True
lab-image-copy.bin 27d8fb24e702ecd8... match=False
One flipped bit gives an unrelated digest, which is what makes the comparison useful. What it proves is narrower than it looks: the file matches the checksum you were given. If the checksum came from the same page as the file, whoever can change one can change the other; a signature made with a key you already trust closes that gap, and the next article signs and verifies a configuration backup with Ed25519.
Passwords are a different job
The same reference draws the line itself: "Naive algorithms such as sha1(password) are not resistant against attacks. A good password hashing function must be tunable, slow, and include a salt." Its BLAKE2 section adds that salted hashing with BLAKE2 "or any other general-purpose cryptographic hash function, such as SHA-256, is not suitable for hashing passwords". The site's password hash guide gives the order of preference: Argon2id, then scrypt, then bcrypt, and PBKDF2 where FIPS compliance requires it. 's Password Storage Cheat Sheet gives the starting parameters: for Argon2id, 19 MiB of memory, two iterations and one degree of parallelism (or an equivalent row of its table); for scrypt, N of 2^17, r of 8 and p of 1; for PBKDF2 with -SHA-256, 600,000 iterations.
The standard library has two of the four. hashlib.scrypt() implements 7914, and hashlib.pbkdf2_hmac() implements PBKDF2 from PKCS #5, which since 3.12 exists only when Python is built with OpenSSL. For both, the reference asks for a salt of "about 16 or more bytes from a proper source, e.g. os.urandom()" and suggests limiting the password to a sensible length (its example is 1024).
import base64 # store bytes as text
import hashlib # scrypt() and pbkdf2_hmac()
import hmac # compare_digest()
import os # urandom() for the salt
import time # how long one derivation takes
N, R, P = 2**17, 8, 1 # OWASP's first scrypt setting: about 128 MiB of memory per hash
salt = os.urandom(16) # a new random salt for every password, 16 bytes or more
try:
hashlib.scrypt(b"correct horse", salt=salt, n=N, r=R, p=P) # maxmem left at its default
except ValueError as exc: # OpenSSL's default memory ceiling is 32 MiB
print("default maxmem:", exc)
def hash_password(password: str) -> str:
"""Derive with scrypt and keep every parameter with the result, so they can be raised later."""
salt = os.urandom(16) # unique per password
key = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=N, r=R, p=P,
maxmem=256 * 1024 * 1024, dklen=32) # allow the 128 MiB this setting needs
b64 = lambda b: base64.b64encode(b).decode("ascii") # bytes to printable text
return f"scrypt${N}${R}${P}${b64(salt)}${b64(key)}" # our own storage format
def verify_password(password: str, stored: str) -> bool:
"""Recompute with the stored parameters and compare in constant time."""
_, n, r, p, salt, key = stored.split("$") # the fields written by hash_password()
again = hashlib.scrypt(password.encode("utf-8"), salt=base64.b64decode(salt), n=int(n), r=int(r),
p=int(p), maxmem=256 * 1024 * 1024, dklen=32) # same inputs, same parameters
return hmac.compare_digest(again, base64.b64decode(key)) # never ==
t0 = time.perf_counter() # start the clock
stored = hash_password("correct horse battery staple") # what the database would keep
print(f"scrypt: {time.perf_counter() - t0:.2f} s ->", stored[:40] + "...")
print("right password:", verify_password("correct horse battery staple", stored))
print("wrong password:", verify_password("correct horse battery stapler", stored))
t0 = time.perf_counter() # PBKDF2 where FIPS-validated primitives are required
dk = hashlib.pbkdf2_hmac("sha256", b"correct horse battery staple", salt, 600_000) # OWASP: 600,000 for HMAC-SHA-256
print(f"pbkdf2_hmac sha256 x 600,000: {time.perf_counter() - t0:.2f} s ->", dk.hex()[:16] + "...")
default maxmem: [digital envelope routines] memory limit exceeded
scrypt: 0.52 s -> scrypt$131072$8$1$n9hDOoIitAVkW2iXgBWrBw...
right password: True
wrong password: False
pbkdf2_hmac sha256 x 600,000: 0.38 s -> b4df7f477a735cda...
The first line is the trap: the reference notes that maxmem "limits memory (OpenSSL 1.1.0 defaults to 32 MiB)", so OWASP's recommended setting fails until you raise the ceiling. The storage string is this example's own format; what matters is that the salt and every cost parameter travel with the hash, so that the parameters can be raised for new passwords while old ones still verify, and that the check uses compare_digest(), explained below. The timings are those of the recorded run on the build machine.
Argon2id is not in the standard library. The pyca/cryptography package has had an Argon2id class since release 44.0.0, and since 45.0.0 it reads and writes the Password Hashing Competition (PHC) string format, which carries the algorithm, the parameters, the salt and the hash in one string. The package's documentation says Argon2id "should be used by most users, as recommended in RFC 9106":
import os # urandom() for the salt
from cryptography.exceptions import InvalidKey # raised when a password does not match
from cryptography.hazmat.primitives.kdf.argon2 import Argon2id # cryptography 44.0 and later
kdf = Argon2id(salt=os.urandom(16), length=32, iterations=2, lanes=1, memory_cost=19456) # OWASP: 19 MiB, t=2, p=1
stored = kdf.derive_phc_encoded(b"correct horse battery staple") # one string: algorithm, parameters, salt, hash
print(stored)
for attempt in (b"correct horse battery staple", b"correct horse battery stapler"): # right, then wrong
try:
Argon2id.verify_phc_encoded(attempt, stored) # parameters come from the string itself
print(attempt.decode(), "-> accepted")
except InvalidKey: # a mismatch is an exception, not False
print(attempt.decode(), "-> rejected")
$argon2id$v=19$m=19456,t=2,p=1$6psAOWhve1KCRijnXqTZFA$ROYKHyHoHI1vYSRUjHIf6mLILzN2e65R5AT6ykYnX8s
correct horse battery staple -> accepted
correct horse battery stapler -> rejected
The run used cryptography 50.0.2, installed with pip into a throwaway virtual environment; the next article explains why that class lives under a package called hazmat.
Pwned Passwords: SHA-1 as a lookup key
Checking a new password against known breaches is the other half of the password guide's advice, and 's range API is built so that the password never leaves the machine. Its documentation describes the model: the client sends "the first 5 characters of either a SHA-1 or an hash", the service answers with "the suffix of every hash beginning with the specified prefix", about 800 of them, and the client looks for its own suffix locally; there are 1,048,576 prefixes and every one returns HTTP 200. The script below computes what would be sent and stops there:
import hashlib # SHA-1, used here as a lookup key and not to protect anything
password = "P@ssw0rd" # a well-known test string; never put a real password in a script
digest = hashlib.sha1(password.encode("utf-8"), usedforsecurity=False).hexdigest().upper() # the range API's form
prefix, suffix = digest[:5], digest[5:] # 5 characters leave the machine, 35 stay
print("SHA-1 :", digest)
print("sent :", f"GET https://api.pwnedpasswords.com/range/{prefix}") # printed, not requested
print("kept :", suffix, "(compared locally with the suffixes in the reply)")
print("ranges :", 16**5) # every prefix from 00000 to FFFFF is a valid range
SHA-1 : 21BD12DC183F740EE76F27B78EB39C8AD972A757
sent : GET https://api.pwnedpasswords.com/range/21BD1
kept : 2DC183F740EE76F27B78EB39C8AD972A757 (compared locally with the suffixes in the reply)
ranges : 1048576
21BD1 is also the prefix whose sample response the API documentation prints. SHA-1 is acceptable here for the reason the password guide gives: nothing is being stored or protected by it, it only divides the corpus into ranges, and usedforsecurity=False says exactly that. The site's Pwned Passwords check does the same in your browser, shows the five characters before anything is sent, and asks only when you press Ask or Enter.
hmac: a hash with a key
A plain hash tells you that data has not changed only if the hash itself reached you safely. HMAC, defined in RFC 2104, mixes a secret key into the hash, so only a holder of the key can produce a valid tag; the site's HMAC article explains the construction and why HMAC explains why hash(key + message) is not a safe substitute. In Python, hmac.new(key, msg, digestmod) returns an HMAC object, and the reference stresses that digestmod is required "despite its argument position" (since 3.8). hmac.digest() is a one-shot form that "uses an optimized C or inline implementation", and extendable-output functions such as SHAKE "cannot be used with HMAC".
import hashlib # the hash HMAC is built on
import hmac # RFC 2104 HMAC
import json # a webhook-style JSON body
# RFC 4231, test case 2: key "Jefe", data "what do ya want for nothing?".
print(hmac.new(b"Jefe", b"what do ya want for nothing?", hashlib.sha256).hexdigest())
print(hmac.digest(b"Jefe", b"what do ya want for nothing?", "sha256").hex()[:16], "...") # one-shot form
SECRET = b"lab-shared-secret-0f7c" # in real use: from a vault or the environment, never in the code
def sign(body: bytes) -> str:
"""What the sender puts in a header: hex HMAC-SHA256 of the exact body bytes."""
return hmac.new(SECRET, body, hashlib.sha256).hexdigest() # digestmod is required since 3.8
def verify(body: bytes, received: str) -> bool:
"""What the receiver does: recompute over the bytes as received, compare in constant time."""
return hmac.compare_digest(sign(body), received) # never ==
body = b'{"event": "config-change", "device": "r1", "user": "netops"}' # bytes as they arrived
tag = sign(body) # the sender's signature
print("intact body :", verify(body, tag))
print("one byte changed :", verify(body.replace(b"r1", b"r2"), tag))
# Re-serialising the parsed JSON changes the bytes (spacing here), so the tag no longer matches.
reserialised = json.dumps(json.loads(body), separators=(",", ":")).encode() # same data, different bytes
print("re-serialised :", verify(reserialised, tag))
5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843
5bdcc146bf60754e ...
intact body : True
one byte changed : False
re-serialised : False
The first line is RFC 4231's published HMAC-SHA-256 value for its second test case, and the HMAC tool holds the same vector. The last line is the bug that sends people to forums: a receiver that parses the JSON and re-serialises it before checking computes the tag over different bytes, even though the data is the same. Verify over the raw body as it arrived, then parse. A valid tag also says nothing about freshness; the verification article adds timestamps and replay windows, and the API signing article shows real schemes built on the same function.
compare_digest, and why == is the wrong comparison
The reference's warning on digest() and hexdigest() is short: when comparing them "to an externally supplied digest during a verification routine", use compare_digest() "instead of the == operator to reduce the vulnerability to timing attacks". The function returns a == b "using an approach designed to prevent timing analysis by avoiding content-based short circuiting behaviour"; since 3.10 it uses OpenSSL's CRYPTO_memcmp() where available. Its note sets the limit honestly: when the lengths differ or an error occurs, a timing attack "could theoretically reveal information about the types and lengths" of the two arguments, though not their values. The secrets module exports the same function.
import hmac # compare_digest()
import secrets # the same function, under a second name
tag = "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" # a hex tag, as ASCII text
print(secrets.compare_digest is hmac.compare_digest) # one function, two names
print(hmac.compare_digest(tag, tag), hmac.compare_digest(bytes.fromhex(tag), bytes.fromhex(tag))) # str/str, bytes/bytes
for x, y in ((tag, bytes.fromhex(tag)), ("café", "café")): # mixed types, then non-ASCII text
try:
hmac.compare_digest(x, y) # both cases are refused
except TypeError as exc: # the function raises rather than guessing
print("TypeError:", exc)
True
True True
TypeError: a bytes-like object is required, not 'str'
TypeError: comparing strings with non-ASCII characters is not supported
Both arguments must be the same type, either bytes-like objects or strings that are " only, as e.g. returned by HMAC.hexdigest()". Comparing raw digests as bytes avoids the question of hex case altogether. The same rule applies beyond HMAC: an API token, a session cookie or a password hash read back from storage should all be compared this way.
secrets: randomness an attacker cannot predict
The random module is the wrong tool for anything secret, and its own documentation says so: its Mersenne Twister generator is "completely deterministic" and "completely unsuitable for cryptographic purposes". 506 added secrets in Python 3.6 because, in its words, the standard library made it "too easy for developers to inadvertently make serious security errors". The module provides "access to the most secure source of randomness that your operating system provides", with helpers for the shapes secrets usually take:
import random # a simulation generator: never for secrets
import secrets # the operating system's best randomness
import string # alphabets for passwords
print(secrets.DEFAULT_ENTROPY, "bytes by default") # the token_* functions' default size today
print(secrets.token_hex(16)) # 16 random bytes as 32 hex digits
print(secrets.token_urlsafe()) # 32 bytes, base64url, safe in a URL or a header
key = secrets.token_bytes(32) # raw bytes, for an HMAC key or a pre-shared key
print(len(key), "raw bytes")
alphabet = string.ascii_letters + string.digits # 62 symbols
print("".join(secrets.choice(alphabet) for _ in range(20))) # a 20-character password, the documentation's recipe
# Why not random: the same seed gives the same "random" sequence, on any machine.
random.seed(2026) # anyone who learns or guesses the seed...
first = [random.randrange(256) for _ in range(4)] # ...can rebuild these bytes
random.seed(2026) # same seed again
print(first, first == [random.randrange(256) for _ in range(4)]) # identical
32 bytes by default
94a7d608956e26d2ddabb7c5ebca01f5
_QO3H-QNU6ohCt1r452y19SF4dcZp78subyuzS4FrB4
32 raw bytes
fhrwcanr2KBT0gj2uTYO
[60, 163, 52, 114] True
The documentation explains the default: "As of 2015, it is believed that 32 bytes (256 bits) of randomness is sufficient for the typical use-case", and it warns that the exact value of DEFAULT_ENTROPY "is subject to change at any time, including during maintenance releases", so pass the size explicitly when a protocol fixes it. Its recipes section generates passwords with secrets.choice() and adds a reminder that applications "should not store passwords in a recoverable format". The pyca/cryptography documentation gives the same advice for keys and nonces: use os.urandom() or secrets, never random.
What a scanner sees in this code
A code scanner reads these choices as patterns. , covered in the secure coding article of this series, flags MD4, MD5 and SHA-1 calls in hashlib (test B324, which also reads usedforsecurity; the MD5 call in that article's run was reported at high severity) and any use of the random module's generators (B311, low severity). Both are cheap to fix in new code: mark non-security digests as such, and take every secret from secrets.
A short checklist
- Hash bytes, not text: encode explicitly, and hash files with
hashlib.file_digest(). - Use SHA-256 or newer for anything that must resist tampering; mark MD5 and SHA-1 uses with
usedforsecurity=Falsewhen nothing depends on their strength. - Never store a password with a plain hash: Argon2id through pyca/cryptography, or scrypt from
hashlibwith the parameters stored next to the hash andmaxmemraised to fit them. - Sign with HMAC over the exact bytes sent and received, and verify before parsing.
- Compare tags, tokens and hashes with
hmac.compare_digest(), bytes with bytes or ASCII text with ASCII text. - Take every token, key, salt and nonce from
secretsoros.urandom(), never fromrandom.
Sources
- Python 3.13 documentation: hashlib, secure hashes and message digests (constructors, usedforsecurity, file_digest, pbkdf2_hmac, scrypt, BLAKE2) (read 2026-10-27)
- CPython source, 3.13 branch, Lib/hashlib.py: file_digest() reads into a reusable 256 KiB buffer (read 2026-10-27)
- Python 3.13 documentation: hmac, keyed-hashing for message authentication (new, digest, compare_digest) (read 2026-10-27)
- Python 3.13 documentation: secrets, generate secure random numbers for managing secrets (read 2026-10-27)
- Python 3.13 documentation: random, the warning against security use and the Mersenne Twister (read 2026-10-27)
- Python documentation (3.15): hashlib, the current text of the same page (read 2026-10-27)
- PEP 506, Adding A Secrets Module To The Standard Library (read 2026-10-27)
- Python Developer's Guide, Status of Python versions: 3.13 in security status until 2029-10 (read 2026-10-27)
- RFC 2104, HMAC: Keyed-Hashing for Message Authentication (read 2026-10-27)
- RFC 4231, Identifiers and Test Vectors for HMAC-SHA-224, HMAC-SHA-256, HMAC-SHA-384, and HMAC-SHA-512: test case 2 (read 2026-10-27)
- RFC 7914, The scrypt Password-Based Key Derivation Function (read 2026-10-27)
- RFC 8018, PKCS #5: Password-Based Cryptography Specification Version 2.1, PBKDF2 (read 2026-10-27)
- RFC 9106, Argon2 Memory-Hard Function for Password Hashing and Proof-of-Work Applications (read 2026-10-27)
- OWASP Cheat Sheet Series, Password Storage Cheat Sheet: Argon2id, scrypt, bcrypt and PBKDF2 parameters (read 2026-10-27)
- cryptography 50.0.2 documentation: key derivation functions, Argon2id, derive_phc_encoded and verify_phc_encoded (read 2026-10-27)
- cryptography 50.0.2 documentation: random number generation (read 2026-10-27)
- Have I Been Pwned, API v3: Pwned Passwords, searching by hash range using k-anonymity (read 2026-10-27)
- Bandit documentation: B324, insecure md4, md5 or sha1 in hashlib, with the usedforsecurity check (read 2026-10-27)
- Bandit documentation: blacklist calls, B311 random, severity Low (read 2026-10-27)