Skip to content
Blog

← All articles

Slow on Purpose, Fast by Design: Password Hashing (bcrypt, Argon2) vs. Integrity Checksums (BLAKE3, SHA-256)

Why password hashes must be slow, and checksums must be fast, with measured numbers: guesses per second for SHA-256, PBKDF2, bcrypt, and Argon2id; throughput for CRC-32C, xxHash, SHA-256, and BLAKE3; and tested code for storing passwords, checksumming files, and detecting tampering in a database.

By 18 min read

“Hash it” is advice you’ll hear for two very different jobs. For passwords, it means: store something that lets you check a password later, without storing the password. For data, it means: compute a short fingerprint that changes if a single bit of the data changes. Both use a hash function. But the qualities that make a hash good at one job make it dangerous at the other, and the most important of them is speed.

A password hash should be as slow as your users will tolerate. An integrity checksum should be as fast as your hardware allows. This article explains why, with measured numbers for both, and shows tested code for each job in a real system: storing passwords, fingerprinting files and backups, and storing both in PostgreSQL. Every code example was run before publishing.

The short answer#

Two jobs with opposite goals#

Password hashingIntegrity checksums
InputA short, guessable secretAny amount of data, often gigabytes
The threatSomeone with a copy of the hashes guessing passwords offlineCorruption, or someone changing the data
Speed goalSlow: tens to hundreds of milliseconds per hashFast: gigabytes per second
Same input, same output?No: a random salt makes every hash uniqueYes: that’s what makes comparison and deduplication work
Uses memory on purpose?Yes (Argon2, scrypt), to slow down GPUsNo
Typical choiceArgon2id, bcryptBLAKE3, SHA-256, CRC-32C

Why password hashes must be slow#

A password database gets stolen far more often than its passwords get guessed online. Once attackers have the hashes, nothing limits them except computing power: no lockout, no rate limit, no alert. They take a list of likely passwords (leaked passwords, dictionary words, common patterns), hash each one the same way you did, and look for matches. The only defense left is making each guess expensive.

Here is how many guesses one CPU core gets per second, depending on how the password was stored:

guesses.py
# guesses.py: how many guesses per second an attacker gets on one CPU core, per stored hash.
import hashlib, os, time
import bcrypt
from argon2 import PasswordHasher


def per_second(fn, seconds=2.0):
    fn()
    n, start = 0, time.perf_counter()
    while time.perf_counter() - start < seconds:
        fn()
        n += 1
    return n / (time.perf_counter() - start)


salt, guess = os.urandom(16), b"tr0ub4dor&3"
argon = PasswordHasher(memory_cost=19456, time_cost=2, parallelism=1)
bcrypt_salt = bcrypt.gensalt(12)
candidates = {
    "SHA-256 (salted)": lambda: hashlib.sha256(salt + guess).digest(),
    "PBKDF2-SHA256, 600,000 iterations": lambda: hashlib.pbkdf2_hmac("sha256", guess, salt, 600_000),
    "bcrypt, cost 12": lambda: bcrypt.hashpw(guess, bcrypt_salt),
    "Argon2id, 19 MiB, 2 passes": lambda: argon.hash(guess),
}


def readable(seconds):
    for unit, size in (("years", 365 * 86400), ("days", 86400), ("hours", 3600), ("minutes", 60)):
        if seconds >= 2 * size:
            return f"{seconds / size:,.0f} {unit}"
    return f"{seconds:,.0f} seconds"


for name, fn in candidates.items():
    rate = per_second(fn)
    print(f"{name}: {rate:,.0f} guesses/s, so a billion guesses take {readable(1e9 / rate)}")
Stored asGuesses per second, one coreA billion guesses take
SHA-256 (salted), in Pythonabout 2.8 million6 minutes
SHA-256, native code (OpenSSL)about 7.4 million2 minutes
PBKDF2-SHA256, 600,000 iterations17689 days
Argon2id, 19 MiB, 2 passes77150 days
bcrypt, cost 1265 years

Measured in Docker on an Intel Core i9-13900K. The native SHA-256 figure is OpenSSL 3.5.9’s speed test on 32-byte inputs. A billion guesses sounds like a lot, but it covers every lowercase password of up to 6 characters, or a large leaked-password list combined with common variations.

