Jun 03

We can use an MD5 implementation of the MessageDigest class to calculate the MD5 sum of a file (or any array of bytes). Once we have that it is simply a matter of feeding the contents of the file to the digest and have it calculate the MD5 sum as shown in the following example.

// Get an MD5 implementation of MessageDigest

MessageDigest digest = MessageDigest.getInstance("MD5");

// Open file and read contents

InputStream is = new FileInputStream(file);				
byte[] buffer = new byte[8192];
int read = 0;
while( (read = is.read(buffer)) >= 0)
   // pass data read from file to digest for processing

   digest.update(buffer, 0, read);

// Get the MD5 sum

byte[] md5sum = digest.digest();

// (Optionally) convert the MD5 byte array to a hex string

String md5sumHex = new BigInteger(1, md5sum).toString(16);

written by objects \\ tags: , , , ,