Backend

How to Store Passwords Today: Argon2 vs bcrypt, and What Not to Do

Use Argon2id for new projects and keep bcrypt only where you're stuck with it. Settings, working Python code, an upgrade path for old hashes and the mistakes to avoid.

Ankit Singh
Software Engineer
·
8 min read
·
AI-assisted

AI tooling disclosure

Generative AI materially contributed to this article.

Human review confirmed by the author.

How to Store Passwords Today: Argon2 vs bcrypt, and What Not to Do

Plan for the day someone gets a copy of your database. A forgotten backup or one SQL injection bug is all it takes.

You can't control whether that happens. You can control what they find inside. If it's passwords, every account is gone. If it's properly hashed passwords, they're stuck with a slow and expensive guessing game.

This post covers how to set that up: which algorithm to pick, which settings to use, how to upgrade old hashes and what not to do. The code is Python, but the rules apply to any language.

Sources: the settings come from OWASP's Password Storage Cheat Sheet and NIST SP 800-63B-4. Recommended numbers change over time, so check both again before you ship.


The short answer

Never store the password itself. Store the output of a slow, salted hash function that was built for passwords, and let a library do the work.

flowchart TD
    A["Choosing an algorithm"] --> B{"FIPS-140 compliance required?"}
    B -- Yes --> C["PBKDF2-HMAC-SHA-256"]
    B -- No --> D{"Argon2id library available?"}
    D -- Yes --> E["Argon2id"]
    D -- No --> F{"scrypt available?"}
    F -- Yes --> G["scrypt"]
    F -- No --> H["bcrypt"]

These are OWASP's minimum settings for each one:

Algorithm

Minimum settings

Argon2id

19 MiB memory, 2 iterations, 1 thread

scrypt

N = 2^17, r = 8, p = 1

bcrypt

Cost 10 or higher, passwords up to 72 bytes

PBKDF2-HMAC-SHA-256

600,000 iterations


What not to do

Mistake

Why it fails

Storing plain text

One leak exposes every account, and people reuse passwords on other sites

Encrypting passwords

Encryption can be reversed. The key has to live where your app can reach it, so a thief who gets both gets everything. Hash instead

Plain MD5, SHA-1 or SHA-256

They were built to be fast, which lets an attacker try huge numbers of guesses per second

No salt, or one shared salt

Identical passwords give identical hashes, and precomputed lookup tables work

Inventing your own scheme

Something like sha256(sha256(pw + salt)) repeated 1,000 times is easy to get wrong. Use a proven algorithm

Capping password length at 16

Long passphrases are good. Don't limit them (bcrypt's 72-byte limit is the one exception, covered below)

Comparing hashes with ==

Use the library's verify function, or hmac.compare_digest, so timing can't leak information

Heads up: older FastAPI tutorials use passlib. It has been inactive for years, and the author of its replacement, pwdlib, says it stops working from Python 3.13. For new code, use argon2-cffi directly or pwdlib.


Why slow is the whole point

A good password hash is deliberately expensive. Each guess costs the attacker time and memory, so cracking millions of hashes becomes impractical.

Run this on your own machine:

import hashlib
import time

start = time.perf_counter()
for _ in range(100_000):
    hashlib.sha256(b"hunter2").digest()

rate = 100_000 / (time.perf_counter() - start)
print(f"SHA-256: {rate:,.0f} guesses per second on one CPU core")

You'll see millions of guesses per second from a single core. A correctly configured password hash allows a handful. That gap is what protects your users.

The salt is a random value that's unique to each password. It means two users with the same password get different hashes, so nobody can crack them all in one pass or use precomputed tables. Most password hashing libraries generate the salt for you and store it inside the hash string, so you rarely handle it yourself. (The standard-library recipe further down is the exception.)


Argon2id: the default choice

Argon2 won the Password Hashing Competition in 2015. It's memory-hard: every guess needs a chunk of RAM, which makes it expensive to attack with GPUs. Use the id variant, which OWASP picks for its balance against both GPU and side-channel attacks.

