00:00

PasswordEncoder in Spring Security

Last updated:

PasswordEncoder is the Spring Security interface that turns a password into a value that is safe to store, and later checks a login attempt against that stored value. It is the reason a Spring application never needs to keep, or even see again, the password a user chose.

This tutorial explains the three methods of PasswordEncoder, the {id} storage format used by DelegatingPasswordEncoder, and how to choose an algorithm. The example then solves a common real problem: a shop has imported customers from an old system with weak SHA-256 hashes, and Spring Security replaces each one with a BCrypt hash the next time that customer logs in.

1. What Is PasswordEncoder?

PasswordEncoder.java (simplified)
public interface PasswordEncoder {
    String encode(CharSequence rawPassword);                        // hash a new password
    boolean matches(CharSequence rawPassword, String encodedPassword); // check a login attempt
    default boolean upgradeEncoding(String encodedPassword) {      // should this hash be replaced?
        return false;
    }
}

encode is called when a password is created or changed, and its result is what you store. matches is called at every login: it hashes the attempt in the same way and compares the results. upgradeEncoding tells Spring Security that a stored hash is outdated and should be re-encoded.

Despite the name, an encoder does not encrypt. Encryption can be reversed with a key; a password hash is designed to be one-way. A good password hash is also salted (a random value per password, so equal passwords get different hashes) and deliberately slow, so guessing millions of passwords from a stolen database is expensive.

2. Why PasswordEncoder Is Needed

Databases leak through backups, logs, SQL injection and insider access. If passwords are stored as plain text or with a fast, unsalted hash such as MD5 or SHA-256, attackers recover most of them within hours, and because people reuse passwords, the damage spreads to other sites.

Spring Security requires a PasswordEncoder for username and password logins, which makes the safe path the default. DaoAuthenticationProvider calls matches for you, so application code never compares passwords itself.

3. How DelegatingPasswordEncoder Works

Algorithms age. A hash that was acceptable ten years ago is weak today, but you cannot re-hash stored passwords without the original passwords. DelegatingPasswordEncoder solves this by storing the algorithm name in front of each hash:

Stored password format
{bcrypt}$2a$10$jxjsbqw3MwzNjsu6BqUrSe9kcuDbc5cus7EjJSy5iPZ95YHxqAX5m
{id}    encoded value produced by that algorithm
DelegatingPasswordEncoder choosing an encoder by prefixFor matches, DelegatingPasswordEncoder reads the id in braces and passes the rest to the matching encoder, such as BCrypt or legacy SHA-256. New passwords are always encoded with the default id, bcrypt. Stored hash {SHA-256}{salt}a3f9... DelegatingPasswordEncoder reads the {id} prefix BCryptPasswordEncoder id: bcrypt (default) MessageDigestPasswordEncoder id: SHA-256 (legacy) Argon2, SCrypt, Pbkdf2 ids: argon2, scrypt, pbkdf2
Figure 1: the prefix selects the algorithm for checking; new hashes always use the default (bcrypt).

PasswordEncoderFactories.createDelegatingPasswordEncoder() builds an instance whose default is bcrypt and which can still verify many older formats. In Spring Security 7.1.2 it recognises these ids:

IdsStatus
bcryptDefault for new passwords
argon2@SpringSecurity_v5_8, scrypt@SpringSecurity_v5_8, pbkdf2@SpringSecurity_v5_8Modern, with current recommended parameters (need extra libraries for Argon2 and SCrypt)
argon2, scrypt, pbkdf2Same algorithms with older default parameters
SHA-256, SHA-1, MD5, MD4, sha256, ldapLegacy, accepted only so old hashes can be checked and upgraded
noopPlain text; acceptable only in throwaway demos

A stored value without any {id} prefix makes matches throw IllegalArgumentException, because the encoder cannot know which algorithm to use.

3.1 Automatic Upgrade at Login

DelegatingPasswordEncoder.upgradeEncoding returns true for any hash whose id is not the default. During a successful login, DaoAuthenticationProvider checks this. If the answer is true and a UserDetailsPasswordService bean exists, it encodes the password the user just typed with the default algorithm and calls updatePassword to save the new hash. Each user is migrated the next time they log in, with no password reset.

4. A Complete Example: Migrating Legacy Hashes in a Loyalty App

A shop has moved its loyalty programme to Spring Boot. Customer Ravi was imported from the old system, which stored salted SHA-256 digests. Customer Zoya signed up after the move and already has a BCrypt hash. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2; CustomerAccountService keeps hashes in a map in place of a database table.

