Labs › security

Build Your Own Password Hashing Service

Build password hashing right — from naive bcrypt to Argon2id to peppering with key rotation. Java co-primary shows Spring Security's DelegatingPasswordEncoder and how to implement transparent hash upgrades on login.

go 1.23 intermediate ~5h build · ~2h read ~430 LoC (v3)
v0: bcrypt — intentionally slowv1: Argon2id — memory-hard, the 2023 recommendationv2: Peppering + key rotation
☕ Java/Spring integration included co primary

Why this lab exists

Every major data breach includes a password dump. In 2012, LinkedIn lost 6.5 million password hashes — all unsalted SHA-1. Crackers recovered the majority in days. In 2013, Adobe lost 130 million password hashes — all encrypted with ECB mode (identical passwords produced identical ciphertext). In 2016, Dropbox lost 68 million bcrypt and SHA-1 hashes. The bcrypt ones have still largely resisted cracking.

The difference between “cracked in days” and “still uncracked after years” is not computational budget. It is algorithm choice. SHA-1, MD5, and SHA-256 are designed to be fast — millions of operations per second per CPU core, billions per second on a GPU. bcrypt, Argon2id, and scrypt are designed to be slow and expensive, specifically to resist the attacker who has your database and unlimited GPU time.

This lab builds password hashing right, across three stages: bcrypt (the baseline), Argon2id (the modern recommendation), and peppering with key rotation (the defense-in-depth layer). The Java co-primary shows Spring Security’s PasswordEncoder hierarchy — the same ideas, the same algorithms, different API.

What we’re building

A password hashing service in Go across three stages, with a Java co-primary implementation using Spring Security’s crypto module.

We build:

  • bcrypt wrapper (v0): cost=10 targeting 100ms per hash, showing the cost doubling effect
  • Argon2id with self-describing encoded format (v1): matching the Go and Spring Security wire format
  • PepperKeyStore with transparent key rotation (v2): version-aware pepper lookup, needsRehash signal
  • HTTP server: POST /hash, POST /verify, GET /health
  • Java: BCryptPasswordEncoder, Argon2PasswordEncoder, custom PepperingPasswordEncoder, PasswordUpgradeService, DelegatingPasswordEncoder for migration

We explicitly skip:

  • scrypt (correct but superseded by Argon2id for new systems)
  • Rate limiting on the verify endpoint (essential in production; see What the Toy Misses)
  • HSM integration for pepper storage (correct in production; adds significant complexity)

Mental model

The threat model has one sentence: the database is stolen.

An attacker has a copy of your entire users table. Every row. Every column. The attack is offline — they run their cracking software on their own hardware, no network involved, no rate limiting. They have unlimited time and a GPU cluster.

Why SHA-256 fails immediately:

An RTX 4090 computes roughly 10 billion SHA-256 hashes per second. A 6-character lowercase password has 26^6 = 308 million combinations. At 10 billion per second, every 6-character lowercase password cracks in 0.03 seconds. A full dictionary of 100 million common passwords cracks in 0.01 seconds. SHA-256 is not a password hashing function — it is a general-purpose hash designed to be fast, and fast is exactly wrong here.

Why slow is the correct design:

bcrypt at cost=10 runs roughly 10,000 hashes per second on a GPU (not 10 billion — 1 million times slower). Those 308 million 6-character lowercase combinations now take 308,000,000 / 10,000 = 30,800 seconds = 8.5 hours. For a dictionary of 100 million passwords: 100,000,000 / 10,000 = 10,000 seconds = 2.8 hours. Slow enough to be painful, not impossible.

Why Argon2id is better:

bcrypt is compute-hard but not memory-hard. A GPU can run thousands of bcrypt computations in parallel, limited only by compute units. Argon2id requires 64MB of RAM per hash. An RTX 4090 has 24GB of VRAM. At 64MB per hash: 24,576 MB / 64 MB = 384 hashes in parallel at most. The same 308 million combinations: 308,000,000 / 384 = 802,083 sequential GPU-time-slots. If each slot takes ~120ms: 802,083 * 0.12 seconds = 96,250 seconds = 26.7 hours. And that assumes perfect GPU utilization with no overhead.