Three things make the real gap even wider than this table suggests:

  • Attackers use GPUs. A single modern graphics card computes billions of SHA-256 hashes per second. Argon2id and scrypt are memory-hard: each guess needs its own block of memory (19 MiB here), which limits how many a GPU can run at once. bcrypt’s small but constantly changing memory table also suits GPUs poorly. That’s much of why these algorithms exist.
  • Attackers have many cores. Every row scales the same way with hardware, so the ratio between rows is what matters: on equal hardware, Argon2id here costs an attacker about 36,000 times more per guess than salted SHA-256.
  • Salts multiply the work. A unique random salt per password means each guess only tests one user. Without salts, one hash of “password123” checks every account at once, and precomputed tables work.

bcrypt, scrypt, Argon2id, and PBKDF2#

AlgorithmSinceMemory-hard?OWASP minimumOur time per hash
Argon2id2015 (won the Password Hashing Competition)Yes19 MiB, 2 passes, 1 lane13 ms
scrypt2009YesN = 217, r = 8, p = 1 (128 MiB)220 ms
bcrypt1999SlightlyCost 1040 ms (cost 10), 160 ms (cost 12)
PBKDF2-HMAC-SHA2562000No600,000 iterations60 ms

Use Argon2id for new systems; it’s the current recommendation of both OWASP and RFC 9106. Use bcrypt if it’s what your framework provides; it’s still sound, apart from a length limit covered below. Use PBKDF2 when you need a FIPS-approved algorithm, since it’s the only one of the four that is. Every algorithm has settings, and all of them should be raised as hardware gets faster.

Storing passwords in a database#

Modern password libraries return a single self-describing string: the algorithm, its settings, the salt, and the hash. Store that string as is. It means you can raise the settings later, and old and new hashes keep working side by side:

passwords.py
# passwords.py: storing and checking passwords with Argon2id (pip install argon2-cffi).
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

# OWASP's minimum Argon2id settings: 19 MiB of memory, 2 passes, 1 lane.
ph = PasswordHasher(memory_cost=19456, time_cost=2, parallelism=1)

stored = ph.hash("correct horse battery staple")
print(stored[:31])  # $argon2id$v=19$m=19456,t=2,p=1$ then the salt and the hash: all you store


def login(stored_hash: str, attempt: str) -> tuple[bool, str]:
    """Returns (ok, hash to store). The hash changes only when it's upgraded."""
    try:
        ph.verify(stored_hash, attempt)  # re-hashes the attempt with the stored salt and settings
    except VerifyMismatchError:
        return False, stored_hash
    if ph.check_needs_rehash(stored_hash):  # the settings were raised since this hash was made
        stored_hash = ph.hash(attempt)  # upgrade it now, while the password is in hand
    return True, stored_hash


print(login(stored, "correct horse battery staple")[0])  # True
print(login(stored, "Correct horse battery staple")[0])  # False

# A hash made years ago with weaker settings is upgraded on the user's next login.
old = PasswordHasher(memory_cost=4096, time_cost=1, parallelism=1).hash("hunter2")
ok, upgraded = login(old, "hunter2")
print(ok, old[:30], "->", upgraded[:31])  # True $argon2id$v=19$m=4096,t=1,p=1$ -> $argon2id$v=19$m=19456,t=2,p=1$

# Every hash gets a new random salt, so equal passwords don't produce equal hashes.
print(ph.hash("hunter2") == ph.hash("hunter2"))  # False

Three habits in that code matter in production:

  • Let the library compare. verify() re-hashes the attempt with the stored salt and settings and compares in constant time. Don’t hash the attempt yourself and compare strings with ==, and never compare in SQL: equal passwords don’t have equal hashes.
  • Upgrade on login. A successful login is the only moment you have the plain password, so it’s when old hashes get re-hashed with current settings.
  • Hash in the application, not the database. PostgreSQL’s pgcrypto can run bcrypt, but then the plain password travels to the database and can end up in query logs and monitoring tools.

In the schema, a password hash is just text that the application reads back. A file checksum is the opposite: raw bytes that you index and look up, because the same content always gives the same checksum. This PostgreSQL schema stores both, with constraints that catch common mistakes:

