Password hashing

suggest change

If your application has user accounts, you need to store something that lets you check a password at login without storing the password itself. The answer is a password hash: a one-way function that turns the password into a string you can store, and that you can later recompute from a login attempt and compare.

A general-purpose hash such as SHA-256 is the wrong tool for this. It is designed to be fast, and fast is exactly what an attacker who has stolen your database wants. Password hashing functions are designed to be slow, salted and (in newer designs) to need lots of memory.

This article covers:

Related articles: Compute Cryptographic Hashes for MessageDigest, Generate Cryptographically Random Data for SecureRandom, and Application security for the bigger picture.

All examples are single files you can run with java -cp <jars> Example.java. The output shown comes from JDK 25. Hashes and timings will differ on your machine.

What a password hash must do

Property Why
One-way Nobody, including you, can turn the hash back into the password
Salted A random salt per password means two users with the same password get different hashes, and precomputed "rainbow tables" are useless
Slow (tunable work factor) Each guess costs the attacker real CPU time. You raise the cost as hardware gets faster
Memory-hard (Argon2, scrypt) Each guess also needs lots of RAM, which makes GPUs and custom chips much less effective
Self-describing output The stored string records the algorithm, parameters and salt, so you can verify it years later and know when it's outdated

The algorithms that meet these requirements, in order of preference (OWASP Password Storage Cheat Sheet):

Algorithm Minimum settings In Java
Argon2id 19 MiB memory, 2 iterations, 1 lane Bouncy Castle, Spring Security
scrypt N=2^17, r=8, p=1 Bouncy Castle, Spring Security
bcrypt cost 10 at.favre.lib:bcrypt, Spring Security
PBKDF2-HMAC-SHA256 600,000 iterations JDK (SecretKeyFactory)

Never use plain MD5, SHA-1 or SHA-256, with or without a salt. Never encrypt passwords either: anyone who gets the key gets every password.

Why a fast hash is a problem

This program counts how many guesses per second one CPU core can check against SHA-256 and against PBKDF2:

import java.security.MessageDigest;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class FastVsSlow {
    public static void main(String[] args) throws Exception {
        byte[] salt = new byte[16];

        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        int n = 1_000_000;
        long t0 = System.nanoTime();
        for (int i = 0; i < n; i++) {
            sha.digest(("guess" + i).getBytes());
        }
        double shaPerSec = n / ((System.nanoTime() - t0) / 1e9);

        SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        int m = 10;
        t0 = System.nanoTime();
        for (int i = 0; i < m; i++) {
            f.generateSecret(new PBEKeySpec(("guess" + i).toCharArray(), salt, 600_000, 256));
        }
        double pbkdfPerSec = m / ((System.nanoTime() - t0) / 1e9);

        System.out.printf("SHA-256:              %,12.0f guesses/s%n", shaPerSec);
        System.out.printf("PBKDF2 (600k rounds): %,12.1f guesses/s%n", pbkdfPerSec);
        System.out.printf("slowdown: about %,.0fx%n", shaPerSec / pbkdfPerSec);
    }
}

Output:

SHA-256:                 4,420,956 guesses/s
PBKDF2 (600k rounds):          4.0 guesses/s
slowdown: about 1,103,456x

That's one core in Java. A single modern GPU checks billions of SHA-256 hashes per second, so an 8-character password hashed with SHA-256 falls in hours. The same GPU is limited to thousands of PBKDF2 guesses per second, and to far fewer Argon2id guesses, because each one needs 19 MiB of memory.

The slowness also costs you: every login spends this time on your server. The goal is to make hashing as slow as you can afford, usually somewhere between 100 ms and 1 s per hash.

PBKDF2 with the JDK only

PBKDF2 is the only password hashing function built into the JDK. It's the weakest of the four (it needs no memory, so GPUs are good at it), but it's FIPS-approved and needs no dependencies. With HMAC-SHA256, OWASP recommends at least 600,000 iterations.

The code below stores the algorithm, iteration count, salt and hash in one string, so the iteration count can be raised later without breaking existing hashes:

