Summary
This postmortem analyzes whether a Spring Boot PasswordEncoder should be reused globally or instantiated repeatedly. The short answer: yes, reuse it. Creating new instances offers no security benefit and introduces unnecessary overhead.
Root Cause
The confusion stems from misunderstanding how BCryptPasswordEncoder works and whether it maintains internal state. Developers often assume cryptographic components must be recreated for safety, but:
- BCryptPasswordEncoder is stateless
- It does not store salts internally
- Each call to
encode()generates a new random salt - Re-instantiating it provides zero additional security
Why This Happens in Real Systems
Real systems often run into this question because:
- Developers fear accidental reuse of salts
- Cryptographic APIs are often opaque
- Some libraries do require fresh instances, causing general caution
- BCrypt’s cost factor makes people think it might “warm up” or cache state
Real-World Impact
Misunderstanding this leads to:
- Unnecessary object creation
- Performance degradation under high authentication load
- Inconsistent code patterns across services
- Over-engineering without security gain
Example or Code (if necessary and relevant)
A globally reused encoder:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(16);
}
Usage:
String hashed = passwordEncoder.encode(rawPassword);
How Senior Engineers Fix It
Senior engineers typically:
- Define a single
PasswordEncoderbean and inject it everywhere - Avoid per-request instantiation
- Rely on Spring Security’s built-in configuration
- Understand that BCrypt’s randomness comes from per-call salt generation, not from the encoder instance
They focus on:
- Correct cost factor
- Consistent configuration
- Avoiding unnecessary CPU overhead
Why Juniors Miss It
Juniors often miss this because:
- They assume cryptographic classes must be ephemeral
- They misunderstand how BCrypt generates salts
- They equate “security” with “create new objects”
- They lack experience with stateless vs. stateful components
- They follow examples without understanding the underlying mechanism
Key takeaway:
Reusing a single PasswordEncoder instance is the correct, secure, and efficient approach in Spring Boot.