【问题标题】:Using BCrypt password hashing with Spring Security Grails plugin将 BCrypt 密码散列与 Spring Security Grails 插件一起使用
【发布时间】:2014-04-16 02:01:44
【问题描述】:

我正在尝试在使用 Spring Security 插件的 Grails 应用程序中使用 BCrypt 密码散列。我已通过将以下内容添加到 Config.groovy

来启用 BCrypt
grails.plugins.springsecurity.password.algorithm = 'bcrypt'

我定义了以下编解码器来简化使用 BCrypt 对密码进行编码:

public class PasswordCodec {

    // it doesn't seem to be possible to dependency-inject codecs, so lookup the bean ourselves
    @Lazy
    private static PasswordEncoder passwordEncoder = Holders.grailsApplication.mainContext.getBean('passwordEncoder')

    static encode = { str ->
        passwordEncoder.encodePassword(str.toString(), null)
    }
}

当我在开发模式下启动应用程序时,数据库会使用几个帐户进行引导(每个帐户都有相同的密码,例如

3.times { i ->
    def username = "user$i"
    def password = "secret".encodeAsPassword()

    new User(username: username, password: password).save()
    // also assign the user a role
}

如果我查看数据库,我发现每个用户密码的编码值都不同!因此,当用户尝试登录并输入“secret”密码时,BCrypt 编码的密码值与数据库中保存的值不匹配也就不足为奇了,因为字符串的 BCrypt 编码值似乎发生了某种变化随着时间的推移。

显然我在这里做错了什么,但我不知道是什么?

【问题讨论】:

  • 我假设您的用户域没有处理密码编码的典型 s2 快速入门代码?
  • 另外,我认为现在默认启用加盐,它基于用户名,因此每个密码都有不同的加盐:grails-plugins.github.io/grails-spring-security-core/docs/… ...假设您仍然有生成的 s2 快速入门代码地点。
  • @JoshuaMoore 不,我没有在 User 类本身中进行任何密码编码(我没有使用 s2-quickstart)
  • @JoshuaMoore 我自己在PasswordCodec 中对密码进行编码,并将null 传递给salt 参数
  • 那么完全奇怪。也许伯特会突然出现并提供一些帮助。我看不出你所做的事情有什么明显的错误,它模仿了我们过去在春天不得不做的事情。

标签: grails spring-security grails-plugin bcrypt


【解决方案1】:

在输入相同的情况下,密码哈希通常是相同的(偶尔输入不同)。但是 bcrypt 和其他人每次都会生成不同的哈希值。不过这不是问题,因为PasswordEncoder 接口既有String encodePassword(String rawPass, Object salt) 方法来生成哈希,也有boolean isPasswordValid(String encPass, String rawPass, Object salt) 方法来验证它们。

对于像 MD5、SHA-1 等更简单的哈希,验证过程只是重新编码明文密码并检查它是否与存储的哈希值相同。使用 bcrypt 的过程要复杂得多,但最终结果是相同的 - 它不检查 相等,而是检查它们是否 等价。因此,如果您对相同的密码进行两次哈希处理并将它们与isPasswordValid 进行比较,它将返回true

【讨论】:

  • 这个弃用的 PasswordEncoder 与这个 PasswordEncoder 有何不同,除了在前一种情况下由用户提供盐? (脱离问题的上下文)
  • 我没有仔细研究这些差异,但我正计划迁移到更新的界面。
  • @BurtBeckwith 我完全错过了isPasswordValid 方法,非常感谢
猜你喜欢
  • 2012-05-01
  • 2016-01-01
  • 2012-04-10
  • 2016-05-24
  • 2015-08-10
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 2019-10-26
相关资源
最近更新 更多