如何计算文件的 SHA512?

How to calculate SHA512 of a file?

我有一个文件,我需要计算它的 SHA512 值。我发现很多网站都可以为我做这件事,但我想在 Java 中以编程方式进行(好吧,Groovy,但这是一回事)。

对于那些好奇的人,我 运行 Oracle 的 TZUpdater 工具并将其指向本地文件。这需要一个包含该文件的 SHA512 值的文件。 http://www.oracle.com/technetwork/java/javase/tzupdater-readme-136440.html

您可以使用以下代码片段计算文件的 SHA-512 摘要:

MessageDigest.getInstance("SHA-512").digest(Files.readAllBytes(Paths.get("/path/file.txt")))

要使此代码正常工作,您需要 JDK7 或更高版本。

注意:如果文件太大而无法放入内存,您应该按照建议使用 Guava。

如果第三方库是公平的游戏,Guava 的 Files.hash 可以使这变得像

一样简单
Files.hash(new File(fileName), Hashing.sha512()).toString();

...这也可能更有效率;如果文件很大,则不需要像 Files.readAllBytes 解决方案那样一次性全部存储在内存中。这也将以十六进制输出适当的散列;如果您需要以字节为单位,只需使用 asBytes() 而不是 toString().

最简单的解决方案,没有外部库,大文件没有问题:

public static String hashFile(File file)
        throws NoSuchAlgorithmException, FileNotFoundException, IOException {
    // Set your algorithm
    // "MD2","MD5","SHA","SHA-1","SHA-256","SHA-384","SHA-512"
    MessageDigest md = MessageDigest.getInstance("SHA-512");
    FileInputStream fis = new FileInputStream(file);
    byte[] dataBytes = new byte[1024];

    int nread = 0;
    while ((nread = fis.read(dataBytes)) != -1) {
        md.update(dataBytes, 0, nread);
    }

    byte[] mdbytes = md.digest();

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < mdbytes.length; i++) {
        sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }
    return sb.toString();
}

来源:https://www.quora.com/How-do-I-get-the-SHA-256-hash-value-of-a-file-in-Java

您也可以使用 Apache Commons 编解码器。

Maven 存储库:https://mvnrepository.com/artifact/commons-codec/commons-codec

代码示例:

public static String calcSha512Hex(File file) throws FileNotFoundException, IOException {
    return org.apache.commons.codec.digest.DigestUtils.sha512Hex(new FileInputStream(file));
}