import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class Pbkdf2Hasher {
    private static final String ALGORITHM = "PBKDF2WithHmacSHA256";
    private static final int ITERATIONS = 600_000; // OWASP 2023+ recommendation for SHA-256
    private static final int SALT_BYTES = 16;
    private static final int HASH_BITS = 256;
    private static final SecureRandom RANDOM = new SecureRandom();
    private static final Base64.Encoder B64 = Base64.getEncoder().withoutPadding();
    private static final Base64.Decoder B64D = Base64.getDecoder();

    /** Returns a self-describing string: $pbkdf2-sha256$i=600000$salt$hash */
    public static String hash(char[] password) throws GeneralSecurityException {
        byte[] salt = new byte[SALT_BYTES];
        RANDOM.nextBytes(salt);
        byte[] hash = pbkdf2(password, salt, ITERATIONS, HASH_BITS);
        return "$pbkdf2-sha256$i=" + ITERATIONS + "$" + B64.encodeToString(salt)
                + "$" + B64.encodeToString(hash);
    }

    public static boolean verify(char[] password, String stored) throws GeneralSecurityException {
        String[] parts = stored.split("[$]");
        // parts[0] is empty because the string starts with '$'
        if (parts.length != 5 || !parts[1].equals("pbkdf2-sha256") || !parts[2].startsWith("i=")) {
            throw new IllegalArgumentException("not a pbkdf2-sha256 hash");
        }
        int iterations = Integer.parseInt(parts[2].substring(2));
        byte[] salt = B64D.decode(parts[3]);
        byte[] expected = B64D.decode(parts[4]);
        byte[] actual = pbkdf2(password, salt, iterations, expected.length * 8);
        return MessageDigest.isEqual(expected, actual); // constant-time comparison
    }

    /** True if the hash was made with weaker settings than we use today. */
    public static boolean needsRehash(String stored) {
        String[] parts = stored.split("[$]");
        return parts.length != 5 || !parts[1].equals("pbkdf2-sha256")
                || Integer.parseInt(parts[2].substring(2)) < ITERATIONS;
    }

    private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bits)
            throws GeneralSecurityException {
        PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bits);
        try {
            return SecretKeyFactory.getInstance(ALGORITHM).generateSecret(spec).getEncoded();
        } finally {
            spec.clearPassword();
        }
    }

    public static void main(String[] args) throws Exception {
        char[] password = "correct horse battery staple".toCharArray();

        long t0 = System.nanoTime();
        String stored = hash(password);
        long ms = (System.nanoTime() - t0) / 1_000_000;

        System.out.println(stored);
        System.out.println("length: " + stored.length() + ", took about " + (ms / 50 * 50) + " ms");
        System.out.println("correct password: " + verify(password, stored));
        System.out.println("wrong password:   " + verify("Correct horse battery staple".toCharArray(), stored));
        System.out.println("hashing again gives a different string: " + !stored.equals(hash(password)));
        System.out.println("needs rehash: " + needsRehash(stored));
        System.out.println("old 10k-iteration hash needs rehash: "
                + needsRehash("$pbkdf2-sha256$i=10000$AAAAAAAAAAAAAAAAAAAAAA$AAAA"));

        Arrays.fill(password, '\0'); // wipe the password from memory
    }
}

Output:

$pbkdf2-sha256$i=600000$GX0wYYslhhiPQR8nLYuaOw$imlY9RyfNVLrs2izGvxyyMDk4Ifuz9MBW9GPa8kS5Xw
length: 90, took about 400 ms
correct password: true
wrong password:   false
hashing again gives a different string: true
needs rehash: false
old 10k-iteration hash needs rehash: true

Things to notice:

The $name$params$salt$hash layout follows the PHC string format, which Argon2 also uses. Allow at least 100 characters for the column that stores it.

Argon2id with Bouncy Castle

