Aug 24

We’ve previously shown how to create an MD5 sum for a file. If you don’t have a file and instead just need an MD5 sum for a byte array then you can achieve it using the following code.

            // Data is the byte array we need an MD5 sum for

            byte[] data = getDataFromWhereever();

            // Get an MD5 implementation of MessageDigest

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

            // Convert the MD5 byte array to a hex string

            String md5 = new BigInteger(1, md.digest(data)).toString(16);

written by objects \\ tags: , , ,

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

// 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: , , , ,