I am using spring security using BCryptPasswordEncoder. Now for change password what I need to do is to compare Existing Password provided by user with DB value.
But since salt is generated dynamically by BCryptPasswordEncoder
, every time I get different hashed value from below method and not necessarily it would match with my DB value.
public static String encodePassword(String password) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(password);
return hashedPassword;
}
What's the remedy for this problem? can I identify salt used for my DB field and use the same salt in above method ?
Use the matches
method on the PasswordEncoder
interface to check whether the password is valid, rather than encoding it again and comparing with the existing hash.
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String existingPassword = ... // Password entered by user
String dbPassword = ... // Load hashed DB password
if (passwordEncoder.matches(existingPassword, dbPassword)) {
// Encode new password and store it
} else {
// Report error
}