Argon2id won the Password Hashing Competition in 2015 and is the first choice for new code. Besides CPU time, it needs a configurable amount of memory per hash, which makes large-scale guessing on GPUs expensive. The JDK doesn't include it. Bouncy Castle has a pure-Java implementation with no native code:

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk18on</artifactId>
    <version>1.86</version>
</dependency>

Gradle: implementation("org.bouncycastle:bcprov-jdk18on:1.86").

Bouncy Castle only gives you the raw function: password and salt in, bytes out. Encoding the parameters is up to you. The code below produces the standard PHC string, the same format the reference C implementation, PHP's password_hash, Python's argon2-cffi and Spring Security produce:

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import org.bouncycastle.crypto.generators.Argon2BytesGenerator;
import org.bouncycastle.crypto.params.Argon2Parameters;

public class Argon2Hasher {
    // OWASP minimum for Argon2id: 19 MiB of memory, 2 passes, 1 lane
    private static final int MEMORY_KIB = 19 * 1024;
    private static final int ITERATIONS = 2;
    private static final int PARALLELISM = 1;
    private static final int SALT_BYTES = 16;
    private static final int HASH_BYTES = 32;
    private static final SecureRandom RANDOM = new SecureRandom();
    private static final Base64.Encoder B64 = Base64.getEncoder().withoutPadding();
    private static final Base64.Decoder B64D = Base64.getDecoder();

    /** Returns a standard PHC string: $argon2id$v=19$m=19456,t=2,p=1$salt$hash */
    public static String hash(String password) {
        byte[] salt = new byte[SALT_BYTES];
        RANDOM.nextBytes(salt);
        byte[] hash = argon2(password, salt, MEMORY_KIB, ITERATIONS, PARALLELISM, HASH_BYTES);
        return "$argon2id$v=19$m=" + MEMORY_KIB + ",t=" + ITERATIONS + ",p=" + PARALLELISM
                + "$" + B64.encodeToString(salt) + "$" + B64.encodeToString(hash);
    }

    public static boolean verify(String password, String stored) {
        // "", "argon2id", "v=19", "m=...,t=...,p=...", salt, hash
        String[] parts = stored.split("[$]");
        if (parts.length != 6 || !parts[1].equals("argon2id") || !parts[2].equals("v=19")) {
            throw new IllegalArgumentException("not an argon2id v19 hash");
        }
        int m = 0, t = 0, p = 0;
        for (String kv : parts[3].split(",")) {
            int value = Integer.parseInt(kv.substring(2));
            switch (kv.charAt(0)) {
                case 'm' -> m = value;
                case 't' -> t = value;
                case 'p' -> p = value;
                default -> throw new IllegalArgumentException("bad parameter " + kv);
            }
        }
        byte[] salt = B64D.decode(parts[4]);
        byte[] expected = B64D.decode(parts[5]);
        byte[] actual = argon2(password, salt, m, t, p, expected.length);
        return MessageDigest.isEqual(expected, actual);
    }

    private static byte[] argon2(String password, byte[] salt, int memoryKib, int iterations,
                                 int parallelism, int hashBytes) {
        Argon2Parameters params = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)
                .withVersion(Argon2Parameters.ARGON2_VERSION_13)
                .withMemoryAsKB(memoryKib)
                .withIterations(iterations)
                .withParallelism(parallelism)
                .withSalt(salt)
                .build();
        Argon2BytesGenerator generator = new Argon2BytesGenerator();
        generator.init(params);
        byte[] out = new byte[hashBytes];
        generator.generateBytes(password.getBytes(StandardCharsets.UTF_8), out);
        return out;
    }

    public static void main(String[] args) {
        String stored = hash("pässwörd-🔑");
        System.out.println(stored);
        System.out.println("correct: " + verify("pässwörd-🔑", stored));
        System.out.println("wrong:   " + verify("passwort", stored));
    }
}

Run with java -cp bcprov-jdk18on-1.86.jar Argon2Hasher.java. Output:

$argon2id$v=19$m=19456,t=2,p=1$r1qFL1jiFhEgFfCG1eFXXA$jzWcIH7kq49Kl2tUnKHrbCpDiY5RA3D8QMbKCWRFdCk
correct: true
wrong:   false

