Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
413 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...