In Python, install argon2-cffi and you're nearly done:

from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

ph = PasswordHasher()  # Argon2id with sensible defaults

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

try:
    ph.verify(stored_hash, "correct horse battery staple")  # returns True
except VerifyMismatchError:
    print("Wrong password")

The defaults are 64 MiB of memory, 3 iterations and 4 lanes. That's the second option recommended in RFC 9106, and it's above OWASP's minimum.

The string that comes back holds the algorithm, the settings and the salt. Store it as-is in one column (255 characters is plenty). That's what makes upgrades easy later.

Picking your own settings

OWASP lists several combinations that give equal protection. The only difference is how much CPU and RAM they use:

Memory

Iterations

Parallelism

46 MiB

1

1

19 MiB

2

1

12 MiB

3

1

9 MiB

4

1

7 MiB

5

1

In argon2-cffi, you pass them like this (memory is in KiB):

ph = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)  # OWASP minimum

Heads up: memory is paid for on every concurrent login. A hundred people logging in at once at 19 MiB each is about 1.9 GB. Settings that are too heavy can also help someone knock over your login endpoint, so rate-limit it. OWASP's rule of thumb is that one hash should take under a second on your own server, so benchmark before you decide.


bcrypt: fine, if it's what you have

Here's how the two compare:

Argon2id

bcrypt

OWASP's position

First choice

Legacy systems only

Settings you can tune

Memory, iterations and parallelism

One cost factor

Memory use

Adjustable (OWASP minimum is 19 MiB)

Fixed and small

Password length

No 72-byte limit

72 bytes at most

Python library defaults

64 MiB, 3 iterations, 4 lanes

Cost 12

For a new project, pick Argon2id. If you already run bcrypt, keep it and upgrade users as they log in.

bcrypt isn't broken, and plenty of systems rely on it. But OWASP says to use it only in legacy systems where Argon2 and scrypt aren't available. The Python bcrypt library's own README says you should really use Argon2id or scrypt.

If you're on bcrypt, three things matter:

  • Cost 10 or higher. The Python library defaults to 12.

  • The 72-byte limit. bcrypt only reads the first 72 bytes of a password. Older versions of the Python library silently cut the rest off. Version 5.0 raises a ValueError instead.

  • Don't pre-hash with plain SHA-256 to get around the limit. OWASP warns it can be dangerous, because of null bytes in the hash output and an attack called password shucking. Cap the length at 72 bytes, or move to Argon2id, which has no such limit.


Upgrading old hashes when users log in

You can't convert a hash into a different hash, because you don't have the password. But you do have it for a moment during login. That's your chance to upgrade:

import bcrypt
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

ph = PasswordHasher()

def check_login(user, password: str) -> bool:
    stored = user.password_hash

    if stored.startswith("$2"):  # legacy bcrypt: $2a$, $2b$ or $2y$
        # Old bcrypt versions silently cut passwords at 72 bytes. Match that here.
        raw = password.encode("utf-8")[:72]
        if not bcrypt.checkpw(raw, stored.encode("ascii")):
            return False
        user.password_hash = ph.hash(password)  # upgrade to Argon2id
        user.save()
        return True

    try:
        ph.verify(stored, password)
    except VerifyMismatchError:
        return False

    if ph.check_needs_rehash(stored):  # settings changed since this hash was made
        user.password_hash = ph.hash(password)
        user.save()
    return True

check_needs_rehash is how you raise your settings later. Change the settings you pass to PasswordHasher(...), and every user's hash upgrades the next time they log in. (user.save() stands in for your own database code.)

Some users won't come back for a long time, so their old hashes stay put. OWASP suggests two options for those:

  • Delete the hashes of long-inactive users and make them reset their password.

  • Wrap the old hash in a new one, for example argon2(md5(password)), so everyone is protected right away. Replace it with a direct hash at next login.


No extra packages? Use the standard library

Python's hashlib has scrypt built in. This uses OWASP's minimum settings:

import hashlib
import hmac
import os