schema.sql
-- schema.sql (PostgreSQL): where each kind of hash lives.
CREATE TABLE users (
  id            bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email         text NOT NULL UNIQUE,
  -- The whole self-describing string: algorithm, settings, salt and hash. Never indexed, never compared in SQL.
  password_hash text NOT NULL CHECK (password_hash LIKE '$argon2id$%' OR password_hash LIKE '$2b$%')
);

CREATE TABLE files (
  id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name    text NOT NULL,
  size    bigint NOT NULL,
  -- A checksum is raw bytes: 32 bytes as bytea, not 64 hex characters as text.
  blake3  bytea NOT NULL CHECK (octet_length(blake3) = 32)
);
-- Integrity hashes are meant to be looked up: the same content always gives the same hash.
CREATE UNIQUE INDEX files_blake3 ON files (blake3);

INSERT INTO users (email, password_hash)
VALUES ('ada@example.com', '$argon2id$v=19$m=19456,t=2,p=1$c29tZXNhbHQ$aGFzaA');

-- Deduplication: is this exact content already stored?
INSERT INTO files (name, size, blake3)
VALUES ('hello.txt', 5, decode('ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f', 'hex'));
SELECT name FROM files WHERE blake3 = decode('ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f', 'hex');

Our test ran it on PostgreSQL 18. The CHECK constraint rejected a bare hex digest as a password hash; the length check rejected a checksum that wasn’t 32 bytes; and the unique index caught the same content being stored twice.

Password-hashing pitfalls#

bcrypt’s 72-byte limit

bcrypt uses only the first 72 bytes of a password. That’s plenty for typed passwords, but bytes aren’t characters: in UTF-8, 40 accented characters are already 80 bytes. Older bcrypt libraries silently ignored the rest, so two long passwords that started the same way were interchangeable. Python’s bcrypt 5.0 now refuses instead:

bcrypt72.py
# bcrypt72.py: bcrypt only uses the first 72 bytes of a password (pip install bcrypt).
import bcrypt

long_password = "é" * 40  # 40 characters, but 80 bytes in UTF-8
try:
    bcrypt.hashpw(long_password.encode(), bcrypt.gensalt())
except ValueError as e:
    print(e)  # bcrypt 5.0 refuses; earlier versions silently ignored everything after byte 72
# password cannot be longer than 72 bytes, truncate manually if necessary (e.g. my_password[:72])

If you’re using bcrypt and need longer passwords, limit the password length in your sign-up form, or switch to Argon2id, which has no such limit.

Built-ins only: scrypt in Node.js

If you can’t add a dependency, Node.js has scrypt built in. One trap: OWASP’s minimum settings need 128 MiB, and Node refuses anything over 32 MiB unless you raise maxmem:

scrypt.mjs
// scrypt.mjs: password hashing with only Node.js built-ins (node:crypto's scrypt).
import { scrypt, randomBytes, timingSafeEqual } from "node:crypto";
import { promisify } from "node:util";

const scryptAsync = promisify(scrypt);
// OWASP's minimum for scrypt: N = 2^17, r = 8, p = 1. That needs 128 MiB, above Node's 32 MiB default limit.
const N = 2 ** 17, r = 8, p = 1, maxmem = 256 * 1024 * 1024;

export async function hashPassword(password) {
  const salt = randomBytes(16);
  const key = await scryptAsync(password.normalize("NFC"), salt, 32, { N, r, p, maxmem });
  return `scrypt$${N}$${r}$${p}$${salt.toString("base64")}$${key.toString("base64")}`;
}

export async function verifyPassword(stored, password) {
  const [, n, rr, pp, salt, key] = stored.split("$");
  const expected = Buffer.from(key, "base64");
  const actual = await scryptAsync(password.normalize("NFC"), Buffer.from(salt, "base64"), expected.length, {
    N: Number(n), r: Number(rr), p: Number(pp), maxmem,
  });
  return timingSafeEqual(actual, expected); // compare without leaking where the first difference is
}

const stored = await hashPassword("correct horse battery staple");
console.log(stored.slice(0, 18)); // scrypt$131072$8$1$
console.log(await verifyPassword(stored, "correct horse battery staple")); // true
console.log(await verifyPassword(stored, "correct horse battery stapler")); // false

The normalize("NFC") call matters too. An accented letter can be typed as a single Unicode character or as two (a letter plus a combining accent), and without normalization, the same password typed on different devices can produce different hashes.

Add a pepper for defense in depth

