LeepCast
Subscribe
All posts
Security

Password Hashing Explained: Argon2id, bcrypt, scrypt, and PBKDF2 Parameters That Hold Up

Why fast hashes fail for passwords, how the main password hashing algorithms compare, which cost settings OWASP and RFC 9106 actually recommend, and a working login flow that upgrades old hashes on the fly.

LeepCast8 min read

Every application that accepts passwords eventually faces the same question: what exactly goes into the database? The answer is never the password itself and never a fast hash such as SHA-256 on its own. It is the output of a deliberately slow, salted password hashing function whose cost settings are chosen on purpose and revisited over time. This guide explains why that is, compares Argon2id, scrypt, bcrypt and PBKDF2, gives the parameter values published by OWASP and RFC 9106, and walks through a working login flow that upgrades old hashes automatically.

Why a fast hash is the wrong tool

The threat model for stored passwords is an attacker who already has a copy of the user table. Breaches happen through SQL injection, leaked backups, misconfigured storage buckets and compromised admin accounts, so the design question is how expensive it is to turn each stolen hash back into a password. General-purpose hashes like SHA-256 are built to be fast, and graphics cards compute them in enormous parallel batches. An attacker can try dictionary words, leaked password lists and mutation rules against every stolen hash at very low cost.

Password hashing functions invert that priority. They are designed to be slow and, in the better designs, to require a large amount of memory per guess. A legitimate server pays that cost once per login. An attacker pays it for every single guess, multiplied by every account they want to crack. Memory-hard functions add a second penalty: GPUs and custom chips have plenty of arithmetic units but comparatively little fast memory per core, so forcing each guess to fill tens of megabytes of RAM limits how many guesses can run in parallel.

Salts, peppers and the stored string

A salt is a random value generated separately for each password and stored next to the hash. It makes precomputed lookup tables useless and ensures that two users with the same password end up with different hashes, so an attacker cannot crack one and learn the other for free. RFC 9106 recommends a 16-byte salt for password hashing. Modern libraries generate it for you; there is rarely a good reason to supply your own.

A pepper is a different idea: a single secret shared across all passwords and kept outside the database, ideally in a secrets manager or hardware security module. OWASP describes it as defense in depth only. It helps if the database leaks but the application secrets do not. It also has an operational cost: if the pepper is ever compromised and must be rotated, existing hashes cannot simply be re-keyed, because doing so requires the original passwords.

Libraries for Argon2, bcrypt and scrypt usually emit a self-describing string. An Argon2id hash in the common PHC string format looks like $argon2id$v=19$m=19456,t=2,p=1$ followed by the base64 salt and the base64 hash. The algorithm, version, memory cost in kibibytes, number of passes and degree of parallelism all travel with the hash. That detail matters later, because it lets one database hold hashes made with different settings, or even different algorithms, during a migration.

Choosing an algorithm

The OWASP Password Storage Cheat Sheet ranks the options in a clear order, and the reasoning behind each recommendation is worth knowing:

  • Argon2id is the first choice. It is specified in RFC 9106 and is the one variant that RFC requires every implementation to support. It combines Argon2i's side-channel resistance in the first half of the first pass with Argon2d's resistance to time-memory trade-off attacks for the rest.
  • scrypt is the fallback when Argon2id is not available. It is also memory-hard, but its settings are less intuitive and it is less commonly exposed by password libraries.
  • bcrypt is for legacy systems. It has a long track record but uses only a few kilobytes of memory, and most implementations only consider the first 72 bytes of input.
  • PBKDF2 is the option when FIPS-140 compliance is mandatory. It is not memory-hard, so it relies entirely on a high iteration count to slow attackers down.

The RFC also lists Argon2d and Argon2i. Argon2d uses data-dependent memory access and is aimed at proof-of-work settings where timing side channels are not a concern. Argon2i is data-independent. For storing user passwords, Argon2id is the variant to pick.

Parameter values that are actually published

