When a database leaks, the question that decides how bad the day is gets asked within hours: how were the passwords stored? If they sit in plaintext, or behind an unsalted fast hash, every account is compromised before the incident report is written, and because people reuse passwords, so are accounts on other services. If they were hashed with a properly tuned, memory-hard function and a unique salt, the attacker faces a slow, expensive guessing job that only succeeds against weak passwords.

Password storage is one of the few security topics with a clear, stable, well-understood answer. This article lays it out: why general-purpose hashes fail, how to choose between Argon2id, bcrypt and scrypt, how salts and peppers work, how to tune cost, and how to migrate an existing user base without forcing a reset.

What Goes Wrong With Naive Storage

Four storage schemes appear again and again in breach post-mortems:

  • Plaintext. One read-only vulnerability exposes every credential. Support staff and backups can see them too.
  • Reversible encryption. The key must live next to the application, so an attacker who reaches the database through the application usually reaches the key. There is no legitimate reason for a server to be able to recover a user’s password.
  • Fast hashes such as MD5, SHA-1 or SHA-256, unsalted. These are designed to be quick. A modern GPU can test enormous numbers of candidates per second, and precomputed tables turn common passwords into instant lookups.
  • Fast hashes with a salt. Better, because tables stop working and identical passwords no longer produce identical hashes, but the per-guess cost is still tiny.

The defender’s goal is to make each guess expensive in time and memory, so that the attacker’s hardware advantage shrinks. How attackers use dedicated cracking tools against these formats is explained in Password Cracking With Hashcat; this article is the defensive counterpart.

The Right Primitive: A Password Hashing Function

A password hashing function has three properties that a general hash lacks:

  1. A built-in salt, so each hash is unique even for identical passwords.
  2. A tunable work factor, so you can raise the cost as hardware improves.
  3. Memory hardness (in the better designs), so that parallel hardware such as GPUs and custom chips gains less.

The mainstream choices are:

FunctionMemory-hardNotes
Argon2idYesWinner of the Password Hashing Competition; the usual first choice for new systems
scryptYesSolid, but harder to tune because its parameters interact
bcryptNo (small fixed memory)Old, battle-tested, available everywhere
PBKDF2NoAcceptable where compliance mandates it (for example FIPS), needs a very high iteration count

Argon2 comes in variants. Argon2id blends data-dependent and data-independent memory access and is the recommended one for password hashing. Use argon2d or argon2i only if you have a specific reason.

Argon2id in Practice

Argon2id has three cost parameters: memory (m), iterations (t) and parallelism (p). OWASP’s guidance lists several equivalent minimum configurations, one of them being 19 MiB of memory, 2 iterations and 1 degree of parallelism, with higher-memory, lower-iteration options as alternatives. Treat published values as a floor and tune upward for your hardware.

Here are minimal examples with maintained libraries.

# Python: argon2-cffi
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

ph = PasswordHasher(time_cost=3, memory_cost=64 * 1024, parallelism=1)  # 64 MiB

hash_ = ph.hash("correct horse battery staple")
# $argon2id$v=19$m=65536,t=3,p=1$<salt>$<hash>

try:
    ph.verify(hash_, "correct horse battery staple")
    if ph.check_needs_rehash(hash_):
        hash_ = ph.hash("correct horse battery staple")  # store the new hash
except VerifyMismatchError:
    pass  # wrong password
// Node.js: argon2 package
import argon2 from "argon2";

const hash = await argon2.hash(password, {
  type: argon2.argon2id,
  memoryCost: 64 * 1024, // KiB
  timeCost: 3,
  parallelism: 1,
});

const ok = await argon2.verify(hash, candidate);
<?php
// PHP: built-in password API
$hash = password_hash($password, PASSWORD_ARGON2ID, [
    'memory_cost' => 65536, // KiB
    'time_cost'   => 3,
    'threads'     => 1,
]);