A pepper is a secret key, kept outside the database (in a secrets manager or an HSM), that is mixed into every password hash, for example by applying HMAC with the pepper before hashing. If only the database leaks, the hashes can’t be attacked at all without it. It’s optional, and it adds key management, but it costs nothing per login.

The server pays the cost too#

Every slow hash an attacker computes, your server computes too, on every login. That’s the price of the protection, and it needs planning:

  • Pick settings by measuring. Aim for a hash time your login can afford, commonly somewhere between 50 and 500 milliseconds on your production hardware, and never below OWASP’s minimums.
  • Memory adds up. Each Argon2id hash with OWASP’s settings requires 19 MiB of memory while running. Fifty logins at the same moment need almost 1 GB.
  • Slow hashing is a denial-of-service target. Rate-limit login attempts per account and per address, limit concurrent hashing, and cap password length (a few hundred characters is plenty).
  • Don’t reveal whether an account exists. If unknown email addresses return instantly while real ones take 100 ms, the timing tells an attacker which accounts are real. Hash a dummy password for unknown users too.

Why checksums must be fast#

Integrity checksums are the opposite case. The input is usually large and not secret: a backup, a downloaded file, a database page. Nobody is guessing it. What matters is that the checksum changes when the data does, and that it costs as little as possible, because it’s computed on every write, every read, or every file in a backup set.

Here is the throughput of common choices on a 1 GiB input, on the same machine:

FunctionKindSpeed
BLAKE3, all threadsCryptographic40 GiB/s
CRC-32C (hardware instruction)Error-detecting code20 GiB/s
xxHash3, 64-bitNon-cryptographic hash16 GiB/s
CRC-32 (zlib)Error-detecting code6.7 GiB/s
BLAKE3, 1 threadCryptographic4.9 GiB/s
SHA-1 (hardware-accelerated)Broken for collisions2.7 GiB/s
SHA-256 (hardware-accelerated)Cryptographic2.4 GiB/s
BLAKE2bCryptographic1.2 GiB/s
MD5Broken for collisions1.1 GiB/s
SHA-512Cryptographic1.1 GiB/s
SHA3-256Cryptographic0.7 GiB/s

Python 3.14’s hashlib (OpenSSL), plus the blake3, xxhash, and google-crc32c packages. For how BLAKE3 uses threads and SIMD lanes to get there, see our BLAKE3 deep dive.

For comparison: at bcrypt’s cost 12, the password-hash side of this article, one hash takes 160 ms. Hashing a 1 GiB backup “slowly” wouldn’t make it safer, just slower.

CRC, xxHash, or a cryptographic hash?#

The right checksum depends on what you’re protecting against:

  • Random corruption (a bad disk sector, a flipped bit in memory or on the network): an error-detecting code like CRC-32C, or a fast non-cryptographic hash like xxHash, is enough and fastest. This is what storage systems use per block. Btrfs uses CRC-32C by default, and PostgreSQL keeps a 16-bit checksum on every 8 KB data page, which PostgreSQL 18 enables by default (our test confirmed it in a new cluster).
  • Content identity at scale (deduplication, content-addressed storage, build caches): use a cryptographic hash. With billions of objects, or any chance that someone crafts inputs, a 32-bit CRC or 64-bit xxHash will produce collisions; a 256-bit cryptographic hash won’t. BLAKE3 is the fastest choice, and SHA-256 the most widely supported.
  • An adversary who could craft data: only a cryptographic hash, and not MD5 or SHA-1. Practical collisions exist for both, meaning an attacker can create two different files with the same hash.

Checksums for files and backups#

For files, the practical concern is memory: read the file in chunks, or memory-map it, so a 100 GB backup doesn’t need 100 GB of RAM. Record the checksum when the file is written, and compare it when it’s read back:

checksum.py
# checksum.py: fingerprint a large file without reading it all into memory (pip install blake3).
import hashlib, os
import blake3


def sha256_file(path: str, chunk: int = 1 << 20) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        while block := f.read(chunk):  # 1 MiB at a time: memory use stays flat for any file size
            h.update(block)
    return h.hexdigest()


def blake3_file(path: str) -> str:
    # Memory-maps the file and hashes it with all CPU threads (BLAKE3's tree makes that possible).
    return blake3.blake3(max_threads=blake3.blake3.AUTO).update_mmap(path).hexdigest()