Because the format is standard, hashes move between languages. A hash created by PHP's password_hash("secret", PASSWORD_ARGON2ID), $argon2id$v=19$m=65536,t=4,p=1$YnAvVWhQVXNJaHg5QjFjbg$MzB/eHPsGvTN34rySFmVM099RmuA4C9/yJUGtjqKonk, verifies with the verify method above, and PHP's password_verify accepts hashes created by hash. That's useful when you migrate a user database from another stack.

The parameters:

The password is converted to bytes with UTF-8. Always pick the charset explicitly, or a server with a different default charset will compute different hashes for non-ASCII passwords. You may also want to normalize the password with java.text.Normalizer.normalize(pw, Normalizer.Form.NFKC) first, so that é typed as one code point and as e plus an accent produce the same hash.

bcrypt

bcrypt dates from 1999. It isn't memory-hard, but it has held up well and is supported everywhere. Its output is a 60-character string that holds the version, cost and salt: $2a$12$ + 22 characters of salt + 31 characters of hash.

The JDK has no bcrypt. A small, well-maintained library is at.favre.lib:bcrypt:

<dependency>
    <groupId>at.favre.lib</groupId>
    <artifactId>bcrypt</artifactId>
    <version>0.10.2</version>
</dependency>

It depends on at.favre.lib:bytes, so the command line needs both jars: java -cp "bcrypt-0.10.2.jar:bytes-1.6.1.jar" BcryptDemo.java (use ; instead of : on Windows).

import at.favre.lib.crypto.bcrypt.BCrypt;
import at.favre.lib.crypto.bcrypt.LongPasswordStrategies;

public class BcryptDemo {
    public static void main(String[] args) {
        char[] password = "s3cret-Passw0rd".toCharArray();

        // cost 12 = 2^12 rounds of the key setup
        String hash = BCrypt.withDefaults().hashToString(12, password);
        System.out.println(hash);
        System.out.println("length: " + hash.length());

        BCrypt.Result ok = BCrypt.verifyer().verify(password, hash);
        BCrypt.Result bad = BCrypt.verifyer().verify("s3cret-passw0rd".toCharArray(), hash);
        System.out.println("correct: " + ok.verified + ", cost " + ok.details.cost
                + ", version " + ok.details.version);
        System.out.println("wrong:   " + bad.verified);

        // A hash made by PHP's password_hash("hunter2", PASSWORD_BCRYPT)
        String fromPhp = "$2y$10$OeSnhkFvLIq5/mHJd6Evb.Oe37zp/.X9/ecOjYNSNUSjg/0wbMzNK";
        System.out.println("PHP hash verifies: "
                + BCrypt.verifyer().verify("hunter2".toCharArray(), fromPhp).verified);

        // bcrypt only uses the first 72 bytes of the password
        String longPw = "a".repeat(72);
        try {
            BCrypt.withDefaults().hashToString(12, (longPw + "b").toCharArray());
        } catch (IllegalArgumentException e) {
            System.out.println("73 bytes: " + e.getMessage());
        }
        // Opt in to pre-hashing long passwords with SHA-512 instead
        BCrypt.Hasher hasher = BCrypt.with(LongPasswordStrategies.hashSha512(BCrypt.Version.VERSION_2A));
        String h1 = hasher.hashToString(12, (longPw + "b").toCharArray());
        BCrypt.Verifyer verifyer = BCrypt.verifyer(BCrypt.Version.VERSION_2A,
                LongPasswordStrategies.hashSha512(BCrypt.Version.VERSION_2A));
        System.out.println("73rd char changed, still matches: "
                + verifyer.verify((longPw + "c").toCharArray(), h1).verified);
    }
}

Output:

$2a$12$wVrEuU.4yBD/xqb9MWOJzOBGBlKZYTgvCoVYkY4m/4tiAHINgkRli
length: 60
correct: true, cost 12, version $2a$
wrong:   false
PHP hash verifies: true
73 bytes: password must not be longer than 72 bytes plus null terminator encoded in utf-8, was 73
73rd char changed, still matches: false