Why peppering makes this moot:

The hash in the database is argon2id(password + pepper). The pepper is a 32-byte random secret stored in an environment variable or a vault — not in the database. If the database is stolen, the attacker has hashes of (password + pepper). Without knowing the pepper, they cannot crack anything. The attack on the hash is: try a candidate password, append the pepper, hash it, compare. No pepper = no candidates = no cracking.

The pepper does not replace good hashing. It is defense-in-depth: the database alone is not enough. The attacker now needs the database AND the server-side secret.

┌─────────────────────────────────────────────────────────────┐
│  Threat model: database stolen                               │
│                                                             │
│  Without peppering:                                         │
│    Attacker has: hashes                                     │
│    Can do: offline brute-force (limited by Argon2id time)  │
│                                                             │
│  With peppering:                                            │
│    Attacker has: hashes + unknown pepper                    │
│    Can do: nothing (can't construct valid candidates)       │
│                                                             │
│  With peppering AND database + vault compromise:            │
│    Attacker has: hashes + pepper                            │
│    Can do: offline brute-force (back to Argon2id time)     │
│    But: compromising DB + vault = full system compromise    │
│    → You have bigger problems than password cracking        │
└─────────────────────────────────────────────────────────────┘

Prerequisites

  • Go 1.23+ and Java 17+
  • Maven 3.9+ (for the Java co-primary)
  • Understanding of hash functions (SHA-256, HMAC) at a conceptual level
  • The JWT Library lab is helpful context for key-versioning concepts

Stage-by-stage build

Stage 0 bcrypt — intentionally slow ~80 LoC ›
  • Implement HashBcrypt(password, cost) using golang.org/x/crypto/bcrypt
  • Implement VerifyBcrypt(password, hash) — always constant-time
  • Time cost=10 vs cost=11: verify that cost=11 takes roughly 2x longer
  • Read the self-describing hash format: $2a$10$<salt><hash>

bcrypt was designed in 1999 by Niels Provos and David Mazières specifically for password hashing. The core insight was already clear then: password hashing must be adjustable in cost, so that as hardware gets faster, you can increase the work factor and keep pace.

The cost factor is an exponent: bcrypt internally iterates 2^cost times. Cost=10 means 1024 iterations. Cost=14 means 16,384 iterations — 16 times more work. When hardware doubles in speed, you increment the cost by 1 and you’re back to the same wall-clock time.

// HashBcrypt: wraps golang.org/x/crypto/bcrypt
func HashBcrypt(password string, cost int) (string, error) {
    hash, err := bcrypt.GenerateFromPassword([]byte(password), cost)
    return string(hash), err
}

// VerifyBcrypt: constant-time comparison built into bcrypt.CompareHashAndPassword
func VerifyBcrypt(password, hash string) bool {
    err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
    return err == nil
}

The returned hash is self-describing. $2a$10$... tells you: bcrypt version 2a, cost factor 10, then 22 characters of base64-encoded salt, then 31 characters of the hash. This means you can verify hashes even after changing the cost factor in your config — each hash remembers its own parameters. The same design applies to Argon2id in v1.

bcrypt’s weakness is that it is not memory-hard. Each bcrypt computation uses a small, fixed amount of RAM (about 4KB for its Blowfish state). GPUs can run thousands of bcrypt computations in parallel, limited only by the number of compute units, not by VRAM. A modern GPU can achieve ~10,000 bcrypt hashes/sec (cost=10). Argon2id, which requires 64MB per hash, changes this dramatically.

Stage 1 Argon2id — memory-hard, the 2023 recommendation ~200 LoC ›
  • Implement HashArgon2id(password, pepper, params) with a PHC-format encoded output
  • Implement VerifyArgon2id(password, pepper, encoded) — parse params from encoded string
  • Verify the encoded format matches: $argon2id$v=19$m=65536,t=3,p=4$<base64-salt>$<base64-hash>
  • Understand why 64MB memory requirement limits GPU parallelism

Argon2id won the Password Hashing Competition in 2015. It has three variants:

  • Argon2d: fast GPU resistance via data-dependent memory access. Vulnerable to side-channel attacks — not recommended for password hashing.
  • Argon2i: side-channel resistant via data-independent memory access. Weaker GPU resistance.
  • Argon2id: hybrid — uses Argon2i for the first pass (side-channel safety), Argon2d for subsequent passes (GPU resistance). This is the recommended variant.

The key parameter is memory — the amount of RAM required per hash computation. Each hash allocates a memory matrix of memory KiB and fills it with pseudo-random data derived from the password and salt. The final hash is derived from the entire filled matrix. You cannot skip filling the matrix — the output depends on it.

// Argon2Params holds the tuning knobs
type Argon2Params struct {
    Memory      uint32  // KiB — 65536 = 64MB
    Iterations  uint32  // passes over memory
    Parallelism uint8   // threads
    SaltLength  uint32
    KeyLength   uint32
}

func HashArgon2id(password, pepper string, params Argon2Params) (string, error) {
    salt := make([]byte, params.SaltLength)
    rand.Read(salt)

    // Pepper appended to password before hashing. Not stored anywhere.
    hash := argon2.IDKey(
        []byte(password+pepper), salt,
        params.Iterations, params.Memory, params.Parallelism,
        params.KeyLength,
    )

    // PHC string format — self-describing, interoperable with Spring Security
    return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
        argon2.Version,
        params.Memory, params.Iterations, params.Parallelism,
        base64.RawStdEncoding.EncodeToString(salt),
        base64.RawStdEncoding.EncodeToString(hash),
    ), nil
}

