AOUADI Slim
AOUADI Slim

Reputation: 457

Hash a password with $2y$ in java

i am having issues with hashing passwords in java so when i try to log in and write my password i want to get that written password hash it using $2y$ as the same format in my database because that it what the FOSBundle is using as encryption methode the BCrypt but instead i get a hashed password which starts with $2a$ instead of $2y$ so i can't compare them is there anyway to change that $2a$ hash into $2y$ hash ?

My function :

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");
      }
    }
  }
}

he can't find the user i am looking for because the hashed password i passed to him " hashed2 " is not the same in my database because in my database it stars with $2y$ and this hash methode give a $2a$ hashed password

Upvotes: 3

Views: 5273

Answers (1)

Karol Dowbecki
Karol Dowbecki

Reputation: 44932

Based on BCrypt wiki the prefix $2a$, $2y$ and $2b$ are used to store the algorithm version. Although $2y$ fixed a bug in previous implementation this fix seems to be limited to 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.

Since it looks like you are using JBCrypt you will always get $2a$ version. Latest version 0.4 definitely uses it.

You can try comparing the hashed password without the version prefix. I never had to compare PHP and Java BCrypt implementation so I've no idea if this will work. In your code you can do following:

// 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"); 
}

Upvotes: 2

Related Questions