1

当我通过以下代码重现 SHA2 哈希时:

MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.digest("A".getBytes("UTF-8"));

它给了我一个字节数组,即:85,-102,-22,-48,-126,100,-43,121,93,57,9,113,-116,-35,5,-85,-44,-107,114, -24,79,-27,85,-112,-18,-13,26,-120,-96,-113,-33,-3

但是当我通过 MySQL 重现相同的哈希时,它给了我一个字符串:5cfe2cddbb9940fb4d8505e25ea77e763a0077693dbb01b1a6aa94f2

如何转换 Java 的结果,以便将其与 MySQL 的结果进行比较?

4

2 回答 2

4

首先检查您的数据库结果,看起来您的初始哈希实际上是 SHA-224 而不是 SHA-256:

mysql> SELECT SHA2("A", 224);
+----------------------------------------------------------+
| SHA2("A", 224)                                           |
+----------------------------------------------------------+
| 5cfe2cddbb9940fb4d8505e25ea77e763a0077693dbb01b1a6aa94f2 |
+----------------------------------------------------------+
1 row in set (0.00 sec)

代替:

mysql> SELECT SHA2("A", 256);
+------------------------------------------------------------------+
| SHA2("A", 256)                                                   |
+------------------------------------------------------------------+
| 559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd |
+------------------------------------------------------------------+
1 row in set (0.06 sec)

从那里你走在正确的轨道上,你只需要将 byte[] 输出转换为十六进制字符串。

import java.security.MessageDigest;

public class TestSHA256 {

    public static void main(String[] args) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest("A".getBytes("UTF-8"));

            StringBuilder hexString = new StringBuilder();
            for (int i: hash) {
                hexString.append(Integer.toHexString(0XFF & i));
            }
            System.out.println(hexString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

输出:

559aead08264d5795d399718cdd5abd49572e84fe55590eef31a88a08fdffd
于 2012-11-11T14:08:11.600 回答
4

Integer.toHexString(0XFF & i)必须替换为String.format("%02x", 0XFF & i),否则只会产生 1 个字符的输出,而需要 2 个字符。

于 2016-05-05T13:56:21.243 回答