2

I have a zip file, and in my Java code i want to calculate the md5 hash of the zip file. Is there any java libary i can use for this purpose ?. Some example would be really appreciated.

Thank You

Joey
  • 25
  • 1
  • 3
  • Could you please look at the bottom right of the page into the "Related" section? Thanks. – bezmax Mar 14 '11 at 10:51
  • I had a look at the related questions and could'nt find a question related to hashing a File in Java. There are some for Strings in Java and files in Perl and so on but none for a File in Java. – Chris Mar 14 '11 at 10:57
  • I'm sorry just found that one: http://stackoverflow.com/questions/304268/using-java-to-get-a-files-md5-checksum – Chris Mar 14 '11 at 11:23

2 Answers2

4

I got that working a few weeks ago with this Article here:

http://www.javalobby.org/java/forums/t84420.html

Just to have it a stackoveflow:

public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException {
MessageDigest digest = MessageDigest.getInstance("MD5");
File f = new File("c:\\myfile.txt");
InputStream is = new FileInputStream(f);                
byte[] buffer = new byte[8192];
int read = 0;
try {
    while( (read = is.read(buffer)) > 0) {
        digest.update(buffer, 0, read);
    }       
    byte[] md5sum = digest.digest();
    BigInteger bigInt = new BigInteger(1, md5sum);
    String output = bigInt.toString(16);
    System.out.println("MD5: " + output);
}
catch(IOException e) {
    throw new RuntimeException("Unable to process file for MD5", e);
}
finally {
    try {
        is.close();
    }
    catch(IOException e) {
        throw new RuntimeException("Unable to close input stream for MD5 calculation", e);
    }
}       
}
Chris
  • 7,675
  • 8
  • 51
  • 101
  • There's an easier way, please take a look at http://stackoverflow.com/questions/304268/getting-a-files-md5-checksum-in-java – Randyaa Jan 02 '15 at 14:50
0

There is also an option to do that with Apache Codec like that

final String sha256 = DigestUtils.sha256Hex(new FileInputStream(file))