Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 672
Steve Avatar asked Oct 24 '25 06:10

Steve


1 Answers

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().

UPDATE: In newer versions of Guava, Files.hash(File,String) has been deprecated. Instead, you can use:

com.google.common.io.Files.asByteSource(file).hash( Hashing.sha512())
like image 185
Louis Wasserman Avatar answered Oct 26 '25 21:10

Louis Wasserman