Cost settings are where most real-world mistakes live, so it helps to start from the published numbers instead of library defaults copied from an old tutorial. The OWASP cheat sheet gives these minimums:

  • Argon2id: m=19456 (19 MiB), t=2, p=1. OWASP lists equivalent alternatives that trade memory for passes, such as m=47104 (46 MiB) with t=1, m=12288 (12 MiB) with t=3, m=9216 (9 MiB) with t=4, and m=7168 (7 MiB) with t=5, all at p=1.
  • scrypt: N=2^17 (128 MiB), r=8, p=1, with alternatives such as N=2^16 at p=2 or N=2^15 at p=3.
  • bcrypt: a work factor of at least 10, raised as high as your servers can tolerate.
  • PBKDF2: 600,000 iterations for HMAC-SHA256, 220,000 for HMAC-SHA512, and 1,400,000 for HMAC-SHA1, which is listed as legacy only.

RFC 9106 takes a different angle. Its first recommended option is Argon2id with t=1, p=4 and 2 GiB of memory, which is reasonable for key derivation on a well-provisioned machine but heavy for a web server handling many concurrent logins. Its second recommended option, intended for memory-constrained environments, is t=3, p=4 and 64 MiB. The Python argon2-cffi library uses that second profile, which it calls RFC_9106_LOW_MEMORY, as its default since version 21.2.0. Both sets of numbers are defensible; the right one depends on how much memory a login is allowed to consume on your hardware.

OWASP's general rule of thumb is that computing a single password hash should take less than one second, and that the right work factor is found by testing on the servers that will actually run it.

Tuning on your own hardware

Treat the published figures as a floor and measure. Memory cost is multiplied by concurrency: if 50 logins arrive at once with m=64 MiB, the hashing alone can briefly need over 3 GiB. Excessive settings also hand attackers an easy denial-of-service lever, because each failed login attempt costs you the same work as a successful one. The script below times verification at a few memory settings so you can pick a value that fits your latency budget and your container's memory limit.

python
import time
from argon2 import PasswordHasher

for memory_mib in (19, 46, 64):
    ph = PasswordHasher(time_cost=2, memory_cost=memory_mib * 1024, parallelism=1)
    stored = ph.hash("benchmark-password")
    start = time.perf_counter()
    for _ in range(10):
        ph.verify(stored, "benchmark-password")
    per_call_ms = (time.perf_counter() - start) / 10 * 1000
    print(f"m={memory_mib} MiB, t=2, p=1: {per_call_ms:.1f} ms per verify")

Run it on the same instance type that serves production traffic, not on a developer laptop, and repeat the measurement whenever you change hardware. Rate limiting on the login endpoint belongs alongside the hash settings, since it caps how much of that cost an attacker can force you to pay.

A complete login flow with automatic upgrades

The example below uses argon2-cffi's PasswordHasher with the OWASP baseline settings. It handles three things that are easy to get wrong: catching the right exceptions on verification, avoiding an obvious timing difference for unknown usernames, and upgrading old hashes when a user logs in successfully. It runs as-is after pip install argon2-cffi.

python
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError

# OWASP baseline: 19 MiB of memory, 2 passes, 1 lane
ph = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)

# Used when the username does not exist, so the response takes as long
DUMMY_HASH = ph.hash("not-a-real-password")

users: dict[str, str] = {}  # username -> encoded hash string


def register(username: str, password: str) -> None:
    users[username] = ph.hash(password)


def login(username: str, password: str) -> bool:
    stored = users.get(username)
    try:
        ph.verify(stored or DUMMY_HASH, password)
    except (VerificationError, InvalidHashError):
        return False
    if stored is None:
        return False
    if ph.check_needs_rehash(stored):
        users[username] = ph.hash(password)  # upgrade on successful login
    return True


# A hash created years ago with weaker settings
old = PasswordHasher(time_cost=1, memory_cost=8192, parallelism=1)
users["ada"] = old.hash("lovelace-1843")

print(login("ada", "wrong-guess"))     # False
print(login("ada", "lovelace-1843"))   # True, and the hash is upgraded
print(users["ada"].split("$")[3])      # m=19456,t=2,p=1
print(login("nobody", "anything"))     # False

