Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security - BcryptPasswordEncoder

I use Spring security in our Application and would like to validate user input with the password stored in the DB for the change password option.

The password is stored as follows in DB.

user.setPassword(new BCryptPasswordEncoder().encode("<userPassword>"));

Here the user entered password is encoded using the above logic and stored in the DB. Now I am just trying to get password from user for change password. After getting the password from user I encode using the above logic and try to compare with the DB. The encoded value seems to be different even I use the same logic for encoding.

My configuration from WebSecurityConfig:

@Autowired
public void configAuthentication(final AuthenticationManagerBuilder auth) throws Exception {

    auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());

}

I am not sure what is wrong with comparison.

like image 953
Udaya Vani Avatar asked Oct 18 '25 19:10

Udaya Vani


1 Answers

The encoded value seems to be different even I use the same logic for encoding.

Bcrypt algorithm uses a built-in salt value which is different each time. So, yes even for the same Clear Text same encoding process would generate different Cipher Texts.

After getting the password from user I encode using the above logic and try to compare with the DB

Do not encode the Raw Password. Suppose rawPassword is the password that client gave you and encodedPassword is the encoded stored password in the database. Then, instead of encoding the rawPassword and comparing the result using String#equals, use the PasswordEncoder#matches method:

PasswordEncoder passwordEnocder = new BCryptPasswordEncoder();
if (passwordEncoder.matches(rawPassword, encodedPassword)) {
    System.out.println("Matched!");
}
like image 137
Ali Dehghani Avatar answered Oct 20 '25 08:10

Ali Dehghani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!