gpt4 book ai didi

java - 当我测试使用 SecretKeyFactory 对密码进行哈希处理的程序时,它总是返回密码不相同

转载 作者:行者123 更新时间:2023-12-01 23:52:02 26 4
gpt4 key购买 nike

在我的代码中,我尝试使用 SecretFactoryPBKDF2WithHmacSHA1 实例对密码进行哈希处理。(在此之前你会看到 O 生成随机盐)

但是当我尝试在一个简单的 java 项目中使用两个相同的密码测试该程序时,它给我的答复是它们不相同。可能是什么原因?

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

}

最佳答案

 return Arrays.equals(hashOfInput,storedPassword);

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

有关详细信息,请参阅 this question以及乔恩·斯基特的回答。

关于java - 当我测试使用 SecretKeyFactory 对密码进行哈希处理的程序时,它总是返回密码不相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16184389/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com