Skip to main content

Security and hardening · Intermediate · 22 min

Hash and verify passwords with Argon2id

By Padding · Updated 18 Nov 2026
Python 3.15.2 · argon2-cffi 25.1.0 · bcrypt 5.0.0 · Node.js 26 · @node-rs/argon2 2.2.2

You will have a small Python password module that hashes with Argon2id at parameters tuned on your own machine, adds a pepper kept outside the database, upgrades old Argon2 and bcrypt hashes when users sign in, and produces hashes that Node.js can verify too.

On this page

A password database will leak one day: a stolen backup, a misconfigured bucket, an injection bug. What you store decides what happens next. If you stored a fast hash such as SHA-256 or MD5, an attacker can try guesses as fast as the hardware allows and recover most real passwords within days. If you stored a slow, memory-hard hash with a per-user salt, each guess costs real time and real memory. Only passwords near the top of attacker wordlists still fall quickly, and strong, unique ones stay out of practical reach.

Argon2id is the hash the OWASP Password Storage Cheat Sheet recommends first. In this tutorial you build a small password module in Python with argon2-cffi 25.1, measure the difference against SHA-256 yourself, pick parameters for your own machine, add a pepper, and handle the part most guides skip: users whose hashes were made years ago with weaker settings or with bcrypt. A final step verifies the same hashes from Node.js with @node-rs/argon2.

Everything runs in a throwaway folder, ~/argon2-demo, with a SQLite file standing in for your users table.

Step 1 · Create the project and install the libraries

Make the demo folder, a virtual environment, and install exact versions of argon2-cffi and bcrypt. You need bcrypt only to read old hashes during a migration; new hashes are all Argon2id.

Bash
mkdir -p ~/argon2-demo
cd ~/argon2-demo
python3 -m venv .venv
.venv/bin/pip install --quiet argon2-cffi==25.1.0 bcrypt==5.0.0

argon2-cffi wraps the reference C implementation of Argon2, and both packages ship prebuilt wheels for Linux, macOS and Windows, so no compiler is needed.

Check it worked

Bash
.venv/bin/python -c "from importlib.metadata import version; print(version('argon2-cffi'), version('bcrypt'))"

The command prints 25.1.0 5.0.0.

Step 2 · See why a fast hash is the wrong tool

A general-purpose hash is built to be fast: that is what you want for checking a download, and exactly what an attacker wants when guessing passwords. Argon2 is built to be slow on purpose, and to be memory-hard: each hash fills a block of memory (19 MiB in the settings below) and reads it back in an order that depends on earlier results, so every guess needs its own copy of that memory. Memory size and bandwidth then cap how many guesses a graphics card can run at once, far fewer than its thousands of cores would allow. The 19 MiB floor narrows the attacker's lead rather than removing it, which is why the tuning step later raises the memory cost as far as your servers allow.

Count how many guesses per second each approach allows on your machine:

Bash
cat > speed.py <<'PY'
import hashlib
import os
import time

from argon2 import PasswordHasher

password = "plum-tree-river-7"
salt = os.urandom(16)


def guesses_in_one_second(guess):
    count = 0
    end = time.perf_counter() + 1.0
    while time.perf_counter() < end:
        guess()
        count += 1
    return count


fast = guesses_in_one_second(lambda: hashlib.sha256(salt + password.encode()).digest())

hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
stored = hasher.hash(password)
slow = guesses_in_one_second(lambda: hasher.verify(stored, password))

print(f"SHA-256 with a salt: {fast:>10,} guesses per second")
print(f"Argon2id, 19 MiB:    {slow:>10,} guesses per second")
print(f"ratio: {fast // max(slow, 1)}")
PY
.venv/bin/python speed.py

A salt alone does not help much here. It stops precomputed tables and forces the attacker to crack each user separately, but each guess still costs only one fast hash.

Check it worked