Verification parses the encoded string to extract parameters, then recomputes the hash with the same salt and compares with subtle.ConstantTimeCompare. The parsed parameters may differ from the current default parameters — that is intentional. Old hashes created with weaker parameters still verify correctly. The needsRehash signal (v2) tells you to transparently upgrade the hash on next login.

The GPU math: Argon2id with m=65536 KiB (64MB). An RTX 4090 has 24GB VRAM: 24,576 MB / 64 MB = 384 maximum parallel Argon2id computations. Compare bcrypt (cost=10): limited by compute units, not VRAM. An RTX 4090 has 16,384 CUDA cores and can run thousands of bcrypt computations simultaneously. Argon2id’s memory requirement caps GPU parallelism at a physical hardware limit.

Stage 2 Peppering + key rotation ~150 LoC ›
  • Implement PepperKeyStore with CurrentKey + PreviousKeys slice
  • Hash(password) → {hash, pepperVersion} using current pepper
  • Verify(password, hash, pepperVersion) → {ok, needsRehash}
  • Test: rotate pepper, old hash still verifies with needsRehash=true
  • Test: upgraded params → needsRehash=true even with same pepper

A pepper is a server-side secret. It is NOT stored in the database. It lives in an environment variable, a secrets manager (AWS Secrets Manager, HashiCorp Vault), or an HSM. The stored hash is argon2id(password + pepper). If the database is stolen alone, the attacker cannot crack any hash — they cannot construct valid candidates without knowing the pepper.

The PepperKeyStore manages key rotation: you can change the pepper over time without invalidating all existing hashes. Each hash is stored with a version number. On verification, you look up the pepper for that version, verify with it, and if it matches an old version, signal needsRehash.

type PepperKeyStore struct {
    CurrentKey   PepperKey    // used for all new hashes
    PreviousKeys []PepperKey  // retained for old hash verification
    Params       Argon2Params
}

func (s *PepperKeyStore) Hash(password string) (HashResult, error) {
    pepper := decodePepper(s.CurrentKey.Secret)
    encoded, _ := HashArgon2id(password, pepper, s.Params)
    return HashResult{Hash: encoded, PepperVersion: s.CurrentKey.Version}, nil
}

func (s *PepperKeyStore) Verify(password, hash string, pepperVersion int) VerifyResult {
    pepper, found := s.findPepper(pepperVersion)
    if !found {
        return VerifyResult{OK: false}
    }

    ok := VerifyArgon2id(password, decodePepper(pepper.Secret), hash)
    if !ok {
        return VerifyResult{OK: false}
    }

    // Signal rehash if: old pepper version OR params have been upgraded
    needsRehash := pepper.Version != s.CurrentKey.Version || s.paramsChanged(hash)
    return VerifyResult{OK: true, NeedsRehash: needsRehash}
}

