我有一个循环和散列的数据点。我正在使用 SHA-512 的 Java 实现来散列我的数据。哈希应该生成一个 128 个字符的字符串,但有时它会生成一个 127 个字符的字符串,导致我的代码出现越界异常。
该代码通常会在每 20 个不同的哈希值计算中生成一个长度不正确的哈希值 1。
这是我用来实现哈希的代码,来自 https://www.geeksforgeeks.org/sha-512-hash-in-java/
public static String SHA512(String input)
{
try {
// getInstance() method is called with algorithm SHA-512
MessageDigest md = MessageDigest.getInstance("SHA-512");
// digest() method is called
// to calculate message digest of the input string
// returned as array of byte
byte[] messageDigest = md.digest(input.getBytes());
// Convert byte array into signum representation
BigInteger no = new BigInteger(1, messageDigest);
// Convert message digest into hex value
String hashtext = no.toString(16);
// Add preceding 0s to make it 32 bit
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
// return the HashText
return hashtext;
}
// For specifying wrong message digest algorithms
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
这是由上面列出的代码生成的正确长度(128 个字符)的哈希值: ca36f8a40a6211d49e77f84ca37182813fba853fba732e29d18414c739b85f856fd3af702a2cd23174eeaedf2d99a044b0ae0ddea17de7bbb33e3b62cfec5236
下面是由上面列出的代码生成的长度不正确的哈希值(127 个字符): d2d3cb7a7f60a0fd673c86fb82eb515c4f2f40f0308df7b3c838b78c510125967191ad9afe0e4f8e5fb59ed190bc6652d3e4805c886fc1e62213a3284cca661
最佳答案
更改 while 循环条件 < 32
至< 128
修复它。这是有道理的,因为代码应该生成 128 十六进制数字字符串(512 位),而不是 32 十六进制数字字符串(128 位)。看来这可能是OP代码中列出的错误。
关于Java SHA-512 函数仅产生 508 位输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56228355/