java / beginner
Snippet
Hashing User Passwords with BCryptPasswordEncoder
Storing passwords in plain text is a severe vulnerability. Spring Security provides BCryptPasswordEncoder to securely hash passwords with automatic salting. The encode() method transforms cleartext into a secure hash, while matches() validates user input against stored hashes without decrypting them.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.stereotype.Service;@Servicepublic class UserService {private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();public String registerUser(String rawPassword) {return passwordEncoder.encode(rawPassword);}public boolean verifyPassword(String rawPassword, String encodedPassword) {return passwordEncoder.matches(rawPassword, encodedPassword);}}
spring
Breakdown
1
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
Instantiates the BCrypt encoder utility for hashing and checking passwords.
2
return passwordEncoder.encode(rawPassword);
Hashes the plaintext password using the BCrypt hashing algorithm with a random salt.
3
return passwordEncoder.matches(rawPassword, encodedPassword);
Verifies whether the raw password matches the previously hashed password.