The rotation flow:

  1. Generate a new 32-byte pepper. Store it in your secrets manager.
  2. Call store.AddCurrentKey(2, newPepperHex). The old key moves to PreviousKeys.
  3. New user logins create hashes with pepper v2.
  4. Existing users: on next login, Verify finds pepper v1, validates OK, sets NeedsRehash=true.
  5. The caller re-hashes with pepper v2 and updates the database.
  6. Eventually, all active users have v2 hashes. You can remove v1 from PreviousKeys.

The needsRehash signal also fires when the Argon2id parameters have been upgraded (e.g., you increased memory from 32MB to 64MB). The stored hash embeds the parameters it was created with, so paramsChanged() can detect the mismatch by parsing the encoded string.

On the HTTP server: POST /hash returns the hash and pepper version. POST /verify takes the password, hash, and pepper version, returns ok and needsRehash. The caller (your auth service) is responsible for updating the stored hash when needsRehash is true.

Run it yourself

Prereqs: Go 1.23+Java 17+Maven 3.9+
  1. 1
    Clone and run Go tests
    git clone https://github.com/pushkarkumar-dev/system-design-labs
    cd system-design-labs/labs/password-hashing
    go test ./pkg/passwords/ -v
  2. 2
    Start the Go HTTP server
    PEPPER_V1=deadbeefdeadbeef go run ./cmd/server/
  3. 3
    Hash a password
    curl -s -X POST http://localhost:8080/hash \
      -H "Content-Type: application/json" \
      -d '{"password":"correct-horse-battery-staple"}' | jq .
  4. 4
    Verify the password
    HASH=$(curl -s -X POST http://localhost:8080/hash \
      -H "Content-Type: application/json" \
      -d '{"password":"correct-horse-battery-staple"}' | jq -r .hash)
    VERSION=1
    curl -s -X POST http://localhost:8080/verify \
      -H "Content-Type: application/json" \
      -d "{\"password\":\"correct-horse-battery-staple\",\"hash\":\"$HASH\",\"pepperVersion\":$VERSION}" | jq .
  5. 5
    Run the Java demo
    cd labs/password-hashing/java && mvn spring-boot:run
  6. 6
    Run the Java tests
    cd labs/password-hashing/java && mvn test
Expected output
--- go test ./pkg/passwords/ -v ---
=== RUN   TestBcryptRoundtrip
--- PASS: TestBcryptRoundtrip (0.10s)
=== RUN   TestBcryptWrongPassword
--- PASS: TestBcryptWrongPassword (0.10s)
=== RUN   TestArgon2idRoundtrip
--- PASS: TestArgon2idRoundtrip (0.12s)
=== RUN   TestArgon2idWrongPassword
--- PASS: TestArgon2idWrongPassword (0.12s)
=== RUN   TestArgon2idPepperMismatch
--- PASS: TestArgon2idPepperMismatch (0.12s)
=== RUN   TestPepperKeyStoreRoundtrip
--- PASS: TestPepperKeyStoreRoundtrip (0.12s)
=== RUN   TestPepperRotationOldVersionStillVerifies
--- PASS: TestPepperRotationOldVersionStillVerifies (0.24s)
=== RUN   TestNeedsRehashWhenParamsChange
--- PASS: TestNeedsRehashWhenParamsChange (0.24s)
PASS

--- POST /hash ---
{
"hash": "$argon2id$v=19$m=65536,t=3,p=4$...",
"version": 1
}

--- POST /verify (correct password) ---
{
"ok": true,
"needsRehash": false
}

Benchmarks