The cost is a base-2 logarithm: each step up doubles the time. $2a$, $2b$ and $2y$ are variants of the same algorithm from different implementations, and the verifier accepts all of them, so hashes from PHP, Node.js or Ruby verify too.

The important limit: bcrypt only uses the first 72 bytes of the password. Some implementations silently ignore the rest, so two long passwords that share a 72-byte prefix are treated as the same. That is 72 UTF-8 bytes, not 72 characters: a password in Cyrillic or Chinese hits it at 24 to 36 characters. This library throws an exception instead, which is safer. You have two choices:

If you have the choice, Argon2id has no such limit.

Spring Security's PasswordEncoder

If you use Spring, you don't need to write any of the code above. Spring Security's crypto module has a PasswordEncoder interface with implementations for Argon2, bcrypt, scrypt and PBKDF2, and a DelegatingPasswordEncoder that picks the right one based on a {id} prefix in the stored string.

In a Spring Boot application with spring-boot-starter-security it's already on the classpath. In a plain Java project, add:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-crypto</artifactId>
    <version>7.1.1</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>7.0.9</version>
</dependency>

spring-core brings in commons-logging. Argon2 and scrypt also need bcprov-jdk18on from above.

import java.util.Map;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;

public class SpringEncoders {
    public static void main(String[] args) {
        // Each encoder on its own
        PasswordEncoder argon2 = Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8();
        PasswordEncoder bcrypt = new BCryptPasswordEncoder(12);
        PasswordEncoder pbkdf2 = Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8();

        String a = argon2.encode("secret");
        System.out.println("argon2: " + a);
        System.out.println("bcrypt: " + bcrypt.encode("secret"));
        System.out.println("pbkdf2: " + pbkdf2.encode("secret"));
        System.out.println("argon2 matches: " + argon2.matches("secret", a));

        // The factory: bcrypt by default, can verify many other formats
        PasswordEncoder standard = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        System.out.println("factory default: " + standard.encode("secret"));

        // Your own: new hashes use argon2, old bcrypt and pbkdf2 hashes still verify
        PasswordEncoder encoder = new DelegatingPasswordEncoder("argon2", Map.of(
                "argon2", argon2,
                "bcrypt", bcrypt,
                "pbkdf2", pbkdf2));

        String fresh = encoder.encode("secret");
        String legacy = "{bcrypt}" + bcrypt.encode("secret");
        System.out.println("fresh:  " + fresh);
        System.out.println("legacy: " + legacy);
        System.out.println("fresh matches:  " + encoder.matches("secret", fresh));
        System.out.println("legacy matches: " + encoder.matches("secret", legacy));
        System.out.println("fresh needs upgrade:  " + encoder.upgradeEncoding(fresh));
        System.out.println("legacy needs upgrade: " + encoder.upgradeEncoding(legacy));

        try {
            encoder.matches("secret", "$2a$10$noPrefixSoTheEncoderDoesNotKnowWhatThisIs");
        } catch (IllegalArgumentException e) {
            System.out.println("no prefix: " + e.getMessage());
        }
    }
}

Output:

argon2: $argon2id$v=19$m=16384,t=2,p=1$mVinknsjF0bbOVpMNQ4lRw$tJhk1C+ycGAdxR195FYLkgzhhbZaGIjeZqwP1p4I3wE
bcrypt: $2a$12$XRV7aifUShMoxNT.ml0a2ubmgsDaIv8sF4zoAh/dd7jOBZ.JH/a6W
pbkdf2: 4e9390cbad79f3b53805aa3ad447ae02d960c7af456a606d857e26a279d20e6874b762a858a8276ec96575eb84b87fe8
argon2 matches: true
factory default: {bcrypt}$2a$10$5WyU3oYo6R9QvP1My6blAuodi.pF9YcKmjy1IkwD5r5cFsUg476rG
fresh:  {argon2}$argon2id$v=19$m=16384,t=2,p=1$dsv6jsghdvugKJB1U7Qypw$8UxadGOLZBbg8D/wQfxCVecUA3is+I+ejsw/KxegMMk
legacy: {bcrypt}$2a$12$odo7PNvh.EAt9uBLN3xSieIc4SXtazzPaYY6iztAeAu2YjpR/hD4y
fresh matches:  true
legacy matches: true
fresh needs upgrade:  false
legacy needs upgrade: true
no prefix: Given that there is no default password encoder configured, each password must have a password encoding prefix. Please either prefix this password with '{noop}' or set a default password encoder in `DelegatingPasswordEncoder`.

