【问题标题】:how to encode password with java in the same way that FOSUserBundle do如何以与 FOSUserBundle 相同的方式使用 java 对密码进行编码
【发布时间】:2018-03-24 18:03:59
【问题描述】:

我的数据库包含一个带有盐和密码列的用户表。 FOSUserBundle 使用 sha512

# app/config/security.yml
# ...

encoders:
    "FOS\UserBundle\Model\UserInterface": sha512

但这还不是全部,还有其他参数,如迭代次数、散列算法、成本、key_lenght、编码为 base64 等,我为这些参数拍摄了图像。

在我的 java 应用程序中,我需要以与 fosuser 相同的方式对输入密码进行编码... 我尝试使用 org.apache.commons.codec.digest.Crypt,我不知道如何修复像 fosuser 这样的参数

【问题讨论】:

    标签: java fosuserbundle encode salt


    【解决方案1】:

    Tomcat 有一个 API 级别的类 MessageDigestCredentialHandler,它可以完成您所描述的大部分工作。如果它不完全是您所需要的,那么它的源代码应该为您提供足够的指针来处理盐和迭代。

    首先它可以对密码进行编码或变异:

    MessageDigestCredentialHandler credentialHandler = new MessageDigestCredentialHandler();
    credentialHandler.setAlgorithm("SHA-512");
    credentialHandler.setSaltLength(16);
    credentialHandler.setIterations(5);
    credentialHandler.mutate("password");
    -> 5e0bdcf374c9c36b8930f23579ca0297$5$2c72f01ce132a1d070e67ad4730f3c26dba6d1dce7d32c6d8fe127afc952cd02308bdbdd45333e71f4dfed57bc5288ce501da30228907b9d49f5932896c025a2
    

    注意生成的字符串有一个盐,然后是 $,然后是迭代次数,另一个 $ 和(十六进制)编码密码。

    如果您的数据库中使用的是十六进制编码,那么您也可以匹配密码:

    MessageDigestCredentialHandler credentialHandler = new MessageDigestCredentialHandler();
    credentialHandler.setAlgorithm("SHA-512");
    String salt = "5e0bdcf374c9c36b8930f23579ca0297";
    int iterations = 5;
    String hexPassword = "2c72f01ce132a1d070e67ad4730f3c26dba6d1dce7d32c6d8fe127afc952cd02308bdbdd45333e71f4dfed57bc5288ce501da30228907b9d49f5932896c025a2";
    credentialHandler.matches("password", salt + "$" + iterations + "$" + hexPassword);
    -> true
    

    如果盐和/或密码是 base 64 编码的,还有更多工作要做,但请查看source for MessageDigestCredentialHandler.matches(String, String)。它也确实在那里处理 base64 编码,但从通读它看起来不支持多次迭代。我建议看看它是如何对十六进制编码路线进行迭代的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多