Benchmark results on M2 MacBook Pro, 16GB RAM (estimated — see bench-results.json)
Metric Result Notes
bcrypt cost=10 100 ms/hash Deliberate slowness — the entire point. cost=10 is the standard for login flows.
bcrypt cost=14 1,600 ms/hash 2^4 = 16x slower than cost=10. For high-security admin accounts.
Argon2id (m=64MB, t=3, p=4) 120 ms/hash OWASP 2023 recommendation. Memory requirement is the key defense.
Attacker (bcrypt cost=10, RTX 4090) 10,000 hashes/sec GPU-parallel bcrypt is compute-limited. Still 1M times slower than SHA-256.
Attacker (Argon2id 64MB, RTX 4090) 384 parallel hashes max VRAM-limited: 24,576MB / 64MB = 384 max. Memory-hardness in action.
SHA-256 baseline (RTX 4090) 10,000,000,000 hashes/sec Never use SHA-256 for passwords. 6-char lowercase cracks in 0.03 seconds.

The SHA-256 vs Argon2id comparison is the most important number in this table. A 6-character lowercase password (26^6 = 308 million combinations): SHA-256 at 10 billion/sec cracks it in 0.03 seconds. Argon2id at 384 parallel hashes on a GPU: the same password takes roughly 26.7 hours. Peppering makes the comparison moot — without the pepper, neither algorithm can be attacked at all.

Stress tests

The go test suite covers the critical correctness properties. For stress testing:

# Run with -count=10 to repeat each test 10 times (catches timing flukes)
go test ./pkg/passwords/ -count=10 -run TestTimingAttack

# Benchmark mode — actual hash throughput numbers
go test ./pkg/passwords/ -bench=BenchmarkArgon2id -benchtime=10s

# Race detector — password hashing shouldn't have races but good practice
go test ./pkg/passwords/ -race ./...

For load testing the HTTP server:

# hey (HTTP load generator): 100 concurrent hash requests
hey -n 1000 -c 100 -m POST -H "Content-Type: application/json" \
  -d '{"password":"test-password"}' \
  http://localhost:8080/hash

At 100 concurrent requests and ~120ms per hash, expect ~833 hashes/sec throughput (limited by Argon2id cost, not network). This is the correct behavior — each request must be slow. An HTTP server that hashes faster than this is misconfigured.

What the toy misses

What the toy misses Honest gaps vs. production
  • Scrypt (memory-hard predecessor to Argon2) Scrypt is still widely used (Litecoin, many web apps). Argon2id won the Password Hashing Competition (2015) and is now preferred, but scrypt is correct to use. Our service only implements Argon2id.
  • Rate limiting on verification Our service hashes and verifies but doesn't rate-limit verification attempts. An attacker with network access to our service can probe passwords at HTTP request speed. In production, verification happens only after authenticated login, with exponential backoff on failure and account lockout.
  • Secure memory wipe After hashing, the plaintext password should be zeroed from memory to prevent it appearing in core dumps or swap. Go's GC makes this hard — the string may be copied multiple times. C implementations use sodium_memzero(). Our implementation does not wipe. This is a known limitation of high-level language password hashing.
  • HSM for pepper storage A pepper stored in a config file or environment variable is only as secure as that file or process environment. Production systems store peppers in an HSM (Hardware Security Module) or a secrets manager (AWS KMS, HashiCorp Vault). The pepper never leaves the HSM in plaintext — the HSM performs the HMAC computation internally.
  • Password strength checking Hashing a weak password with Argon2id does not make it strong. 'password1' with perfect hashing is still cracked in seconds with a dictionary attack. Production systems check password strength (e.g., the zxcvbn library) before accepting it and reject passwords that appear in known breach lists (HaveIBeenPwned API).
  • Audit logging Every hash and verification event should be logged with timestamp, user ID (not password), and outcome for security audit purposes. Failed verification attempts in rapid succession indicate a brute-force attempt. Our service has no audit trail and no anomaly detection.

Wiring it into a Java/Spring service

☕

Wiring it into a Java/Spring service

co primary spring-security-crypto
Maven dependencies
org.springframework.security:spring-security-crypto
org.springframework.boot:spring-boot-starter-security:3.3.0
org.springframework.boot:spring-boot-starter-web:3.3.0

Go reference — what we built