SHA-256 manages somewhere around a million guesses per second from a single Python thread. Argon2id manages a few dozen. The ratio line is in the tens of thousands on most machines. An attacker with optimised code and graphics cards does far better against SHA-256 than this loop; against Argon2id, the memory each guess needs limits them.

Step 3 · Hash and verify a password

Create a hasher with the OWASP minimum for Argon2id, 19 MiB of memory (m=19456 KiB), two passes (t=2) and one lane (p=1), then hash and verify a password:

Bash
cat > first_hash.py <<'PY'
from argon2 import PasswordHasher, extract_parameters
from argon2.exceptions import VerifyMismatchError

hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)

first = hasher.hash("plum-tree-river-7")
second = hasher.hash("plum-tree-river-7")
print(first)
print(second)
print("same password, different hashes:", first != second)

print("right password:", hasher.verify(first, "plum-tree-river-7"))
try:
    hasher.verify(first, "plum-tree-river-8")
except VerifyMismatchError:
    print("wrong password: rejected")

params = extract_parameters(first)
print("read back from the hash:", params.memory_cost, params.time_cost, params.parallelism)
PY
.venv/bin/python first_hash.py

The string hash() returns is the whole record you store, in the PHC string format:

  • $argon2id is the variant, and v=19 is the Argon2 version.
  • m=19456,t=2,p=1 are the parameters this hash was made with.
  • The next part is a random 16-byte salt, and the last part is the 32-byte hash, both in unpadded Base64.

Because the parameters and salt travel inside the string, you never store them in separate columns, and verify() can check a hash made with any settings. That is what makes upgrading parameters later possible. Note that verify() returns True or raises an exception; it never returns False, so a bare if hasher.verify(...) without a try is a bug waiting to happen.

Check it worked

The first two lines both start $argon2id$v=19$m=19456,t=2,p=1$ and differ after that. Then you see same password, different hashes: True, right password: True, wrong password: rejected and read back from the hash: 19456 2 1.

Step 4 · Tune the parameters to about 100 ms on your server

The OWASP figures are a floor, not a target. Use as much cost as your server can afford: a sign-in that takes about 100 ms is unnoticeable to a person and expensive for an attacker. Raise memory first, because memory is what hurts attackers most, and raise passes only once memory hits the limit you can spare.

That limit matters. Every sign-in being checked at the same moment needs its own block of memory, so 8 parallel sign-ins at 128 MiB each need 1 GiB. On a small 1 or 2 GB virtual server, a common choice for teams keeping hosting costs down, set MAX_MEMORY_KIB lower. The hashing always happens on your server, never on the user's device, so people signing in on low-end Android phones or slow prepaid connections are not affected by the value you choose.

Run this on the machine that will check passwords, not on your laptop:

Bash
cat > tune.py <<'PY'
import json
import statistics
import time

from argon2 import PasswordHasher

TARGET_MS = 100
MAX_MEMORY_KIB = 131072  # 128 MiB per sign-in; lower this on a small server
MAX_TIME_COST = 6
MEMORY_STEPS_KIB = [19456, 32768, 47104, 65536, 98304, 131072]


def median_ms(hasher, runs=5):
    stored = hasher.hash("tuning-password")
    timings = []
    for _ in range(runs):
        start = time.perf_counter()
        hasher.verify(stored, "tuning-password")
        timings.append((time.perf_counter() - start) * 1000)
    return statistics.median(timings)


choice = None
time_cost = 2
while choice is None:
    for memory in [m for m in MEMORY_STEPS_KIB if m <= MAX_MEMORY_KIB]:
        ms = median_ms(PasswordHasher(time_cost=time_cost, memory_cost=memory, parallelism=1))
        print(f"m={memory:>6} KiB ({memory // 1024:>3} MiB)  t={time_cost}  p=1  {ms:6.1f} ms")
        choice = {"memory_cost": memory, "time_cost": time_cost, "parallelism": 1}
        if ms >= TARGET_MS:
            break
    else:
        if time_cost < MAX_TIME_COST:
            time_cost += 1
            choice = None