Notes:

A login flow that upgrades old hashes

You can't re-hash passwords in a batch job, because you don't have the passwords. The only time you have the plain password is during a successful login. So the standard upgrade strategy is: verify against the old hash, and if it's outdated, hash the password again with current settings and save the new hash.

The same method also handles a common information leak. If a login for an unknown username returns immediately, while a wrong password takes 50 ms of hashing, an attacker can tell which usernames exist just by timing the responses. The fix is to check the password against a dummy hash when the user doesn't exist:

import java.util.HashMap;
import java.util.Map;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;

public class LoginService {
    private final PasswordEncoder encoder = new DelegatingPasswordEncoder("argon2", Map.of(
            "argon2", new Argon2PasswordEncoder(16, 32, 1, 19 * 1024, 2),
            "pbkdf2", Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8()));

    // Stands in for a users table: username -> stored hash
    private final Map<String, String> users = new HashMap<>();

    // Checked when the user doesn't exist, so that case takes as long as a wrong password
    private final String dummyHash = encoder.encode("dummy-password-never-matches");

    public void register(String username, String password) {
        users.put(username, encoder.encode(password));
    }

    public boolean login(String username, String password) {
        String stored = users.get(username);
        if (stored == null) {
            encoder.matches(password, dummyHash); // burn the same time, ignore the result
            return false;
        }
        if (!encoder.matches(password, stored)) {
            return false;
        }
        // The only moment we know the plain password: upgrade old hashes now
        if (encoder.upgradeEncoding(stored)) {
            users.put(username, encoder.encode(password));
            System.out.println("  (upgraded hash for " + username + ")");
        }
        return true;
    }

    public static void main(String[] args) {
        LoginService svc = new LoginService();
        svc.register("alice", "alice-pw");
        // bob was created years ago, when the app used PBKDF2
        svc.users.put("bob", "{pbkdf2}"
                + Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8().encode("bob-pw"));

        System.out.println("bob before: " + svc.users.get("bob").substring(0, 30) + "...");
        System.out.println("bob, right password: " + svc.login("bob", "bob-pw"));
        System.out.println("bob after:  " + svc.users.get("bob").substring(0, 30) + "...");
        System.out.println("bob again:  " + svc.login("bob", "bob-pw"));
        System.out.println("alice, wrong password: " + svc.login("alice", "nope"));

        long t0 = System.nanoTime();
        svc.login("alice", "nope");
        long wrongPw = (System.nanoTime() - t0) / 1_000_000;
        t0 = System.nanoTime();
        svc.login("mallory", "nope");
        long noUser = (System.nanoTime() - t0) / 1_000_000;
        System.out.println("wrong password took " + wrongPw + " ms, unknown user took " + noUser + " ms");
    }
}

Output:

bob before: {pbkdf2}4cc6168a473f6745804f89...
  (upgraded hash for bob)
bob, right password: true
bob after:  {argon2}$argon2id$v=19$m=19456...
bob again:  true
alice, wrong password: false
wrong password took 44 ms, unknown user took 39 ms

Bob's PBKDF2 hash was replaced by an Argon2id hash on his first successful login. Accounts that never log in keep their old hashes. After a migration period, you can expire those accounts' passwords and send them a password-reset email.

