在 java 中用 $2y$ 散列密码

Hash a password with $2y$ in java

我在 java 中遇到密码散列问题,所以当我尝试登录并写入密码时,我想使用 $2y$ 将写入的密码散列为与我的数据库中相同的格式,因为它是 FOSBundle 使用的加密方法 BCrypt 但我得到一个以 $2a$ 而不是 $2y$ 开头的散列密码,所以我无法比较它们 无论如何要将 $2a$ 散列更改为 $2y $哈希?

我的函数:

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 = "y$" + 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:

In June 2011, a bug was discovered in crypt_blowfish, a PHP implementation of BCrypt.

...

Nobody else, including canonical OpenBSD, adopted the idea of 2x/2y. This version marker change was limited to crypt_blowfish.

因为看起来您正在使用 JBCrypt,所以您将始终获得 $2a$ 版本。最新版本0.4肯定用它。

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

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