with open("params.json", "w") as f:
    json.dump(choice, f, indent=2)
print("chosen:", choice)
PY
.venv/bin/python tune.py

The script starts at the OWASP minimum, walks memory up to your cap, then adds passes until a verification takes at least 100 ms, and writes the result to params.json. It never chooses anything below m=19456,t=2,p=1. Keep p=1 unless you have measured a gain: OWASP notes that more lanes do not make guessing slower.

argon2-cffi also has a built-in benchmark. Use it to double-check a single setting, replacing the numbers with the ones your run chose:

Bash
.venv/bin/python -m argon2 -t 2 -m 19456 -p 1

Check it worked

The table shows each setting with its timing, rising as memory grows, and the last line names your choice, for example chosen: {'memory_cost': 65536, 'time_cost': 2, 'parallelism': 1}. cat params.json shows the same three numbers. The benchmark prints the parameters it used and a line ending in per password verification. Re-run the tuner after moving to new hardware; Argon2 parameters are meant to rise over time.

Step 5 · Add a pepper kept outside the database

A salt is stored next to the hash. A pepper is one secret value, shared by all passwords, that is never stored in the database. Someone who steals only the database, through a backup or a SQL injection, then cannot test a single guess. OWASP calls this defence in depth: it helps only while the pepper stays separate, and it is no substitute for a strong hash.

This tutorial uses a pre-hashing pepper: the password is run through HMAC-SHA256 keyed with the pepper, and the Base64 of that result is what Argon2id hashes. Base64 keeps the input printable, which matters if a bcrypt step ever touches it.

Create the pepper in a file that is private from the moment it exists, then load it into an environment variable:

Bash
cd ~/argon2-demo
( umask 077 && .venv/bin/python -c "import secrets; print(secrets.token_urlsafe(32))" > pepper.secret )
printf 'pepper.secret\nusers.db\n.venv/\n' > .gitignore
export PASSWORD_PEPPER="$(cat pepper.secret)"
ls -l pepper.secret

On your server, keep the pepper where your other application secrets live, such as a secrets manager or a root-owned file readable only by the app's user, and pass it to the app as PASSWORD_PEPPER. Back it up separately from the database: if you lose it, no one can sign in. Plan for the opposite case too. A pepper cannot be changed without each user's password, so if it leaks, users protected by it need to reset their passwords.

Now write the module the rest of the tutorial uses. It reads the parameters from params.json and the pepper from the environment, and refuses to run without a pepper rather than quietly hashing without one:

Bash
cat > passwords.py <<'PY'
import base64
import hashlib
import hmac
import json
import os
import secrets
from pathlib import Path

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

_PARAMS = json.loads(Path(__file__).with_name("params.json").read_text())
HASHER = PasswordHasher(
    time_cost=_PARAMS["time_cost"],
    memory_cost=_PARAMS["memory_cost"],
    parallelism=_PARAMS["parallelism"],
)


def peppered(password: str) -> str:
    pepper = os.environ.get("PASSWORD_PEPPER")
    if not pepper:
        raise RuntimeError("PASSWORD_PEPPER is not set")
    mac = hmac.new(pepper.encode(), password.encode("utf-8"), hashlib.sha256).digest()
    return base64.b64encode(mac).decode("ascii")


def hash_password(password: str) -> str:
    return HASHER.hash(peppered(password))


_dummy_hash = None


def _spend_time(password: str) -> None:
    # Run a real verification so an unknown username takes as long as a known one.
    global _dummy_hash
    if _dummy_hash is None:
        _dummy_hash = hash_password(secrets.token_urlsafe(16))
    try:
        HASHER.verify(_dummy_hash, peppered(password))
    except VerificationError:
        pass