If your old hashes are so weak that you don't want to keep them around until users log in (for example unsalted MD5), you can wrap them: store argon2(md5(password)) for every user right away in a batch job, mark those rows, and at login compute md5 first for marked rows. Then upgrade them to plain argon2(password) as above.

Choosing the work factor

Pick parameters by measuring on your production hardware. Aim for the slowest setting that keeps login latency and server load acceptable, which is usually 100 to 500 ms per hash for an interactive login. Here is a quick benchmark for bcrypt cost:

import at.favre.lib.crypto.bcrypt.BCrypt;

public class BcryptCost {
    public static void main(String[] args) {
        char[] pw = "benchmark-password".toCharArray();
        BCrypt.withDefaults().hashToString(4, pw); // warm up the JIT

        for (int cost = 10; cost <= 14; cost++) {
            long t0 = System.nanoTime();
            BCrypt.withDefaults().hashToString(cost, pw);
            long ms = (System.nanoTime() - t0) / 1_000_000;
            System.out.printf("cost %d: %5d ms%n", cost, ms);
        }
    }
}

Output:

cost 10:    91 ms
cost 11:   228 ms
cost 12:   378 ms
cost 13:   860 ms
cost 14:  1574 ms

On this machine, cost 12 is a reasonable choice. The same approach works for Argon2 (vary m first, then t) and for PBKDF2 (vary the iteration count).

Keep in mind:

Adding a pepper

A pepper is a secret key that is mixed into every password hash and stored outside the database: in a secrets manager, an HSM, or an environment variable. If an attacker steals the database through SQL injection or a leaked backup but not the application's secrets, the hashes are useless to them, because they can't compute a single guess.

The usual way to add one is to compute an HMAC of the password with the pepper as the key, then hash the HMAC with a normal password hash. As a bonus, the Base64 of an HMAC-SHA256 is always 44 characters, which solves bcrypt's 72-byte limit:

import at.favre.lib.crypto.bcrypt.BCrypt;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class PepperedHasher {
    private final SecretKeySpec pepper;

    PepperedHasher(byte[] pepperKey) {
        this.pepper = new SecretKeySpec(pepperKey, "HmacSHA256");
    }

    // HMAC the password with the secret pepper, then bcrypt the result.
    // Base64 of a 32-byte HMAC is 44 chars: always under bcrypt's 72-byte limit.
    private char[] peppered(String password) throws GeneralSecurityException {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(pepper);
        byte[] digest = mac.doFinal(password.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(digest).toCharArray();
    }

    String hash(String password) throws GeneralSecurityException {
        return BCrypt.withDefaults().hashToString(12, peppered(password));
    }

    boolean verify(String password, String stored) throws GeneralSecurityException {
        return BCrypt.verifyer().verify(peppered(password), stored).verified;
    }

    public static void main(String[] args) throws Exception {
        // In production: load from a secrets manager or env var, never from the database
        byte[] key = "0123456789abcdef0123456789abcdef".getBytes(StandardCharsets.UTF_8);
        PepperedHasher hasher = new PepperedHasher(key);

        String longPassword = "x".repeat(100) + "-end";
        String stored = hasher.hash(longPassword);
        System.out.println(stored);
        System.out.println("correct:        " + hasher.verify(longPassword, stored));
        System.out.println("last char diff: " + hasher.verify("x".repeat(100) + "-enD", stored));

        PepperedHasher otherPepper = new PepperedHasher(
                "ffffffffffffffffffffffffffffffff".getBytes(StandardCharsets.UTF_8));
        System.out.println("stolen DB, no pepper: " + otherPepper.verify(longPassword, stored));
    }
}

Output:

$2a$12$okBPioWQL2vVPS3Thi4VGeCw7rA59o0J4GRw8HoDVfEB4xw0EtCwS
correct:        true
last char diff: false
stolen DB, no pepper: false

The downside is operational: if you lose the pepper, every user has to reset their password, and rotating it requires the same upgrade-on-login dance. Use one if you can manage secrets properly. Skip it otherwise; a good salted password hash is the part that matters.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents