Tania Marinova
Tania Marinova

Reputation: 1898

When I test my program that hashes password using SecretKeyFactory it always returns passwords are not the same

In my code I try to hash a password using PBKDF2WithHmacSHA1 instance of SecretFactory. (before that you will see that O generate random salt)

But when I try to test the program in a simple java project with two passwords that are the same it gives me a response that they are not the same. What may be the reason?

tatic byte[] salt = new byte[16];
public static String password = "peachy";
public static String newpassword = "peachy";

public static byte []storedpassword;

public static void main(String[] args) throws Exception {

    generateSalt();
    System.out.println("salt1:"+salt.toString());
    storedpassword=hash(password,salt);
    System.out.println(storedpassword.toString());
    boolean answer = check(newpassword, storedpassword);
    System.out.println(answer);


}
public static void generateSalt()
{
     Random randomno = new Random();
     randomno.nextBytes(salt);

}

private static byte[] hash(String password, byte[] salt) throws Exception   
{  
    SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);

    return f.generateSecret(spec).getEncoded();

}
public static boolean check(String givenPassword, byte[] storedPassword)
   throws Exception{
        System.out.println("salt2:"+salt.toString());
        byte[] hashOfInput = hash(givenPassword,salt);
        System.out.println(hashOfInput.toString());
        return hashOfInput.equals(storedPassword);
   }

}

Upvotes: 0

Views: 315

Answers (1)

Kyle
Kyle

Reputation: 4278

 return Arrays.equals(hashOfInput,storedPassword);

You can't compare the byte[] using the .equals() method, use the code above. The reason why you cannot compare them using the .equals() method is because the byte[]'s equals() method tests for reference equality, not logical (every byte is the same) equality. This is because byte[] inherits from Object, and that is how the Object class's equals() method is implemented.

For more information, see this question and the answer by Jon Skeet.

Upvotes: 3

Related Questions