java - 具有 Spring 安全性的自定义密码盐

标签 java spring-security bcrypt

我想使用 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。

  1. 有没有办法使用my SaltSource?或者
  2. 哪种可靠的算法允许我的 SaltSource

谢谢。

最佳答案

第一个问题的答案:

BCryptPasswordEncoder 有 hardcoded盐源 ( Bcrypt.getsalt ).
因此无法强制 BCryptPasswordEncoder 使用其他盐源。
尽管如此,您可以尝试将其子类化,并添加自定义盐属性。

关于java - 具有 Spring 安全性的自定义密码盐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26744359/

相关文章:

java - 解决 Java 中的运行时依赖关系

java - 尝试构建示例 Red5 Secure 项目,但由于某些依赖项而失败

java - Spring security OAuth2 刷新 token - IllegalStateException,需要 UserDetailsS​​ervice

python - 如何从数据库中检索密码

javascript - 导出在 JavaScript 中如何工作。哈希未定义 bcryptjs

java - Android MediaMetadataRetriever 从大多数键返回空值

java - Android 运行时验证错误

将 cookie 设置为安全时,Spring Boot 无法登录

node.js - meteor 运行服务器获取错误: “Could not locate the bindings file. […]bcrypt[…]”

java - 用于 Java 的 GAE : Mail API