if (password_verify($candidate, $hash)) {
    if (password_needs_rehash($hash, PASSWORD_ARGON2ID, ['memory_cost' => 65536, 'time_cost' => 3, 'threads' => 1])) {
        // rehash and store
    }
}

Notice what the code does not do: it does not generate salts by hand, concatenate strings, or compare hashes with ==. The library encodes algorithm, parameters, salt and hash in one self-describing string, and its verify function does a constant-time comparison. Never write your own scheme on top of a raw hash.

Choosing the cost

There is no universal number. A practical method:

  1. Decide how much latency a login can afford, commonly in the range of a few hundred milliseconds on your production hardware.
  2. Decide how much memory you can spare per concurrent login. Memory-hard hashing means 100 simultaneous logins at 64 MiB need roughly 6.4 GiB.
  3. Benchmark on the real servers and pick the highest cost that fits both budgets.
  4. Revisit the setting periodically, and rely on rehash-on-login (below) to apply new parameters.

Memory hardness also creates a denial-of-service concern: an attacker who sends many login requests can force you to spend memory and CPU on each. Pair strong hashing with rate limiting on the login endpoint so that the cost stays proportional to legitimate traffic.

bcrypt: Still Fine, With Two Caveats

bcrypt remains a respectable choice, especially in ecosystems where Argon2 support is thin. Its work factor is a single number: each increment doubles the cost. A cost of 10 is commonly cited as a minimum, with 12 or more common today on server hardware; benchmark to find the value that fits your latency budget.

import bcrypt

hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12))
ok = bcrypt.checkpw(candidate.encode(), hashed)

The two caveats are well-known:

  • Input length limit. bcrypt only uses the first 72 bytes of the input. Some implementations silently truncate; others reject longer input. Long passphrases are therefore partly ignored, and multi-byte characters use up the budget faster.
  • NUL bytes. Some implementations stop at a zero byte.

A frequently suggested workaround is to pre-hash the password with SHA-256 and feed the result to bcrypt. If you do that, encode the digest with base64 (raw digest bytes can contain NUL bytes), and be aware of the “password shucking” problem: if the same pre-hash is used elsewhere, the intermediate value becomes an equivalent password. Using HMAC with a secret key as the pre-hash step avoids that, and brings us to peppers. If you have the choice, Argon2id sidesteps the length issue entirely.

Salts: What They Do and Do Not Do

A salt is a random value stored alongside the hash, unique per password. It exists to ensure that:

  • identical passwords produce different hashes, so one cracked hash does not reveal others;
  • precomputed tables and rainbow tables are useless;
  • the attacker must attack each hash separately.

A salt is not secret. It sits in the same row as the hash. It does not make a weak password strong, and it does not slow down a targeted attack on a single account. Password hashing libraries generate a cryptographically random salt of adequate length for you. Never use the username, email or a constant as the salt.

Peppers: An Extra Layer Outside the Database

A pepper is a secret value mixed into the hashing process that is not stored in the database. If an attacker obtains only the database, for example through SQL injection or a stolen backup, the pepper protects the hashes because they cannot be tested offline without it.

A common, defensible construction is to compute an HMAC of the password with the pepper and hash the result:

import hmac, hashlib, base64, os
from argon2 import PasswordHasher

PEPPER = os.environ["PASSWORD_PEPPER"].encode()   # from a secrets manager, not the DB
ph = PasswordHasher()

def prehash(password: str) -> str:
    mac = hmac.new(PEPPER, password.encode(), hashlib.sha256).digest()
    return base64.b64encode(mac).decode()

def store(password: str) -> str:
    return ph.hash(prehash(password))

def check(stored: str, candidate: str) -> bool:
    try:
        return ph.verify(stored, prehash(candidate))
    except Exception:
        return False

Peppers have real costs that you should weigh honestly:

  • Rotation is hard. Changing the pepper invalidates existing hashes unless you version it. Store a pepper identifier next to each hash (for example a prefix such as p2$) and keep old peppers available while users migrate on login.
  • Loss is catastrophic. If the pepper is lost, nobody can log in. Back it up in a secrets manager with strict access control.
  • It only helps against database-only compromise. An attacker who gets code execution on the application server usually gets the pepper as well, and then it adds little.
  • Complexity. More moving parts mean more places for a bug.