The Go implementation in labs/password-hashing/pkg/passwords/ covers three stages in ~430 lines. No dependencies beyond golang.org/x/crypto. Every operation is explicit: bcrypt cost tuning, Argon2id parameter selection, PHC string encoding/parsing, constant-time comparison via subtle.ConstantTimeCompare, and pepper key rotation with version tracking.

The key design decisions carry over to Java: peppers are appended before hashing (never stored), hashes are self-describing (params embedded in the encoded string), and verification signals needsRehash when parameters or peppers are outdated.

Java co-primary — Spring Security’s PasswordEncoder hierarchy

Spring Security’s spring-security-crypto module provides a PasswordEncoder interface that every hashing strategy implements. This is not just convenient — it is the correct abstraction. Your authentication code depends on PasswordEncoder, not on bcrypt or Argon2id specifically. Swapping algorithms requires changing one line of configuration.

The hierarchy:

PasswordEncoder (interface)
  BCryptPasswordEncoder     — bcrypt, cost=10 default
  Argon2PasswordEncoder     — Argon2id, configurable params
  SCryptPasswordEncoder     — scrypt, for legacy compatibility
  DelegatingPasswordEncoder — dispatches by {prefix} in the stored hash
  PepperingPasswordEncoder  — our custom wrapper (adds server-side pepper)

PasswordHasherBcrypt.java — bcrypt with explicit cost

public class PasswordHasherBcrypt {
    private final BCryptPasswordEncoder encoder;

    public PasswordHasherBcrypt(int cost) {
        this.encoder = new BCryptPasswordEncoder(cost);
    }

    public String hash(String rawPassword) {
        return encoder.encode(rawPassword);
        // Returns: $2a$10$<22-char-salt><31-char-hash> — same format as Go
    }

    public boolean needsRehash(String encodedPassword) {
        // Returns true if stored cost < encoder's configured cost.
        // Triggers transparent upgrade on next login.
        return encoder.upgradeEncoding(encodedPassword);
    }
}

PasswordHasherArgon2.java — Argon2id with OWASP params

// OWASP-recommended params (2023), matching Go DefaultArgon2Params()
Argon2PasswordEncoder encoder = new Argon2PasswordEncoder(
    16,     // saltLength bytes
    32,     // hashLength bytes
    2,      // parallelism
    65536,  // memory KiB — 64MB
    3       // iterations
);

String hash = encoder.encode("my-password");
// Returns: $argon2id$v=19$m=65536,t=3,p=2$<base64-salt>$<base64-hash>
// This format is identical to the Go HashArgon2id() output.
// A hash created by the Go server can be verified by this encoder.

The encoded string format is defined by the PHC (Password Hashing Competition) string format specification. Both the Go argon2.IDKey wrapper and Spring Security’s Argon2PasswordEncoder produce and consume this format. Cross-language hash verification works out of the box.

PepperingPasswordEncoder.java — the PasswordEncoder extension point

The PasswordEncoder interface is the correct abstraction for adding peppering. Implementing it lets you compose with DelegatingPasswordEncoder, inject it as a Spring bean, and use it anywhere PasswordEncoder is expected — including Spring Security’s authentication manager.

public class PepperingPasswordEncoder implements PasswordEncoder {
    private final PasswordEncoder delegate;
    private final String pepper;

    public PepperingPasswordEncoder(PasswordEncoder delegate, String pepper) {
        this.delegate = delegate;
        this.pepper = pepper;
    }

    @Override
    public String encode(CharSequence rawPassword) {
        // Hash: (password + pepper). Pepper never leaves this class.
        return delegate.encode(rawPassword.toString() + pepper);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        // Verify: (password + pepper) against stored hash. Constant-time via delegate.
        return delegate.matches(rawPassword.toString() + pepper, encodedPassword);
    }

    @Override
    public boolean upgradeEncoding(String encodedPassword) {
        // Delegate decides if params are outdated. Triggers needsRehash signal.
        return delegate.upgradeEncoding(encodedPassword);
    }
}

Usage in Spring configuration:

