我在使用Java哈希密码时遇到问题,因此当我尝试登录并写入密码时,我想使用$ 2y $作为数据库中相同的格式来获取该书面密码哈希值,因为它使用的是FOSBundle加密methode BCrypt,但是我得到了一个以$ 2a $而不是$ 2y $开头的哈希密码,因此我无法比较它们是否可以将$ 2a $哈希更改为$ 2y $ hash?

我的职能:

public void CheckLogin(String username,String password) throws SQLException{

  String requete = "Select * from user WHERE username ='"+username+"';";
  ste = con.createStatement();
  res = ste.executeQuery(requete);

  while(res.next()) {
    if (res.getString(2).equals(username)) {
      System.out.println("Password FOS ="+res.getString(8));

      String hashed2 = BCrypt.hashpw(password, BCrypt.gensalt(12));
      hashed2 = "$2y$" + hashed2.substring(4);
      System.out.println("HASHED PASSWORD =" + hashed2);

      if (BCrypt.checkpw(res.getString(8),hashed2)) {
        System.out.println("It matches");
      } else {
        System.out.println("It does not match");
      }
    }
  }
}

他找不到我要寻找的用户,因为我传递给他的哈希密码“hashed2”在我的数据库中不一样,因为在我的数据库中它以$ 2y $开头,并且此哈希方法提供了$ 2a $哈希密码

最佳答案

基于BCrypt wiki,前缀$ 2a $,$ 2y $和$ 2b $用于存储算法版本。尽管$ 2y $修复了先前实现中的一个错误,但此修复似乎仅限于PHP:

2011年6月,在BCrypt的PHP实现crypt_blowfish中发现了一个错误。

...

其他人,包括规范的OpenBSD,都没有采用2x / 2y的想法。
此版本标记更改仅限于crypt_blowfish。

由于您似乎正在使用JBCrypt,因此您将始终获得$ 2a $版本。最新版本0.4肯定会使用它。

您可以尝试比较没有版本前缀的哈希密码。我从来不需要比较PHP和Java BCrypt的实现,所以我不知道这是否行得通。在您的代码中,您可以执行以下操作:

// JBCrypt requires version $2a, change the prefix
String hashed2 = "$2a" + res.getString(8).substring(3);
if (BCrypt.checkpw(password, hashed2)) {
  System.out.println("It matches");
}

07-27 13:37
查看更多