java - 使用盐存储和验证散列密码

标签 java hash

我模拟存储密码哈希并在登录过程中验证它。

我有一个名为 hashPassword(String password) 的方法来获取字符串密码并返回其添加盐的哈希值。

我选择 salt 为静态值,在本示例中,我为密码选择相同的值 (hello123)

public class T1 {

public static void main(String[] args) {
    String userDefinedPassword = "hello123";
    String hashedPassToStoreInDB = String.valueOf(hashPassword(userDefinedPassword));
    System.out.println("what stores in DB: " + hashedPassToStoreInDB);
    // store in database

    //Password Verify
    String inputPassword = "hello123";
    String hashedInputPassword = String.valueOf(hashPassword(inputPassword));
    System.out.println("Users hashed password: " + hashedInputPassword);

    if (hashedPassToStoreInDB.equals(hashedInputPassword)) {
        System.out.println("Correct");
    } else {
        System.out.println("Incorrect");
    }
}

private static byte[] hashPassword(String password) {
    byte[] salt = new byte[16];
    byte[] hash = null;
    for (int i = 0; i < 16; i++) {
        salt[i] = (byte) i;
    }
    try {
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
        SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        hash = f.generateSecret(spec).getEncoded();

    } catch (NoSuchAlgorithmException nsale) {
        nsale.printStackTrace();

    } catch (InvalidKeySpecException ikse) {
        ikse.printStackTrace();
    }
    return hash;
}
}

但结果是:

what stores in DB: [B@219c9a58
Users hashed password: [B@305918a5
Incorrect

为什么这两个值不相同?

我的代码有什么问题吗?

最佳答案

问题出在这里:

String hashedPassToStoreInDB = String.valueOf(hashPassword(userDefinedPassword));

这里:

String hashedInputPassword = String.valueOf(hashPassword(inputPassword));

您正在从 hashPassword 方法返回的 byte[] 创建一个 String,但使用了错误的方法。由于 String#valueOf 方法中的 byte[] 没有重载,因此它结束调用 String#valueOf(Object obj)它将在内部使用Object#toString,而数组的字符串表示形式本身是没有意义的。

使用new String(byte[] byteArray)相反。

String hashedPassToStoreInDB = new String(hashPassword(userDefinedPassword));
//...
String hashedInputPassword = new String(hashPassword(inputPassword));

关于java - 使用盐存储和验证散列密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27843642/

相关文章:

c++ - std::unordered_set 指针

data-structures - Clojure:如何使用整数序列而不是字母序列来实现 trie 树?

python - Python中lambda函数的哈希

java - 正则表达式非空白且不包含 <

java - 传递引用改变java中的代码

Java:实现简单的方程

java - 有没有办法从 xml 中定义的一个 TextView 制作一个 TextView 的 ArrayList ?

perl - 将散列传递给子例程

java - 控制Android上的WIFI\蜂窝数据更新频率

c++ - 使用 lambda 做定义哈希函数抛出异常