PasswordEncoder in Spring Security
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?
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:
{bcrypt}$2a$10$jxjsbqw3MwzNjsu6BqUrSe9kcuDbc5cus7EjJSy5iPZ95YHxqAX5m
{id} encoded value produced by that algorithm
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:
| Ids | Status |
|---|---|
bcrypt | Default for new passwords |
argon2@SpringSecurity_v5_8, scrypt@SpringSecurity_v5_8, pbkdf2@SpringSecurity_v5_8 | Modern, with current recommended parameters (need extra libraries for Argon2 and SCrypt) |
argon2, scrypt, pbkdf2 | Same algorithms with older default parameters |
SHA-256, SHA-1, MD5, MD4, sha256, ldap | Legacy, accepted only so old hashes can be checked and upgraded |
noop | Plain 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);
}
}
package com.javabytechie.loyalty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error").permitAll()
.anyRequest().hasRole("CUSTOMER"))
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
// bcrypt for new hashes, plus the ability to verify legacy {SHA-256} hashes
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
package com.javabytechie.loyalty;
import java.security.Principal;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PointsController {
@GetMapping("/api/points")
public Map<String, Object> points(Principal principal) {
return Map.of("customer", principal.getName(), "points", 1240);
}
}
package com.javabytechie.loyalty;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LoyaltyApplication {
public static void main(String[] args) {
SpringApplication.run(LoyaltyApplication.class, args);
}
}
5. Step-by-Step Code Explanation
- The
PasswordEncoderbean is aDelegatingPasswordEncoderfromPasswordEncoderFactories. It encodes with BCrypt and can still check the imported{SHA-256}hash. - Recreating the legacy data. The constructor uses the deprecated
MessageDigestPasswordEncoderonly to produce the kind of hash the old system stored. Production code should never create such hashes. - Two interfaces, one bean.
CustomerAccountServiceimplements bothUserDetailsService(load the user) andUserDetailsPasswordService(save an upgraded hash). Spring Security detects both and wires them into itsDaoAuthenticationProvider. - The upgrade. On Ravi's first successful login,
matchessucceeds with the SHA-256 hash,upgradeEncodingreturns true, andupdatePasswordreceives 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:
$ 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:
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
| Algorithm | Strength | Notes |
|---|---|---|
| BCrypt | Good, widely supported | Default in Spring Security; uses only the first 72 bytes of a password. See BCrypt password encoding. |
| Argon2id | Strongest against GPU attacks (memory-hard) | Recommended first choice by OWASP; needs the Bouncy Castle library |
| SCrypt | Memory-hard | Needs Bouncy Castle |
| PBKDF2 | Acceptable with a high iteration count | Choose it when FIPS-140 compliance is required |
| MD5, SHA-1, SHA-256 | Unsuitable for passwords | Fast hashes; use only to verify and upgrade old data |
8. Common Mistakes and Best Practices
- Using
NoOpPasswordEncoderoutside a demo. It stores plain text. - Declaring a bare
BCryptPasswordEncoderbean in a system with old hashes. It cannot read{id}prefixes or other algorithms. UseDelegatingPasswordEncoderunless 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.
updatePasswordreceives an encoded value; encoding it again locks the user out. - Comparing hashes yourself. Always call
matches; a freshencodeproduces a different salt and never equals the stored value.
9. Summary
PasswordEncoderhasencodefor new passwords,matchesfor logins andupgradeEncodingfor outdated hashes.- Password hashes are one-way, salted and deliberately slow; they are not encryption.
DelegatingPasswordEncoderstores{id}in front of each hash, encodes new passwords with BCrypt and still verifies older formats.- With a
UserDetailsPasswordServicebean, 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
Frequently Asked Questions (FAQ)
Q1. What is the difference between encode() and matches()?
encode creates a new salted hash for storage. matches checks a raw password against an existing hash. Because each encode call uses a new salt, you must never compare two encoded values directly.
Q2. Why does Spring Security store passwords with a {bcrypt} prefix?
The prefix records which algorithm produced the hash. DelegatingPasswordEncoder uses it to pick the right encoder, which lets one system verify old and new formats while it migrates users.
Q3. How do I migrate existing password hashes to BCrypt without a password reset?
Use DelegatingPasswordEncoder, prefix the old hashes with their algorithm id, and provide a UserDetailsPasswordService bean. Each user's hash is re-encoded with BCrypt at their next successful login.
Q4. Is password hashing the same as encryption?
No. Encryption is reversible with a key. A password hash is one-way: the system can only check whether a submitted password produces the same hash.
Q5. What happens if a stored password has no {id} prefix?
DelegatingPasswordEncoder.matches throws IllegalArgumentException because it cannot tell which algorithm to use, unless you configure a default encoder for unprefixed values.