@Bean
public PasswordEncoder passwordEncoder() {
    String pepper = System.getenv("APP_PEPPER"); // load from vault in production
    Argon2PasswordEncoder argon2 = new Argon2PasswordEncoder(16, 32, 2, 65536, 3);
    return new PepperingPasswordEncoder(argon2, pepper);
}

PasswordUpgradeService.java — transparent hash upgrades on login

The upgrade service implements the pattern where a successful login transparently upgrades an outdated hash. The caller (your auth controller) gets an AuthResult with the new hash and writes it back to the database.

public AuthResult authenticate(String rawPassword, String storedHash) {
    if (!encoder.matches(rawPassword, storedHash)) {
        return AuthResult.failure();
    }

    if (encoder.upgradeEncoding(storedHash)) {
        // Password verified. Hash is outdated (old cost or old pepper).
        // Re-hash with current encoder and signal the caller to update DB.
        String newHash = encoder.encode(rawPassword);
        return AuthResult.successWithUpgrade(newHash);
    }

    return AuthResult.success();
}

This matches the Go PepperKeyStore.Verify() returning NeedsRehash: true. Both implementations signal the same thing: the caller must update the database. Neither implementation updates the database directly — that separation keeps the hashing service stateless and testable.

PasswordHashingConfig.java — DelegatingPasswordEncoder for algorithm migration

DelegatingPasswordEncoder stores a format prefix in the hash: {bcrypt}$2a$10$... or {argon2}$argon2id$v=19$.... The prefix tells the decoder which delegate to use for verification. New hashes get the current default prefix. Old hashes keep their original prefix and continue to verify until they are upgraded.

Map encoders = new HashMap();
encoders.put("bcrypt", new BCryptPasswordEncoder(10));
encoders.put("argon2", new PepperingPasswordEncoder(
    new Argon2PasswordEncoder(16, 32, 2, 65536, 3), pepper
));

// Default encoding: new hashes use {argon2}
DelegatingPasswordEncoder delegating = new DelegatingPasswordEncoder("argon2", encoders);

Migration path for a production system:

  1. Add DelegatingPasswordEncoder with both bcrypt and argon2 delegates.
  2. New users get {argon2} hashes immediately.
  3. Existing bcrypt users: on login, matches() calls the bcrypt delegate (from the prefix). If it succeeds and upgradeEncoding() returns true, re-hash with argon2 and update DB.
  4. After N months, all active users have {argon2} hashes. Remove the bcrypt delegate.

No flag day. No forced password resets. No downtime. This is the correct production migration approach.

The shared lesson

The Go PepperKeyStore and the Java PepperingPasswordEncoder + PasswordUpgradeService make the same design choices because there is only one correct set of choices for password hashing:

  1. Use a slow, adaptive algorithm (bcrypt or Argon2id — not SHA-256).
  2. Add a server-side pepper that is not stored in the database.
  3. Signal when a hash is outdated (needsRehash/upgradeEncoding) so the caller can upgrade transparently on login.
  4. Never store or log the plaintext password beyond the scope of the hash computation.

The languages and APIs differ. The security model is identical.

What surprised me

Where to go deeper

  • NIST SP 800-63B (password guidance): the US federal standard — includes memory-hard requirements — pages.nist.gov/800-63-3/sp800-63b.html
  • Argon2 RFC 9106: the IETF standard for Argon2 — includes the PHC string format specification — rfc-editor.org/rfc/rfc9106
  • Password Hashing Competition results: the selection process that chose Argon2 — password-hashing.net
  • Spring Security PasswordEncoder docs: explains the full encoder hierarchy and DelegatingPasswordEncoder migration — docs.spring.io
  • HaveIBeenPwned API: check if a password appears in known breaches without sending the password — k-anonymity model — haveibeenpwned.com/API/v3
  • Previous in security: JWT Library — key handling, algorithm pinning, and why algorithm selection must never trust attacker-controlled input
  • Next in security: mTLS From Scratch — mutual TLS and client certificate authentication without a CA
  • System design questions this unlocks: How do you migrate 50 million password hashes from bcrypt to Argon2id without forcing password resets? What is the correct bcrypt cost for 2025? How does HaveIBeenPwned check your password without learning it (k-anonymity)?