def verify_password(stored: str | None, password: str) -> tuple[bool, str | None]:
    """Return (ok, new_hash). Store new_hash when it is not None."""
    if stored is None:
        _spend_time(password)
        return False, None

    if stored.startswith("$2"):
        # Legacy bcrypt hash, made before the pepper existed. bcrypt only ever
        # read the first 72 bytes, and bcrypt 5 raises on longer input.
        try:
            ok = bcrypt.checkpw(password.encode("utf-8")[:72], stored.encode("ascii"))
        except ValueError:
            ok = False
        return (True, hash_password(password)) if ok else (False, None)

    try:
        HASHER.verify(stored, peppered(password))
    except (VerificationError, InvalidHashError):
        return False, None
    if HASHER.check_needs_rehash(stored):
        return True, hash_password(password)
    return True, None
PY

Check it worked

ls -l shows -rw------- for pepper.secret. Then prove that the database alone is not enough: hash a password, and verify it with the right pepper and with a wrong one:

Bash
cd ~/argon2-demo
.venv/bin/python -c "
import os
from passwords import hash_password, verify_password
stored = hash_password('plum-tree-river-7')
print('right pepper:', verify_password(stored, 'plum-tree-river-7')[0])
os.environ['PASSWORD_PEPPER'] = 'a-guess-at-the-pepper'
print('wrong pepper:', verify_password(stored, 'plum-tree-river-7')[0])
"

The output is right pepper: True and wrong pepper: False. The right password fails without the right pepper.

Step 6 · Upgrade old hashes when users sign in

You cannot rehash a stored hash on its own, because you need the password. The only moment you have it is a successful sign-in, so that is when you upgrade: verify, then ask check_needs_rehash() whether the hash was made with your current parameters, and if not, store a fresh one. The verify_password function above already does this, and it treats bcrypt hashes the same way, so you can move off bcrypt without asking anyone to reset a password.

Seed a users table with three accounts in three states: one still on bcrypt, one on Argon2id with weak parameters from years ago, and one already current. The demo passwords are written into the script for practice; in your app they come from the sign-in form.

Bash
cat > seed_users.py <<'PY'
import sqlite3

import bcrypt
from argon2 import PasswordHasher

from passwords import hash_password, peppered

old_hasher = PasswordHasher(time_cost=3, memory_cost=4096, parallelism=1)

users = {
    "amina": bcrypt.hashpw(b"amina-demo-pass", bcrypt.gensalt(rounds=12)).decode(),
    "kofi": old_hasher.hash(peppered("kofi-demo-pass")),
    "lena": hash_password("lena-demo-pass"),
}

db = sqlite3.connect("users.db")
db.execute("DROP TABLE IF EXISTS users")
db.execute("CREATE TABLE users (username TEXT PRIMARY KEY, hash TEXT NOT NULL)")
db.executemany("INSERT INTO users VALUES (?, ?)", users.items())
db.commit()
for name, stored in db.execute("SELECT username, hash FROM users ORDER BY username"):
    print(f"{name:<6} {stored[:31]}")
PY
.venv/bin/python seed_users.py

Now the sign-in. It looks up the hash, verifies, and writes the new hash back in the same place:

Bash
cat > signin_demo.py <<'PY'
import sqlite3

from passwords import verify_password

db = sqlite3.connect("users.db")


def sign_in(username, password):
    row = db.execute("SELECT hash FROM users WHERE username = ?", (username,)).fetchone()
    ok, new_hash = verify_password(row[0] if row else None, password)
    if ok and new_hash:
        db.execute("UPDATE users SET hash = ? WHERE username = ?", (new_hash, username))
        db.commit()
    return ok, new_hash is not None


attempts = [
    ("amina", "wrong-guess"),
    ("amina", "amina-demo-pass"),
    ("kofi", "kofi-demo-pass"),
    ("lena", "lena-demo-pass"),
    ("nobody", "any-pass"),
]
for username, password in attempts:
    ok, upgraded = sign_in(username, password)
    print(f"{username:<7} signed in: {ok!s:<5}  upgraded: {upgraded}")

print()
for name, stored in db.execute("SELECT username, hash FROM users ORDER BY username"):
    print(f"{name:<6} {stored[:31]}")
