Password Hashing Guide: bcrypt vs argon2 vs scrypt

Start With the Decision: Four Rules

Your situation What to do
New project Use argon2id, tuning parameters backwards from a 250–500 ms hash target
Existing bcrypt (cost ≥ 12), no compliance pressure Keep it; move to argon2id at the next refactor and raise cost periodically
MD5 / SHA / plaintext / homegrown Schedule migration now, replacing hashes lazily
Constrained environment (embedded, no argon2 library) bcrypt with cost ≥ 12

There is one reason for all of it: memory hardness strips GPUs and ASICs of their parallelism advantage, and bcrypt cannot offer that. Password policy, entropy, and MFA are a separate topic, covered in the password security guide.

Hashing Is Not Encryption, and a Fast Hash Is Not a Password Hash

What a user submits at signup is plaintext. After an exfiltration — SQL injection, a leaked backup, an insider — plaintext storage exposes everyone at once, and because people reuse passwords across sites, one breach cascades into many. Encryption is not a substitute: a leaked key decrypts everything, and key management is far more complex than hashing.

Password storage has exactly two hard requirements, both against performance: one-way (the stored value cannot reveal the plaintext) and slow and expensive (every guess carries a real cost).

Why MD5 / SHA-256 Fail Here

General-purpose hashes optimise for throughput, because checksums, indexing, and dedup all want speed. A modern GPU computes billions of SHA-256 per second, enough to exhaust passwords up to eight characters in hours; MD5 and SHA-1 also carry collision problems.

So the answer is not a "stronger hash" but a deliberately slow, resource-hungry algorithm: 250 ms per verification is invisible at login and multiplies an attacker's cost by thousands.

Three Core Concepts

Salt

A salt is a random value mixed into the input before hashing. Libraries do the mixing for you, equivalent to:

hash = bcrypt(password, salt, cost)
Scenario No salt With salt
Two users both pick 123456 Identical hash, crackable in bulk Different hashes, one at a time
Rainbow table Direct hit Useless, must be rebuilt
Database leak One crack covers every matching password Each user stands alone

Three requirements: unique per user (a user ID does not count; it must come from a CSPRNG), at least 16 bytes, and not secret (store it beside the hash). bcrypt and argon2 generate and encode the salt automatically; hand-rolled salting is almost always the wrong direction.

Work Factor / Cost

The cost parameter controls iterations or resource use: bcrypt's cost means 2^cost rounds; argon2 uses time, memory, and parallelism; scrypt uses N, r, and p.

The tradeoff is direct: raising it makes enumeration costlier and logins slower; lowering it does the reverse. The baseline is 250–500 ms per hash, and you must not copy someone else's numbers — machines differ enormously. Measure on hardware matching production, then revisit as hardware improves.

Memory Hardness

bcrypt mostly burns CPU, which attackers parallelise cheaply with ASICs, FPGAs, and GPUs. Memory hardness forces every computation to occupy a large block of memory, so:

  • ordinary CPUs and GPUs have enough memory and run normally;
  • an ASIC or FPGA needs large on-chip memory to parallelise, and hardware cost jumps;
  • cheap hardware loses its parallelism advantage to memory capacity and bandwidth.

argon2 and scrypt are both memory-hard, which is the root reason they beat bcrypt.

The Three Algorithms

bcrypt

Released in 1999 and still the most widely deployed.

How it works: key derivation built on Blowfish, with cost controlling 2^cost rounds.

Parameters: cost from 4 to 31, recommended 12–14; a 16-byte salt, generated automatically.

Storage format:

$2b$12$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy
  • $2b$ — algorithm marker (2a, 2b, and 2y are all bcrypt variants; 2b is the corrected one)
  • 12 — the cost
  • the next 22 characters are the Base64-encoded salt
  • the final 31 characters are the Base64-encoded hash

Strengths: two decades of production exposure, mature libraries in every language, better ASIC resistance than the SHA family.

Weaknesses: not memory-hard, so GPU parallelism still works; a 72-byte password cap; a cost ceiling of 31 that may not last.

// Node.js
const bcrypt = require('bcrypt');

const cost = 12;
const hash = await bcrypt.hash('userPassword123', cost);
// $2b$12$...

const match = await bcrypt.compare('userPassword123', hash);
# Python
import bcrypt

hash = bcrypt.hashpw(b'userPassword123', bcrypt.gensalt(rounds=12))
match = bcrypt.checkpw(b'userPassword123', hash)

argon2

Winner of the 2015 Password Hashing Competition and today's first choice. Three variants:

  • argon2id (recommended): hybrid, balancing side-channel and GPU resistance;
  • argon2i: side-channel resistance first, suited to key derivation;
  • argon2d: GPU resistance first, but carries side-channel risk.

Parameters: memory in KB, 65536 (64 MB) or more recommended; time, 2–3; parallelism, 2–4; a salt of at least 16 bytes.

