Reputation:
I'm using spring security for my application. When a user register first time, their passwords are encrypted with BCryptPasswordEncoder
.
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(password);
Now, in case of password changing, users enter their current password and I need to check if this current password is same against the encrypted password that is saved in the database.
I know it is not possible to generate two same encrypted hash with same string with BCryptPasswordEncoder
. So probably only way to compare the passwords if they are same is to get the original password that is saved in the database and compare with the current entered password.
So, is there any way to compare the passwords or to get the original password from the database saved hashed password?
Upvotes: 5
Views: 11820
Reputation: 3331
Yes, passwordEncoder
doesn't create same hashes, but you can compare them, and if it was generated from the same string, it will return true. Check my example:
public class Test {
public static void main(String[] args) {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
List<String> passwords = Arrays.asList(bCryptPasswordEncoder.encode("testPassword"),
bCryptPasswordEncoder.encode("testPassword"),
bCryptPasswordEncoder.encode("testPassword"),
bCryptPasswordEncoder.encode("testPassword"));
passwords.stream()
.filter(e -> bCryptPasswordEncoder.matches("testPassword", e))
.forEach(e -> System.out.println(true));
}
}
and i get 4 true
.
Upvotes: 2
Reputation: 13930
You need to only check the raw password against the encoded password in the db. For example,
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String p = bCryptPasswordEncoder.encode("SomeCoolPassword");
System.out.println(bCryptPasswordEncoder.matches("SomeCoolPassword", p));
Upvotes: 10