A pepper is a reasonable defense-in-depth measure for higher-value systems with a mature secrets process. It is not a replacement for a good hash, and not something to add before the basics are right. A hardware security module or a key management service that performs the HMAC operation without exposing the key is the stronger version of the same idea.

Rehash on Login and Migrating Legacy Hashes

You do not need a forced password reset to upgrade storage. Users type their password at every login, which is the only moment you can recompute a hash.

Upgrading parameters or algorithm. On successful verification, check whether the stored hash uses outdated parameters (check_needs_rehash, password_needs_rehash) and, if so, store a fresh hash.

Migrating from a weak legacy hash. Two approaches combine well:

  1. Wrap the existing hashes immediately. Take each stored legacy hash, such as an unsalted SHA-1 digest, and run it through Argon2id, storing a marker for the scheme: argon2id(sha1(password)). The database is protected right away, even for dormant users who never log in again. On verification, compute the legacy hash first, then the Argon2id verification.
  2. Replace on next login. After a successful login with the wrapped scheme, hash the plain password directly with Argon2id and remove the wrapper marker.
def verify_and_upgrade(user, candidate):
    if user.scheme == "legacy_sha1_wrapped":
        inner = hashlib.sha1(candidate.encode()).hexdigest()
        ok = ph.verify(user.hash, inner)   # wrapped hash
        if ok:
            user.hash = ph.hash(candidate)
            user.scheme = "argon2id"
            user.save()
        return ok
    ...

Keep the scheme marker in its own column, so queries such as “how many users still use the wrapped scheme?” are easy, and so you can force a reset for accounts that never migrate within a defined period.

Storage is one layer of a larger authentication design.

  • Do not truncate or restrict passwords arbitrarily. Allow long passphrases, accept spaces and any Unicode character, and normalize Unicode consistently (NFKC is the common choice) before hashing. Reject only what you must.
  • Check against known-breached passwords at registration and reset rather than imposing composition rules. Complexity rules produce predictable patterns; blocklists reduce actual risk.
  • Use constant-time comparisons and return identical responses for “unknown user” and “wrong password”.
  • Rate-limit and monitor login attempts, because hashing cost protects stored hashes, not the live endpoint.
  • Prefer to remove passwords where you can. Passkeys vs Passwords covers phishing-resistant alternatives that leave nothing crackable in your database.
  • Never log passwords, including in error messages, request dumps and debugging output.
  • Protect password reset flows: single-use, short-lived, high-entropy tokens stored hashed.

Common Mistakes

  • Using a fast general-purpose hash (MD5, SHA-1, SHA-256) alone, with or without salt.
  • Inventing a scheme such as sha256(salt + password) or hashing in a loop manually.
  • Setting Argon2 or bcrypt costs from a tutorial and never revisiting them.
  • Keeping the pepper in the same database or repository as the hashes.
  • Truncating passwords silently at 72 bytes with bcrypt.
  • Comparing hash strings with a normal equality operator.
  • Doing the hashing on the client only, so that the hash itself becomes the password.
  • Ignoring the memory cost of Argon2 under concurrent load.

Key Takeaways

  • Never store plaintext, reversibly encrypted or fast-hashed passwords; use a dedicated password hashing function.
  • Argon2id is the default choice for new systems; bcrypt remains acceptable when you respect its 72-byte limit; PBKDF2 is for compliance-driven cases with a high iteration count.
  • Use the library’s built-in salting and verification, and tune cost on your real hardware for both latency and memory.
  • A pepper kept outside the database adds defense in depth against database-only theft, but needs versioning, backup and careful secret management.
  • Rehash on login to raise parameters, and wrap legacy hashes immediately instead of waiting for users to return.
  • Combine strong storage with breached-password checks, rate limiting and, where possible, passkeys.