PY
.venv/bin/python signin_demo.py

A wrong password never triggers an upgrade, and the unknown user nobody still costs one full Argon2id verification, so response times do not reveal which usernames exist. Your sign-in page should give the same message for both cases.

Check it worked

Before the sign-ins, amina starts $2b$12$, kofi starts $argon2id$v=19$m=4096,t=3,p=1$ and lena shows your tuned parameters. The sign-in lines read:

  • amina with the wrong password: signed in False, upgraded False.
  • amina, kofi: signed in True, upgraded True.
  • lena: signed in True, upgraded False, because her hash was already current.
  • nobody: signed in False.

In the table after them, all three users start with $argon2id$v=19$ and your tuned m= and t=. Run .venv/bin/python signin_demo.py again and every line says upgraded: False.

Accounts that never sign in stay on bcrypt. Once most active users have moved, you can deal with the rest by wrapping their bcrypt hashes in Argon2id, or by expiring those passwords and sending reset emails.

Step 7 · Verify the same hashes from Node.js

The encoded string is a shared format, so a Node.js service can check the hashes your Python code wrote, as long as it applies the same pepper. @node-rs/argon2 is a native binding with prebuilt binaries, defaults to Argon2id, and takes memoryCost, timeCost and parallelism options.

Bash
cd ~/argon2-demo
mkdir -p node
cd node
npm init -y > /dev/null
npm install --silent @node-rs/argon2@2.2.2

The script reads the policy from the same params.json, verifies Amina's upgraded hash from the SQLite file, hashes a new password, and implements a needs-rehash check with parseOptions(), which reads the parameters back out of a hash:

Bash
cat > check.mjs <<'JS'
import { createHmac } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { DatabaseSync } from 'node:sqlite';
import argon2 from '@node-rs/argon2';

const params = JSON.parse(readFileSync('../params.json', 'utf8'));
const policy = {
  memoryCost: params.memory_cost,
  timeCost: params.time_cost,
  parallelism: params.parallelism,
};

const pepper = process.env.PASSWORD_PEPPER;
if (!pepper) throw new Error('PASSWORD_PEPPER is not set');
const peppered = (password) =>
  createHmac('sha256', pepper).update(password, 'utf8').digest('base64');

function needsRehash(stored) {
  if (!stored.startsWith('$argon2id$')) return true;
  const found = argon2.parseOptions(stored);
  return (
    found.memoryCost !== policy.memoryCost ||
    found.timeCost !== policy.timeCost ||
    found.parallelism !== policy.parallelism
  );
}

const db = new DatabaseSync('../users.db', { readOnly: true });
const { hash: stored } = db.prepare('SELECT hash FROM users WHERE username = ?').get('amina');

console.log('python hash, right password:', await argon2.verify(stored, peppered('amina-demo-pass')));
console.log('python hash, wrong password:', await argon2.verify(stored, peppered('wrong-guess')));

const fresh = await argon2.hash(peppered('new-user-pass'), policy);
console.log('new node hash:', fresh.split('$').slice(0, 4).join('$'));
console.log('needs rehash:', needsRehash(fresh));
JS
node check.mjs

Unlike argon2-cffi, verify() here resolves to true or false rather than raising. Python's base64.b64encode and Node's digest('base64') produce the same padded text, which is why the peppered input matches across the two.

Check it worked

The output is python hash, right password: true, python hash, wrong password: false, a line new node hash: $argon2id$v=19$m=...,t=...,p=1 with your tuned numbers, and needs rehash: false. A hash written by Python verified in Node.js.

Step 8 · Clean up

Remove the demo folder, including the pepper file and the database, and clear the variable from your shell:

Bash
cd ~
rm -rf ~/argon2-demo
unset PASSWORD_PEPPER

Check it worked

ls ~/argon2-demo reports No such file or directory, and echo "${PASSWORD_PEPPER:-unset}" prints unset.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.