如何在Java中一致地生成正确的SHA-384哈希字符串



我试图生成文件,然后对其内容进行散列,并将该散列附加在文件内容的末尾。对于has,我使用的是SHA-384,下面粘贴了我的哈希函数代码。问题是它在生成正确的哈希字符串方面不一致,因此哈希和文件内容最终对某些文件无效(不匹配(,而对其他文件有效。我能做些什么来解决这个问题吗?我正在使用第三方应用程序来读取和验证文件,因此不幸的是,我无法获得它们的解码功能。

public static String hash384(byte[] inputBytes) throws Exception{
try {
Runtime.getRuntime().gc();
String hash;
MessageDigest messageDigest = MessageDigest.getInstance("SHA-384");
messageDigest.update(inputBytes);
byte[] digestedBytes = messageDigest.digest();
hash = new String(digestedBytes, "windows-1251");
return hash;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}

我建议使用Apache的commons-codec模块中的DigestUtils,这样就可以编写两行代码:

import static org.apache.commons.codec.digest.MessageDigestAlgorithms.SHA_384;
...
// digest
byte[] digest = new DigestUtils(SHA_384).digest(new File(<file path>));
// hex digest
String hdigest = new DigestUtils(SHA_384).digestAsHex(new File(<file path>));

最新更新