简体   繁体   中英

How to calculate SHA512 of a file?

I have a file, and I need to calculate the SHA512 value for it. I've found plenty of sites offering to do it for me, but I'd like to do it programmatically in Java (well, Groovy, but it's the same thing).

For those curious, I'm running Oracle's TZUpdater tool and pointing it at a local file. This requires a file that contains the SHA512 value for that file. http://www.oracle.com/technetwork/java/javase/tzupdater-readme-136440.html

You can calculate the SHA-512 digest of a file with this code snippet:

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

For this code to work you will need JDK7 or higher.

Note: if the file is too big to fit in memory you should probably go with Guava as proposed.

If third-party libraries are fair game, Guava's Files.hash could make this as simple as

Files.hash(new File(fileName), Hashing.sha512()).toString();

...which would also potentially be more efficient; if the file is large, it not need be stored in memory all at once as in the Files.readAllBytes solution. This will also output a proper hash in hexadecimal; if you need it in bytes just use asBytes() instead of toString() .

Simplest solution, no external libs, no problems with big files:

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();
}

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

You could also use Apache Commons Codec.

Maven Repository: https://mvnrepository.com/artifact/commons-codec/commons-codec

Code example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM