3

我一直在尝试加密项目中的一些用户密码,但我似乎无法让它正常工作。我决定使用 SHA-256 算法,当我使用 Sha2(Example,256) 向 MySQL 引入密码时,它会在加密密码中添加两个零。在 Java 中,我使用它对程序中的文本进行哈希处理,但无法获得相同的结果。

    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest("ContrasenhaPassword".getBytes("UTF-8"));

        StringBuilder hexString = new StringBuilder();
        for (int i: hash) {
            hexString.append(Integer.toHexString(0XFF & i));
        }
        String Hashed = new String(hexString);
        System.out.println(hexString);
        System.out.println(Hashed);
        // Below, MySQL Output for SHA2('ContrasenhaPassword',256)
        System.out.println("d17bf0da90f56b8fc627bac6523ffd284aa0d82c870e1a0428274de048f49d78");
        System.out.println(Hashed.equals(hexString));
        } catch (Exception e) {
        e.printStackTrace();
        }

我得到的输出是:

        d17bf0da90f56b8fc627bac6523ffd284aa0d82c87e1a428274de048f49d78
        d17bf0da90f56b8fc627bac6523ffd284aa0d82c87e1a428274de048f49d78
        d17bf0da90f56b8fc627bac6523ffd284aa0d82c870e1a0428274de048f49d78
        false 
        BUILD SUCCESSFUL (total time: 0 seconds)

有任何想法吗?

4

2 回答 2

6

不同之处在于您如何打印它们:

for (int i: hash) {
  hexString.append(Integer.toHexString(0XFF & i));
}

省略前导零,因此有一个字节格式为“e”而不是“0e”。可能最简单的选择是

for (int i: hash) {
  hexString.append(String.format("%02x", i));
}

或者,如果你可以使用Guava,整个事情可以更简单地完成

Hashing.sha256().hashString("ContrasenhaPassword", Charsets.UTF_8).toString()

它在一行中为您提供(正确格式化的)十六进制编码的 SHA-256 哈希。

于 2013-06-07T22:57:21.390 回答
1

你不能添加缺少的零吗

for (int i: hash) 
{
    if(Integer.toHexString(0xFF & i).length() == 2)
        hexString.append(Integer.toHexString(0xFF & i));
    else
        hexString.append ( 0x00 + Integer.toHexString(0xFF & i));
}

对我来说似乎没问题。

于 2013-12-08T16:31:49.637 回答