匹配的Java SHA2输出VS MySQL的SHA2输出(Matching Java SHA2 O

2019-08-02 14:21发布

当我通过下面的代码重现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

但是,当我通过My​​SQL的复制相同的哈希它给了我一个字符串,它是:5cfe2cddbb9940fb4d8505e25ea77e763a0077693dbb01b1a6aa94f2

我怎么能转换THA Java的结果,这样我可以与MySQL的结果进行比较呢?

Answer 1:

首先检查你的数据库的结果,它看起来像您最初的哈希实际上是一个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)

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

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


Answer 2:

Integer.toHexString(0XFF & i)必须被替换String.format("%02x", 0XFF & i)否则它仅产生1个字符输出,而2个字符的预期。



文章来源: Matching Java SHA2 Output vs MySQL SHA2 Output