← Back to section · Tutorials & Labs

Password Storage in Practice: Storing Passwords Correctly with hashlib.scrypt and pbkdf2_hmac

User passwords must never be stored in plaintext, nor with a single SHA-256 — ordinary hashes are fast in exactly the way offline crackers want. This tutorial explains how password hashing fundamentally differs from ordinary hashing, and builds a complete salted, parameterized, verifiable storage format with hashlib.scrypt and hashlib.pbkdf2_hmac.

Published 22 November 2026 · 6 min read · PQ Frontier

Password Storage in Practice: Storing Passwords Correctly with hashlib.scrypt and pbkdf2_hmac
AI-generated site artwork
Video explainer · Python cryptography: experiments and prototypes

What this tutorial aims to do

Imagine your website’s database has been stolen — that is the starting assumption password storage must be designed under. The attacker now guesses passwords offline on their own machines, with no login rate limit in the way, and a single graphics card can test billions of candidates per second. That is why passwords cannot be stored with an ordinary hash: SHA-256 is frighteningly fast, which is precisely what the cracker wants. This tutorial builds storage you can actually deploy: understand why password hashing must be “deliberately slow”, implement the registration and verification paths with the standard library’s hashlib.scrypt and hashlib.pbkdf2_hmac, and get the parameters, salt and storage format right the first time.

How password hashing differs from ordinary hashing

Ordinary hashes are designed to be fast and uniform; password hashes are designed for the exact opposite, under three hard requirements. First, deliberate slowness: each computation must consume a meaningful amount of CPU time, dragging an attacker’s attempts per second from billions down to thousands. Second, memory hunger: algorithms such as scrypt occupy tens of megabytes while computing, so the thousands of parallel cores that make GPUs devastating are throttled by memory capacity and bandwidth, and cracking costs soar. Third, an independent random salt per user: the salt is a random byte string stored together with the password hash; it ensures that two users with the same password produce completely different stored values, so precomputed rainbow tables cannot hit in bulk and nobody can see at a glance who shares a password. The salt is not a secret and can sit in plaintext next to the hash — its job is to force every single password to be cracked separately, from scratch.

Registration and verification with scrypt

In hashlib.scrypt, the parameter n is the CPU/memory cost factor (it must be a power of two), r is the block size, p the parallelization factor and dklen the output length. The classic setting for interactive logins is n=2^14, r=8, p=1, using roughly 16 MB of memory and on the order of tens to a hundred milliseconds — imperceptible at login, excruciating for bulk cracking. For the storage format, pack the algorithm name, parameters and salt into one delimited string, as many mature libraries do, so that old records remain recognizable when parameters are upgraded later. Verification parses the parameters and salt back out of the record, recomputes the hash of the candidate password, and finishes with a constant-time comparison:

import hashlib, hmac, secrets

def hash_password(password: str) -> str:
    salt = secrets.token_bytes(16)
    n, r, p = 2**14, 8, 1
    dk = hashlib.scrypt(password.encode("utf-8"), salt=salt,
                        n=n, r=r, p=p, dklen=32)
    return f"scrypt${n}${r}${p}${salt.hex()}${dk.hex()}"

def verify_password(password: str, stored: str) -> bool:
    try:
        algo, n, r, p, salt_hex, hash_hex = stored.split("$")
        if algo != "scrypt":
            return False
        dk = hashlib.scrypt(password.encode("utf-8"),
                            salt=bytes.fromhex(salt_hex),
                            n=int(n), r=int(r), p=int(p), dklen=32)
    except (ValueError, MemoryError):
        return False
    return hmac.compare_digest(dk.hex(), hash_hex)

record = hash_password("correct horse battery staple")
print(verify_password("correct horse battery staple", record))  # True
print(verify_password("wrong password", record))                 # False

The modern first choice, Argon2, and two traps on the verification path

If your project can take a third-party dependency, the current industry-consensus first choice is actually Argon2id — the winner of the 2015 Password Hashing Competition, which goes further than scrypt in memory hunger and parallelism resistance. The usual Python binding is argon2-cffi, whose argon2.PasswordHasher class produces a complete encoded string containing algorithm, parameters and salt from its hash() method and verifies with verify(), sparing you the manual format assembly; this tutorial’s main line uses the standard library’s scrypt so that every step stays visible, but a greenfield project should consider Argon2id first. Then, two traps on the verification path. The first is user enumeration: if the login endpoint returns instantly for “no such user” but spends a hundred milliseconds hashing for “wrong password”, the response-time difference leaks whether an account exists; the fix is to run the same hash computation over a fixed dummy password when the user does not exist, keeping both paths equally slow. The second is resource amplification at verification: password hashing is deliberately expensive, which makes the login endpoint a natural CPU-consumption inlet, and an attacker can exhaust server capacity with floods of fake login attempts — so login rate limiting and failure throttling must ship together with password hashing, as a matched pair of defences rather than an either-or choice.

A frequently mis-asked question: should the client hash first?

Beginners often have a seemingly clever idea: let the browser or client hash the password once before sending it, so the server never sees the plaintext password. The idea confuses two different threats. Confidentiality in transit is the job of HTTPS, not of client-side hashing — without transport encryption, the hash the client computes is itself password-equivalent, and anyone who intercepts it can log in with it directly, a failure mode the field calls “the hash is the password”. Server-side password hashing defends against offline cracking after a database leak, and it requires the server to receive material it can process together with a per-user salt; if the client pre-hashes, the server ends up storing a slow hash of that value — workable, but it saves the server nothing and adds a layer of protocol complexity that needs careful justification. The conclusion is simple: no client-side pre-hashing, transport belongs to HTTPS, storage belongs to salted slow hashing, and each layer does its own job. Once this section is clear, you have separated the two entirely different attackers a password faces “on the wire” and “in the database”.

The PBKDF2 alternative and parameter maintenance

If your environment is sensitive to scrypt’s memory footprint, or you must interoperate with older systems that only support PBKDF2, hashlib.pbkdf2_hmac is the ready-made standard-library alternative: it buys time cost with a large iteration count, and current industry guidance for SHA-256 sits in the hundreds of thousands of iterations. It does not consume memory, so its resistance to GPU cracking is weaker than scrypt’s, but where a compliance checklist recognizes only PBKDF2 it is both compliant and serviceable. Whichever algorithm you choose, parameter maintenance is a long-term duty: first, recalibrate parameters every year or two against mainstream hardware so a single verification stays in the roughly one-hundred-millisecond target band; second, when a verification succeeds and the record’s parameters are below the current standard, transparently recompute and overwrite the record with the new parameters, migrating users painlessly at each login; third, never invent your own password-hashing construction, such as nesting SHA-256 ten thousand times — that has neither the salt discipline nor public analysis behind it, and is far weaker than the standard algorithms. One final boundary reminder: password hashing protects against offline cracking after a database leak; it does not replace transport encryption, login rate limiting or multi-factor authentication, and the online side of the defence must still be built separately.

Tags: PythonscryptPBKDF2Password Hashing