Why Password Hashing Is Needed
Storing passwords in plain text is dangerous.
If a database is leaked, attackers immediately get all user passwords.
So instead of storing passwords, we store hashed values.
A hash is a one-way mathematical function that converts a password into an unreadable string.
You cannot reverse it to get the original password.
mypassword → $2a$10$Hf7sd8KJH...3fd2
How Login Works with Hashed Passwords
- When a user logs in:
- User enters password
- Spring Security hashes the entered password
- It compares the new hash with the stored hash in DB
- If both match → login succeeds
- The original password is never stored or compared
PasswordEncoder in Spring Security
Spring Security uses an interface called:
PasswordEncoder
It has two main methods:
String encode(CharSequence rawPassword);
boolean matches(CharSequence rawPassword, String encodedPassword);
Best Algorithm: BCrypt
Spring recommends BCrypt because it:
- Uses salt automatically
- Is slow (harder for hackers to brute force)
- Is adaptive (can be made stronger over time)
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
Why Salting Matters
Without salt:
password → hash
With salt:
password + randomValue → hash
Even if two users have the same password, their hashes will be different.
BCrypt handles salting automatically.
“A salt is a random value added to a password before hashing to make each hash unique and protect against rainbow-table and brute-force attacks.”
How Salt Works
- User creates a password
- System generates a random salt
- Password + salt are hashed together
- Both salt and hash are stored in the database
Example:
$2a$10$WERTY...SALT...HASH
When user logs in:
- Spring Security extracts the salt from the stored hash
- It hashes the entered password using that same salt
- If hashes match → login succeeds
Top comments (0)