How-To Guide

How to Implement Password Hashing with Argon2

Hash passwords with Argon2: pick memory and time parameters, store the full encoded hash, verify and upgrade hashes over time, and test the work factor.

On this page

  1. Introduction
  2. Choose a memory-hard algorithm and parameters
  3. Store the encoded hash, not the parts
  4. Verify and upgrade on login
  5. Bound the cost against abuse
  6. Test the work factor and verification
  7. Common pitfalls
  8. Conclusion

Introduction

A password store is a target: if the database leaks, the attacker holds the hashes and tries to recover the passwords. A fast hash like SHA-256 makes that recovery cheap, because the attacker can test billions of guesses a second. Password hashing is deliberately different: it uses an algorithm designed to be slow and memory-hard, so each guess costs a controllable amount of time and memory, and a brute force becomes impractical.

This tutorial uses Argon2id, the current recommendation, and covers choosing parameters for your hardware, storing the encoded hash that carries the salt and parameters, verifying and migrating to stronger parameters over time, and testing the work factor. The examples use an Argon2 library, and the reasoning applies to scrypt and bcrypt as well.

Choose a memory-hard algorithm and parameters

Use Argon2id, which combines resistance to side-channel attacks with resistance to GPU cracking. The parameters are memory, iterations, and parallelism; together they set the cost of one hash. The goal is a hash that takes a fixed fraction of a second on your hardware, often a target like 100 to 500 milliseconds, so a legitimate login is fast enough and an attacker’s brute force is expensive.

Tune to your server’s memory and CPU. Memory is the strongest lever against GPUs and ASICs, so raise it to the most you can afford per concurrent login without exhausting the host. Increase iterations to add time, and set parallelism to the number of lanes you can run. Benchmark on the production hardware, because the same parameters take very different times on a laptop and a small container; what matters is the time on the machine that will run it.

import argon2 from 'argon2';

const params = {
  type: argon2.argon2id,
  memoryCost: 1 << 16,   // 64 MiB
  timeCost: 3,
  parallelism: 1,
};

async function hashPassword(password) {
  return argon2.hash(password, params); // returns the full encoded string
}

Store the encoded hash, not the parts

An Argon2 hash is stored as an encoded string that includes the algorithm, the parameters, the base64 salt, and the base64 digest, separated by dollar signs. Store that whole string in one column; it is self-describing, so verification needs no separate salt or parameter columns, and a future parameter change is visible in the stored value.

Never store the salt separately or reuse a salt. Argon2 generates a random salt per hash and embeds it in the encoded string, which ensures two hashes of the same password differ and defeats precomputed tables. Let the library generate the salt and produce the encoded value; do not craft the encoding yourself, because a mistake there can silently weaken every hash.

CREATE TABLE users (
  id            bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email         text NOT NULL UNIQUE,
  password_hash text NOT NULL   -- the full $argon2id$v=19$m=65536,t=3,p=1$... string
);

Verify and upgrade on login

Verification takes the stored encoded string and the presented password and returns whether they match, using the parameters recorded in the string. The library parses the parameters from the stored value, so it verifies an old hash with its old parameters even after you have changed the defaults. Never re-encode or re-parameterize the stored value before verifying; verify against exactly what is stored.

Because parameters must increase over time as hardware gets cheaper, migrate hashes on successful login. After verifying the password, check whether the stored hash uses current parameters; if not, re-hash the plaintext with the new parameters and update the row. You have the plaintext only at login, so that is the moment to upgrade, and active users migrate as they sign in. Users who never log in keep an old hash until a forced reset, which is an acceptable trade-off.

async function login(password, user) {
  const ok = await argon2.verify(user.password_hash, password);
  if (!ok) return null;
  if (argon2.needsRehash(user.password_hash, params)) {
    const upgraded = await hashPassword(password);
    await db.query('UPDATE users SET password_hash = $1 WHERE id = $2', [upgraded, user.id]);
  }
  return user;
}

Bound the cost against abuse

A memory-hard hash is expensive by design, which an attacker can turn into a denial of service: many concurrent login attempts each allocate the memory and time of a hash, exhausting the server. Rate-limit login attempts per account and per source, and cap the concurrency of hashing so a flood cannot consume all the memory. The cost that protects the password store must not become the vector that takes it down.

Also guard against the timing of the not-found case. If an unknown email returns immediately and a known email runs a hash, the timing reveals which emails are registered. Always run a hash, against a dummy record when the user does not exist, and return the same error and timing. This pairs the password hashing with the account-enumeration defense in one uniform path.

Test the work factor and verification

Test that hashing the same password twice yields different encoded strings, proving a random salt. Test that verification accepts the correct password and rejects a wrong one. Test that a hash produced with old parameters still verifies, which is what allows migration. Test that a hash takes within a target range on your hardware, so a parameters change that makes it too fast or too slow is caught. Test that the stored value begins with the expected algorithm prefix.

node -e '
const argon2 = require("argon2");
(async () => {
  const t0 = Date.now();
  const h1 = await argon2.hash("pw", { type: argon2.argon2id, memoryCost: 65536, timeCost: 3, parallelism: 1 });
  const h2 = await argon2.hash("pw", { type: argon2.argon2id, memoryCost: 65536, timeCost: 3, parallelism: 1 });
  console.log("ms=" + (Date.now()-t0), "distinct=" + (h1 !== h2), "prefix=" + h1.slice(0,9));
})();'

Common pitfalls

Hashing with a fast algorithm such as SHA-256, reusing a salt or storing one separately, parameters too low to slow an attacker, verifying against a re-encoded value that loses the original parameters, no upgrade path so old hashes persist, and no rate limit so the hashing cost becomes a denial of service are the recurring mistakes. Argon2id with tuned parameters, library-generated salts in the encoded string, verify-then-rehash, and rate limiting address them.

Conclusion

Password hashing is deliberately expensive. Use Argon2id with memory and time tuned to your hardware, store the full encoded hash, verify as stored and re-hash on login when parameters age, and rate-limit the cost. Self-check by asserting two hashes of the same password differ, a wrong password is rejected, and a hash lands in the target time range. Then a leaked database does not hand over the passwords.

Sources: RFC 9106: Argon2, OWASP: Password storage cheat sheet, argon2 reference implementation.

FAQ

Why not SHA-256 the password?
A fast hash is exactly the wrong property for passwords. An attacker with the hashes tries billions of guesses per second. Argon2 is memory-hard and tunable, so each guess costs a configurable amount of memory and time, making a brute force far more expensive.
How do I migrate from an old hash?
Store the algorithm and parameters with each hash. On a successful login, if the stored hash uses an old algorithm or weaker parameters, re-hash the plaintext password with the new settings and update the row. Over time, active users migrate as they log in.

Related Examples