Spring Security - BcryptPasswordEncoder [英] Spring Security - BcryptPasswordEncoder

查看:962
本文介绍了Spring Security - BcryptPasswordEncoder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我们的应用程序中使用Spring安全性,并希望使用存储在数据库中的密码验证用户输入以获取更改密码选项。

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.

密码存储为在DB中跟随。

The password is stored as follows in DB.

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

此处用户输入的密码使用上述逻辑进行编码并存储在数据库中。现在我只是想从用户那里获取更改密码的密码。从用户获取密码后,我使用上述逻辑进行编码,并尝试与DB进行比较。即使我使用相同的编码逻辑,编码值似乎也不同。

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.

我的配置来自 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.

推荐答案


编码值似乎有所不同,即使我对
使用相同的逻辑编码。

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

Bcrypt算法使用内置的salt值,每次都不同。所以,是的,即使是相同的明文相同的编码过程也会生成不同的密文

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

不要编码原始密码。假设 rawPassword 是客户端提供给您的密码, encodedPassword 是数据库中编码的存储密码。然后,使用,而不是编码 rawPassword 并使用 String#equals 比较结果。 PasswordEncoder#matches method:

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

这篇关于Spring Security - BcryptPasswordEncoder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