The OWASP 2024 baseline is memory=19 MiB (19456 KB), time=2, parallelism=1; raise it to memory=64MB, time=3, parallelism=4 for higher-security settings.

Storage format:

$argon2id$v=19$m=65536,t=3,p=4$c2FsdHlzYWx0...$hashbytes...

Strengths: memory-hard; three tunable dimensions; no 72-byte limit; OWASP and NIST's current first choice.

Weaknesses: relatively young, though extensively audited; incomplete library support on some older platforms.

// Node.js (argon2)
const argon2 = require('argon2');

const hash = await argon2.hash('userPassword123', {
  type: argon2.argon2id,
  memoryCost: 65536,   // 64 MB
  timeCost: 3,
  parallelism: 4,
});

const match = await argon2.verify(hash, 'userPassword123');
# Python (argon2-cffi)
from argon2 import PasswordHasher, Type

ph = PasswordHasher(
    time_cost=3,
    memory_cost=65536,
    parallelism=4,
    type=Type.ID
)
hash = ph.hash('userPassword123')
match = ph.verify(hash, 'userPassword123')

scrypt

Designed by Colin Percival in 2009, the first mainstream memory-hard KDF.

Parameters: N must be a power of two, 2^17 = 131072 recommended; r block size, 8; p parallelism, 1–4.

Strengths: memory-hard, a step above bcrypt; mature with reasonable library support.

Weaknesses: fiddlier tuning than argon2; argon2id is generally more efficient at equivalent security; no longer OWASP's first choice.

// Node.js
const scrypt = require('scrypt-js');

// scrypt's synchronous API is awkward; prefer a Promise-based wrapper
# Python (hashlib.scrypt, standard library)
import hashlib, os, base64

salt = os.urandom(16)
hash = hashlib.scrypt(
    b'userPassword123',
    salt=salt,
    n=2**17,
    r=8,
    p=1,
    dklen=32
)
# Store as: base64(salt) + '$' + base64(hash)

Comparing the Three

Dimension bcrypt scrypt argon2id
Year released 1999 2009 2015
Memory-hard No Yes Yes
GPU / ASIC resistance Medium Strong Strongest
Password length limit 72 bytes None None
Parameter dimensions 1 (cost) 3 (N/r/p) 3+ (m/t/p)
Library support Widest Broad Broad
OWASP recommendation Usable Usable Preferred
Typical time per hash ~250 ms ~300 ms ~300 ms
Side-channel resistance Yes Implementation-dependent Yes (argon2id covers both)

The four rules at the top carry the selection decision. One boundary is worth repeating: an existing bcrypt deployment at cost ≥ 12 with no compliance pressure is not an emergency — but put the migration on the refactor list before a hardware generation makes the parameter stale.

Lazy Migration: One Implementation, Two Variants

A batch rehash is impossible: the server holds hashes, not plaintext. Login is the one moment the plaintext actually arrives, which makes it the only reliable upgrade point.

Three steps, no more:

  1. Verify with the old scheme; reject on failure. Never try old and new schemes in the same verification path — that silently weakens the check.
  2. On success, re-hash with the target scheme and write it back.
  3. A failed write must not fail the login. Log it and retry; the upgrade path must not become an availability incident.

The General Implementation

def verify_and_upgrade(user, plaintext):
    scheme = detect_scheme(user.password_hash)      # inferred from the stored prefix
    if not verify(plaintext, user.password_hash, scheme):
        return False
    if scheme != TARGET_SCHEME or params_weaker(user.password_hash):
        user.password_hash = rehash(plaintext, TARGET_SCHEME)
        db.commit()
    return True

You do not need an extra column to know whether to upgrade: bcrypt's $2b$NN$ and argon2's $argon2id$v=19$m=… both encode the algorithm and parameters in the stored string, so parsing the prefix tells you the current state. Only legacy formats such as bare MD5 (32 hex characters, no prefix) need a hash_version field.

Variant A: Raising the bcrypt Cost

The cost lives inside the stored value, so parse it and compare with the target:

if bcrypt_check(plaintext, user.password_hash):
    current_cost = extract_cost(user.password_hash)   # NN from $2b$NN$
    if current_cost < TARGET_COST:
        user.password_hash = bcrypt_hash(plaintext, TARGET_COST)
        db.commit()
    return True

The trap: never edit 12 to 14 inside the string. Cost is a computation parameter; changing characters without recomputing invalidates the hash and locks the user out.

Variant B: bcrypt → argon2id

Same flow, different TARGET_SCHEME — no second implementation needed. The differences are operational:

  • keep the old value until that user has migrated; never clear it early;
  • the stored prefix changes after migration, so monitoring prefix distribution gives you progress;
  • migrate the algorithm first, tune parameters second. Changing two things at once leaves you unable to tell which broke.