with open("backup.bin", "wb") as f:
    f.write(os.urandom(64 << 20))  # a 64 MiB stand-in for a backup file

recorded = blake3_file("backup.bin")  # store this when the backup is made...
print(blake3_file("backup.bin") == recorded)  # ...and compare when restoring: True

with open("backup.bin", "r+b") as f:  # one flipped bit, anywhere
    f.seek(12_345_678)
    byte = f.read(1)
    f.seek(12_345_678)
    f.write(bytes([byte[0] ^ 1]))
print(blake3_file("backup.bin") == recorded)  # False
print(len(sha256_file("backup.bin")))  # 64 hex characters, from 1 MiB reads

One flipped bit in 64 MiB changed the checksum, as it should: any change, anywhere, produces an unrelated hash. Stored in the files table above, the same checksum doubles as a deduplication key.

A checksum doesn’t stop tampering#

A checksum stored alongside the data proves the data hasn’t been accidentally altered. It proves nothing about deliberate changes: anyone who can change the data can recompute the checksum and store that too. For tamper evidence, the check needs a secret the attacker doesn’t have:

tamper.py
# tamper.py: a checksum stored next to the data only catches accidents. Add a key to catch people.
import hashlib, hmac, secrets

row = b'{"account": 42, "balance": 100}'
checksum = hashlib.sha256(row).hexdigest()

# Someone with write access changes the row and stores a fresh checksum for it. Nothing looks wrong.
forged = b'{"account": 42, "balance": 1000000}'
checksum = hashlib.sha256(forged).hexdigest()
print(hashlib.sha256(forged).hexdigest() == checksum)  # True: the forged row passes the check

# With a key the attacker doesn't have (kept in a secrets manager, not in the database),
# they can't produce a matching tag for their change.
key = secrets.token_bytes(32)
tag = hmac.new(key, row, hashlib.sha256).digest()


def verify(data: bytes, stored_tag: bytes) -> bool:
    expected = hmac.new(key, data, hashlib.sha256).digest()
    return hmac.compare_digest(expected, stored_tag)  # constant-time comparison


print(verify(row, tag))  # True
print(verify(forged, tag))  # False

HMAC-SHA256 is the standard choice; BLAKE3’s keyed mode does the same job faster. If the data must be verifiable by people who shouldn’t be able to create valid tags (for example, signed releases or audit logs read by third parties), use a digital signature instead, such as Ed25519. And compare tags with a constant-time function like hmac.compare_digest, not ==.

Mixing them up#

  • A fast hash for passwords. SHA-256, SHA-512, MD5, or BLAKE3, with or without a salt, and even applied a few thousand times. In the 2012 LinkedIn breach, passwords were stored as unsalted SHA-1, and attackers recovered most of them.
  • A password hash for data. bcrypt would take 160 ms per call, produce a different result each time due to its salt, and accept at most 72 bytes of input.
  • MD5 or SHA-1 where someone might cheat. They’re fine for spotting accidental corruption, but not when an attacker can choose the data.
  • A plain checksum as tamper protection. Without a key, it only detects accidents.
  • Comparing secrets with ==. Use the library’s verify for passwords, and a constant-time comparison for tags.

FAQ#

Isn’t salted SHA-256 good enough for passwords?

No. The salt prevents a single guess from checking every account at once, but each guess still takes a fraction of a microsecond. In our measurements, salted SHA-256 allowed about 36,000 times as many guesses per second as Argon2id with OWASP’s minimum settings.

How slow is slow enough?

At least OWASP’s minimums, and then as slow as your login can comfortably afford. Measure on your production hardware, and revisit the settings every year or two.

Can I use BLAKE3 or SHA-256 to derive an encryption key from a password?

Not directly; it has the same weakness as storing a fast hash. Use a password-based key derivation function (Argon2id, scrypt, or PBKDF2) with a salt. Our symmetric encryption guide shows how.

Is CRC-32 a hash?

It’s an error-detecting code: excellent at catching the kinds of errors hardware makes, and trivial to forge on purpose. Use it for corruption checks, never for security. Our hash generator computes CRC-32 alongside SHA-256, BLAKE3, and others so that you can compare them on your own data.

Try it in your browser

  • Hash Generator: compute SHA-256, BLAKE3, CRC-32 and other checksums for text or files, and generate HMACs with a key, in your browser.