N, R, P = 2**17, 8, 1
MAXMEM = 256 * 1024 * 1024  # the default limit is too low for these settings

def hash_password(password: str) -> str:
    salt = os.urandom(16)
    key = hashlib.scrypt(
        password.encode("utf-8"), salt=salt, n=N, r=R, p=P, maxmem=MAXMEM, dklen=32
    )
    return f"scrypt${N}${R}${P}${salt.hex()}${key.hex()}"

def verify_password(password: str, stored: str) -> bool:
    _, n, r, p, salt_hex, key_hex = stored.split("$")
    key = hashlib.scrypt(
        password.encode("utf-8"),
        salt=bytes.fromhex(salt_hex),
        n=int(n), r=int(r), p=int(p),
        maxmem=MAXMEM, dklen=32,
    )
    return hmac.compare_digest(key, bytes.fromhex(key_hex))

Without maxmem you get ValueError: memory limit exceeded. Those settings use 128 MiB of RAM per hash, so watch concurrent logins. OWASP also lists lighter combinations, such as N = 2^16 with p = 2 (64 MiB). Because you wrote the storage format, you also own the upgrade logic. A library does that for you, so prefer one when you can.

If you need FIPS-140 compliance, PBKDF2 is the algorithm to use. Python's standard library has it:

dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 600_000)

Store the salt and the iteration count next to the result so you can raise the count later. The FIPS validation belongs to the crypto module underneath, meaning your OpenSSL build, so check that too.


Pepper: an optional extra layer

A pepper is a secret value shared by all passwords and kept outside the database, in a secrets vault or an HSM. If an attacker only gets the database, a pepper stops them cracking anything at all.

It's defense in depth, not a replacement for a good hash. And rotating a pepper means resetting every user's password, so decide up front whether you want that trade-off.


Password rules that match current guidance

NIST SP 800-63B-4, published in July 2025, changed what a good password policy looks like:

  • Length over complexity. At least 15 characters when the password is the only factor, and at least 8 when it's paired with MFA.

  • Allow long passwords. Accept at least 64 characters, including spaces and Unicode.

  • No composition rules. Don't force a symbol or a capital letter.

  • No scheduled expiry. Require a change only if you have evidence of compromise.

  • Check against a blocklist of common and breached passwords.

  • No security questions.

Pair that with rate limiting on login, and offer MFA or passkeys. Your hashing library also has to handle every Unicode character and even NUL bytes, so don't strip or limit input before hashing.


Other languages

Language

Reach for

Python

argon2-cffi, or pwdlib for one wrapper around Argon2 and bcrypt (FastAPI Users uses it)

Node.js

A wrapper such as the argon2 package. Node 24.7+ also has crypto.argon2(), but it returns raw bytes, so you store the salt and settings and compare in constant time yourself

PHP

password_hash($password, PASSWORD_ARGON2ID), as long as your PHP was compiled with Argon2 support

Go

golang.org/x/crypto/argon2. It returns raw bytes too, so the same extra work applies

Java

Spring Security's Argon2PasswordEncoder, which needs Bouncy Castle on the classpath


Checklist

  • Hash with Argon2id, or scrypt, bcrypt or PBKDF2 if you have a reason.

  • Use a maintained library, and let it generate the salt.

  • Store the full hash string, so settings travel with it.

  • Check needs rehash on every login and upgrade quietly.

  • Cap bcrypt input at 72 bytes, or avoid bcrypt.

  • Follow NIST's rules: long, no complexity theatre, block breached passwords.

  • Rate-limit login, and never log passwords.

If you're starting a new project today, install argon2-cffi, use the defaults and move on. If you inherited an old system, add the upgrade-on-login code first. It fixes the problem without bothering a single user.

Comments(0)

Join the discussion by logging into your account.

No comments yet. Be the first to comment!

Ankit Singh
Ankit Singh

Software Engineer

Passionate developer sharing knowledge about modern web technologies and best practices.

Subscribe to Ankit Singh's Newsletter

Direct email dispatches when new stories are published. Zero algorithms.