package com.javabytechie.loyalty;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.MessageDigestPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class CustomerAccountService implements UserDetailsService, UserDetailsPasswordService {

    private static final Logger log = LoggerFactory.getLogger(CustomerAccountService.class);
    private final Map<String, String> storedHashes = new ConcurrentHashMap<>();

    @SuppressWarnings("deprecation")  // the legacy encoder is used only to recreate old data
    public CustomerAccountService(PasswordEncoder encoder) {
        PasswordEncoder legacy = new DelegatingPasswordEncoder("SHA-256",
            Map.of("SHA-256", new MessageDigestPasswordEncoder("SHA-256")));
        storedHashes.put("ravi", legacy.encode("ravi-pass"));   // imported from the old system
        storedHashes.put("zoya", encoder.encode("zoya-pass"));  // signed up after the move
        storedHashes.forEach((user, hash) -> log.info("Imported {} with {}", user, prefix(hash)));
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String hash = storedHashes.get(username);
        if (hash == null) {
            throw new UsernameNotFoundException("Unknown customer");
        }
        return User.withUsername(username).password(hash).roles("CUSTOMER").build();
    }

    // Called by DaoAuthenticationProvider after a successful login with an outdated hash
    @Override
    public UserDetails updatePassword(UserDetails user, String newEncodedPassword) {
        String old = storedHashes.put(user.getUsername(), newEncodedPassword);
        log.info("Upgraded {}: {} -> {}", user.getUsername(), prefix(old), prefix(newEncodedPassword));
        return User.withUserDetails(user).password(newEncodedPassword).build();
    }

    private static String prefix(String hash) {
        return hash.substring(0, hash.indexOf('}') + 1);
    }
}

5. Step-by-Step Code Explanation

  1. The PasswordEncoder bean is a DelegatingPasswordEncoder from PasswordEncoderFactories. It encodes with BCrypt and can still check the imported {SHA-256} hash.
  2. Recreating the legacy data. The constructor uses the deprecated MessageDigestPasswordEncoder only to produce the kind of hash the old system stored. Production code should never create such hashes.
  3. Two interfaces, one bean. CustomerAccountService implements both UserDetailsService (load the user) and UserDetailsPasswordService (save an upgraded hash). Spring Security detects both and wires them into its DaoAuthenticationProvider.
  4. The upgrade. On Ravi's first successful login, matches succeeds with the SHA-256 hash, upgradeEncoding returns true, and updatePassword receives a fresh {bcrypt} hash of the password he just typed. The value passed in is already encoded; store it as it is.

6. Expected Output

Ravi logs in twice, then Zoya logs in once. All three requests succeed:

Terminal
$ curl -u ravi:ravi-pass localhost:8080/api/points
HTTP/1.1 200
{"points":1240,"customer":"ravi"}

$ curl -u ravi:ravi-pass localhost:8080/api/points
HTTP/1.1 200
{"points":1240,"customer":"ravi"}

$ curl -u zoya:zoya-pass localhost:8080/api/points
HTTP/1.1 200
{"points":1240,"customer":"zoya"}

The interesting part is in the application log, filtered to the lines written by CustomerAccountService:

Terminal
Imported zoya with {bcrypt}
Imported ravi with {SHA-256}
Upgraded ravi: {SHA-256} -> {bcrypt}

Ravi's hash was upgraded during his first login only; his second login was checked against the new BCrypt hash. Zoya already had a BCrypt hash, so nothing changed for her.

7. Choosing an Algorithm

AlgorithmStrengthNotes
BCryptGood, widely supportedDefault in Spring Security; uses only the first 72 bytes of a password. See BCrypt password encoding.
Argon2idStrongest against GPU attacks (memory-hard)Recommended first choice by OWASP; needs the Bouncy Castle library
SCryptMemory-hardNeeds Bouncy Castle
PBKDF2Acceptable with a high iteration countChoose it when FIPS-140 compliance is required
MD5, SHA-1, SHA-256Unsuitable for passwordsFast hashes; use only to verify and upgrade old data

8. Common Mistakes and Best Practices

  • Using NoOpPasswordEncoder outside a demo. It stores plain text.
  • Declaring a bare BCryptPasswordEncoder bean in a system with old hashes. It cannot read {id} prefixes or other algorithms. Use DelegatingPasswordEncoder unless you are certain every hash is BCrypt.
  • Storing hashes without the {id} prefix. The delegating encoder rejects them. Prefix existing values once with a database update, for example {bcrypt} in front of plain BCrypt hashes.
  • Encoding the password twice. updatePassword receives an encoded value; encoding it again locks the user out.
  • Comparing hashes yourself. Always call matches; a fresh encode produces a different salt and never equals the stored value.

9. Summary

  • PasswordEncoder has encode for new passwords, matches for logins and upgradeEncoding for outdated hashes.
  • Password hashes are one-way, salted and deliberately slow; they are not encryption.
  • DelegatingPasswordEncoder stores {id} in front of each hash, encodes new passwords with BCrypt and still verifies older formats.
  • With a UserDetailsPasswordService bean, outdated hashes are replaced automatically at the next successful login.
  • Never store plain text or fast hashes such as MD5 and SHA-256 for passwords.

10. References