当我通过以下代码重现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的结果进行比较?
答案 0 :(得分: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
答案 1 :(得分:2)
Integer.toHexString(0XFF & i)
必须替换为String.format("%02x", 0XFF & i)
,否则只会生成1个字符的输出,而预期会有2个字符。