0

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

}
4

1 回答 1

3
 return Arrays.equals(hashOfInput,storedPassword);

你不能比较byte[]使用.equals()方法,使用上面的代码。您无法使用 .equals() 方法比较它们的原因是因为byte[]'s equals() 方法测试引用相等,而不是逻辑(每个字节都相同)相等。这是因为byte[]继承自Object,这就是Objectequals()方法的实现方式。

有关更多信息,请参阅此问题和 Jon Skeet 的答案。

于 2013-04-24T06:27:28.837 回答