Concept Explanation
Databases leak. Assume yours will. The question is what an attacker gets when it does — a list of usable passwords, or a pile of useless hashes.
Hashing is one-way. You cannot reverse a hash to recover the password. To check a login, you hash the attempt and compare hashes.
Encryption is the wrong tool for passwords: it is reversible, which means the key exists somewhere, which means the attacker can get it too.
Why Not SHA-256?
SHA-256 is a fine hash and a terrible password hash. It is fast — a modern GPU computes billions per second, so a leaked table of SHA-256 hashes falls to brute force quickly.
Password hashes are deliberately slow. BCrypt takes a configurable amount of work:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12); // work factor: 2^12 rounds
}
Each increment of the work factor doubles the cost — for you and for the attacker. 10-12 is the usual range; higher when your hardware allows.
Salting
A salt is random data mixed into each hash. Two users with the password hunter2 get completely different hashes, so:
- Precomputed rainbow tables are useless.
- Cracking one password does not reveal the others.
BCrypt generates and embeds the salt automatically — it lives inside the hash string:
$2a$12$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy
| | \________________/\_____________________________/
alg cost salt hash
This is why you never need a separate salt column.
Registration and Login
@Service
public class AuthService {
private final UserRepository repo;
private final PasswordEncoder encoder;
public AuthService(UserRepository repo, PasswordEncoder encoder) {
this.repo = repo;
this.encoder = encoder;
}
public void register(String username, String rawPassword) {
User u = new User(username, encoder.encode(rawPassword)); // hash once
repo.save(u);
}
public boolean login(String username, String rawPassword) {
return repo.findByUsername(username)
.map(u -> encoder.matches(rawPassword, u.getPasswordHash()))
.orElse(false);
}
}
Note encoder.matches(raw, stored) — never encode(raw).equals(stored). A fresh salt would make that comparison fail every time.
Common Mistakes
- Storing plain text: Still happens. It is the difference between an embarrassing breach and a catastrophic one.
- Using MD5 or SHA-1: Both are cryptographically broken and far too fast.
- Comparing with
equals: Salted hashes never match literally. Always usematches. - Logging the raw password: One
log.debug(request)on a login DTO and every password lands in plain text in your log aggregator. - Capping password length at 8-10 characters: Length is the strongest defence. Allow long passphrases.
- Different errors for "no such user" and "wrong password": That difference tells an attacker which usernames exist. Return one generic message.
Best Practices
- BCrypt, Argon2, or scrypt — a deliberately slow, salted algorithm. Never a general-purpose hash.
- Never log or echo the raw password, not even in development.
- Rate-limit login attempts so brute force is impractical regardless of hash strength.
- Enforce HTTPS: A perfect hash is worthless if the password crosses the network in the clear.
Practice Exercises
- The Different Hashes: Hash the same password twice with
BCryptPasswordEncoderand observe that the outputs differ. Explain whymatchesstill succeeds. - The Cost Curve: Time hashing at work factors 4, 10, and 14. Plot how the cost grows.
- The Generic Message: Implement login so an unknown username and a wrong password produce identical responses.