A few details are worth calling out. The verify method raises VerifyMismatchError for a wrong password, which is a subclass of VerificationError, and InvalidHashError when the stored string is malformed, so catching both keeps a corrupted row from crashing the login handler. The dummy hash means a request for a nonexistent account still performs one full Argon2 computation, so response time does not reveal which usernames exist. The check_needs_rehash method compares the parameters embedded in the stored string with the hasher's current settings, and because the plaintext is available at that moment, the hash can be replaced transparently.

Pitfalls that show up in real systems

bcrypt and the 72-byte limit

Most bcrypt implementations ignore everything after the first 72 bytes of input. Historically that truncation was silent, so two long passphrases sharing a prefix would verify as identical. The Python bcrypt package changed this in version 5.0.0: passing a password longer than 72 bytes to hashpw now raises a ValueError. Remember that the limit is in bytes, not characters, so a passphrase in a non-Latin script reaches it sooner. OWASP advises enforcing a maximum length rather than pre-hashing, because naive pre-hashing can introduce NULL-byte truncation issues and enable an attack known as password shucking. If pre-hashing is truly unavoidable, the cheat sheet describes a construction that base64-encodes an HMAC-SHA384 of the password keyed with a pepper before passing it to bcrypt.

Long inputs and denial of service

Some PBKDF2 implementations process the full password on every iteration, so an extremely long input makes each hash dramatically more expensive. Setting a generous but finite maximum length, enforced before hashing, closes that door. The same check protects any algorithm from request bodies that are megabytes long.

PBKDF2 when compliance requires it

If a FIPS-validated primitive is required, Python's standard library is enough. The important parts are a per-password random salt, the published iteration count, and a constant-time comparison.

python
import hashlib
import hmac
import os

ITERATIONS = 600_000  # OWASP figure for PBKDF2-HMAC-SHA256


def hash_password(password: str) -> tuple[bytes, bytes]:
    salt = os.urandom(16)
    key = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, ITERATIONS)
    return salt, key


def check_password(password: str, salt: bytes, key: bytes) -> bool:
    candidate = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, ITERATIONS)
    return hmac.compare_digest(candidate, key)


salt, key = hash_password("correct horse battery staple")
print(check_password("correct horse battery staple", salt, key))  # True
print(check_password("Tr0ub4dor&3", salt, key))                   # False

In a real system you would also store the iteration count and algorithm name with each record, so the count can be raised later without guessing which rows were created with which setting.

Migrating away from legacy hashes

Teams that inherit a table of unsalted MD5 or SHA-1 hashes have two broad options, both described by OWASP. The cleanest is to expire those credentials and require a password reset, which is secure but disruptive. The gentler path is to wrap each existing hash immediately, for example storing Argon2id of the old MD5 value, so the weak hashes are never exposed in their raw form again. On each user's next successful login, the wrapped hash is replaced with a direct Argon2id hash of the password. Accounts that never log in stay wrapped, and OWASP suggests eventually removing them and forcing a reset.

  1. Store the algorithm and parameters with every hash, using the PHC string format or an explicit column.
  2. Wrap legacy hashes in Argon2id right away instead of waiting for logins.
  3. On successful login, verify through the wrapper, then rehash the plaintext directly.
  4. Use check_needs_rehash, or an equivalent comparison, to raise cost settings over time.
  5. Set a deadline for dormant accounts and require a reset once it passes.

A short checklist

  • Use Argon2id with at least m=19 MiB, t=2, p=1, or a stronger profile you have benchmarked.
  • Let the library generate a 16-byte random salt for every password.
  • Keep the full encoded hash string, parameters included, in one column.
  • Catch verification errors explicitly and treat malformed hashes as failed logins.
  • Rehash on successful login whenever the stored parameters are out of date.
  • Enforce a maximum password length, and the 72-byte limit if you use bcrypt.
  • Rate-limit the login endpoint so hash cost cannot be turned into a denial of service.

None of this is exotic, and the code involved fits on one screen. The difference between a breach that exposes millions of reusable passwords and one that exposes a pile of expensive, mostly uncrackable hashes usually comes down to choosing a memory-hard algorithm, setting its cost deliberately, and building in a way to raise that cost as hardware gets faster.

Share

Enjoyed this?

Get the next deep dive in your inbox. No spam — just the stories worth reading.

Subscribe to the newsletter

Comments