我想使用 bcrypt 和 Spring security 对用户密码进行哈希处理和加盐。
这是我的用户模型(我删除了无用的代码):
public class User {
private Integer id;
private String email;
private String hashedPassword;
private String salt; //I want to use this salt.
private Boolean enabled;
//Getters & Setters
}
以下是我如何使用自己的盐创建新用户:
@Transactional
public User create(String email, String password) {
User user = new User();
user.setSalt(BCrypt.gensalt(12)); //Generate salt
user.setEnabled(true);
user.setEmail(email);
user.setHashedPassword(BCrypt.hashpw(password, user.getSalt()));
return dao.persist(user);
}
这是 Spring 配置:
<beans:bean id="userService" class="com.mycompany.service.UserService"/>
<beans:bean id="myCustomUserDetailService" class="com.mycompany.service.MyCustomUserDetailService"/>
<beans:bean id="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
<beans:bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">
<beans:property name="userPropertyToUse" value="salt"/>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="myCustomUserDetailService">
<password-encoder ref="bcryptEncoder">
<salt-source ref="saltSource"/>
</password-encoder>
</authentication-provider>
</authentication-manager>
在此配置中,我指出PasswordEncoder
必须使用User.getSalt()
;
问题:我收到以下错误 500:
Salt value must be null when used with crypto module PasswordEncoder.
查看 stackoverflow 后,似乎盐必须为 null,因为 BCryptPasswordEncoder 使用它自己的 SaltSource。
- 有没有办法使用my
SaltSource
?或者 - 哪种可靠的算法允许我的
SaltSource
?
谢谢。
最佳答案
第一个问题的答案:
BCryptPasswordEncoder 有 hardcoded盐源 ( Bcrypt.getsalt ).
因此无法强制 BCryptPasswordEncoder 使用其他盐源。
尽管如此,您可以尝试将其子类化,并添加自定义盐属性。
关于java - 具有 Spring 安全性的自定义密码盐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26744359/