Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 39 ยท Testing and Hardening

Password Storage, Hashing and Migration

Store passwords safely: salted slow hashes, DelegatingPasswordEncoder with id prefixes, bcrypt and Argon2 choices, upgrading old hashes at login and a runnable PBKDF2 demo.

If your database leaks, passwords are the part that hurts most, because people reuse them. The goal of password storage is not to hide passwords forever but to make each guess expensive for an attacker. That needs three things: a one-way function, a unique random salt per password, and a deliberately slow algorithm.

Spring Security packages this as the PasswordEncoder interface. The framework classes cannot run on this site, so the examples that run use the JDK's PBKDF2 as a stand-in to demonstrate the mechanics: salt, iterations, constant-time verification and upgrade on login.

What not to do

Approach Problem
Plain text One leak exposes everything
Reversible encryption The key leaks together with the data in most breaches
MD5, SHA-1, plain SHA-256 Designed to be fast: billions of guesses per second on a GPU
One global salt ("pepper" in the code) Identical passwords still match across users, and one rainbow table works for all
Home-made schemes Everyone who tried got it wrong

The right tools

Java
@Bean
PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

The delegating encoder writes hashes with an algorithm id in curly braces:

TEXT
{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG
{argon2@SpringSecurity_v5_8}$argon2id$v=19$m=16384,t=2,p=1$...
{pbkdf2@SpringSecurity_v5_8}...
{noop}plain   <- only for tests

The prefix tells Spring which encoder verifies a stored hash. New passwords use the default (bcrypt), old ones keep working, and you can change algorithms later without a flag day. Choices:

Algorithm Notes
BCryptPasswordEncoder Default. Cost factor 10 to 12; truncates passwords beyond 72 bytes
Argon2PasswordEncoder Memory-hard, needs Bouncy Castle; good modern choice
Pbkdf2PasswordEncoder Standard, FIPS-friendly; use many iterations
SCryptPasswordEncoder Memory-hard alternative

Tune the cost so a single verification takes roughly 100 to 500 ms on your production hardware: slow enough to hurt attackers, fast enough for a login.

How salted slow hashing works

Java Salt and iterations with PBKDF2 (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two users with the same password get different hashes because the salt differs, so an attacker cannot crack all of them at once. The stored value contains everything needed to verify later (iteration count, salt, hash) but nothing that reveals the password.

Migrating old hashes at login

Suppose your legacy table has unsalted SHA-256 hashes. You cannot convert them in bulk (you do not know the passwords), but you can upgrade each user the next time they log in, when the plain password is briefly available. Spring's DelegatingPasswordEncoder supports this with upgradeEncoding(...), and DaoAuthenticationProvider re-encodes automatically when an UserDetailsPasswordService bean exists.

Java Upgrade legacy hashes on login (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In Spring you wire the upgrade by implementing UserDetailsPasswordService:

Java
@Service
class AccountService implements UserDetailsPasswordService {
    @Override
    public UserDetails updatePassword(UserDetails user, String newEncodedPassword) {
        accounts.updatePassword(user.getUsername(), newEncodedPassword);
        return User.withUserDetails(user).password(newEncodedPassword).build();
    }
}

Policy matters as much as hashing

  • Accept long passwords and passphrases (at least 64 characters); do not force odd composition rules.
  • Check new passwords against lists of breached passwords.
  • Never email passwords, never log them, never put them in URLs.
  • Encourage multi-factor authentication for important accounts.
  • Return the same message for "unknown user" and "wrong password", and take similar time (see Login throttling).

stores plain text and exists for demos and tests only. If you find it in production configuration, treat it as an incident.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is plain SHA-256 a poor password hash?

    Password hashes must be deliberately slow and salted: bcrypt, Argon2, scrypt or PBKDF2.
  2. 2. What does the {bcrypt} prefix in DelegatingPasswordEncoder do?

    The id lets many algorithms coexist and makes later migration possible.
  3. 3. How can you migrate unsalted legacy hashes without resetting every password?

    At login you briefly hold the plain password, so you can store a modern hash then.
  4. 4. Why does each password need its own random salt?

    A per-password salt forces the attacker to attack each hash separately.

Summary

  • Store passwords with a slow, salted, one-way algorithm; never encrypt or use fast digests.
  • Use DelegatingPasswordEncoder so algorithm ids travel with the hash and migrations are painless.
  • Tune the cost so one check takes about 100 to 500 ms.
  • Upgrade legacy hashes when users log in.
  • Combine hashing with good policy: long passphrases, breach checks, MFA.

Next: Login throttling and rate limiting