Four Operational Constraints

  1. Keep old hashes until migration finishes: do not drop the old field while active users remain.
  2. Monitor progress: count users per scheme; the unmigrated count is the only honest metric.
  3. Handle dormant accounts: email them to trigger a login, or force a reset under your risk policy — otherwise they sit on the old hash indefinitely.
  4. Canary and rollback: validate the migration logic on a small cohort first, and be able to restore the old value if a write fails.

Real Pitfalls in Implementation

The 72-Byte Truncation (bcrypt)

bcrypt consumes only the first 72 bytes of a password and silently discards the rest, with no signal to the user. Long strings from a password manager, and long passphrases in CJK scripts (each character occupies several UTF-8 bytes), hit the cap easily — the nominal strength is far above the effective one.

A common workaround is to SHA-256 the password before bcrypt, but that changes both the strength model and compatibility: old hashes were computed as bcrypt(password), while the new rule verifies bcrypt(sha256(password)) and will never match. If you do it, do it from day one. argon2 and scrypt have no such limit.

Salt and Comparison: Let the Library Do It

# ❌ Never use the random module
import random
salt = str(random.randint(0, 999999))

# ✅ Cryptographically secure randomness
import os
salt = os.urandom(16)
# ❌ Plain == leaks information through timing
if user_hash == input_hash:

# ✅ Constant-time comparison
import hmac
if hmac.compare_digest(user_hash, input_hash):

bcrypt and argon2 already generate the salt with a CSPRNG inside hash(), and verify() already compares in constant time. Calling the library beats building your own salt + SHA construction on every axis.

Concurrency, Rate Limits, and Error Messages

Password hashing is CPU-bound: one login occupies roughly 250 ms, which becomes a bottleneck under load. Rate-limiting the login endpoint is not only anti-brute-force; it also stops the CPU from being exhausted. Push bulk hashing to an async queue.

Error messages must be uniform, otherwise they leak whether an account exists:

# ❌ Reveals account existence
if user not found:
    return "User does not exist"
if password wrong:
    return "Incorrect password"

# ✅ One message for both
return "Incorrect username or password"

Reproducible Results: PBKDF2's Salt and Iterations

PBKDF2 runs on the standard library, and one snippet shows what each parameter does:

import hashlib
dk = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000, dklen=32)
print(dk.hex()[:32])   # -> 0394a2ede332c9a13eb82e9b24631604

Drop the iteration count from 100000 to 1 and the output changes immediately — iterations participate in the computation, which is why they are a cost parameter and not decoration. Change the salt and the output changes again, which is exactly why rainbow tables stop working. Change one letter of the password and the output is unrecognisable (avalanche).

PBKDF2 is not the first choice, because it is not memory-hard, but it explains "salt plus cost" most plainly. In production use argon2id and tune from a 250–500 ms target; see the hash algorithm cheat sheet for strength comparisons, and the bcrypt hash tool to inspect real output.

Frequently Asked Questions

Which should I choose: bcrypt, scrypt, or argon2?

Use argon2id for new projects. It is what OWASP and NIST currently recommend: it is memory-hard, so it resists GPU and ASIC parallel cracking effectively. An existing bcrypt deployment can stay if there is no migration pressure (keep cost at 12 or above) and move over at the next refactor. In constrained environments (embedded targets, no argon2 library), bcrypt is acceptable. MD5, the SHA family, or a homegrown scheme is high-risk and must be migrated immediately.

How large should the work factor be?

Tune backwards from a single-hash time of 250–500 milliseconds rather than copying someone else's numbers — machine performance varies enormously. For argon2id, start at memory=19 MiB, time=2, parallelism=1 (the OWASP 2024 baseline) and raise it to memory=64MB, time=3, parallelism=4 for higher-security cases. For bcrypt, use cost=12~14. Whatever you pick, measure the actual time on hardware matching your production spec, and revisit it as hardware gets faster.

What is lazy migration, and why can't I just rehash everything in a batch?

A batch rehash needs the plaintext password, but the server only stores the hash — you can rehash only if you have the plaintext, and having it is exactly what you do not have. Lazy migration sidesteps that deadlock: when a user logs in they hand you the plaintext, so you verify with the old algorithm, rehash with the new one, and write it back — one login completes the upgrade. It needs no downtime and no batch job, and inactive accounts simply stay on the old hash until they return. For accounts dormant for a long time, prompt a login or force a password reset.

What problems does bcrypt's 72-byte limit cause?

bcrypt consumes only the first 72 bytes of a password and silently discards the rest. That means very long passwords — long passphrases, or long strings generated by a password manager — have their effective strength truncated, with the user completely unaware. A common workaround is to SHA-256 the password first and feed that to bcrypt, but that introduces its own design tradeoffs you should evaluate yourself. argon2 and scrypt have no such limit.

← Back to Blog