Code Snippets: Compute File MD5 Hash in Java

I was writing an Android app recently that needed to compute the MD5s of some files. Figured I’d share an excerpt.


/**
* Computes an MD5 for a file and returns hex string
* @param filePath – path to the file whose checksum we need to compute
* @return – hex string representing the MD5
*/
public static String ComputeFileMD5(String filePath) throws Exception
{
InputStream inStream = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
MessageDigest hasher = MessageDigest.getInstance(“MD5”);
int numRead = 0;
while (numRead != -1)
{
numRead = inStream.read(buffer);
if (numRead > 0)
hasher.update(buffer, 0, numRead);
}
inStream.close();
byte [] md5Bytes = hasher.digest(); // compute the hash
return ConvertHashToString(md5Bytes);
}

/**
* Converts the byte array associated with an md5 calculation to hex string
* @param md5Bytes – bytes representing an md5 value
* @return – string
*/
private static String ConvertHashToString(byte [] md5Bytes)
{
String returnVal = “”;
for (int i=0; i < md5Bytes.length; i++) // convert it to a hash value returnVal += Integer.toString( ( md5Bytes[i] & 0xff ) + 0x100, 16).substring( 1 ); return returnVal.toUpperCase(); } [/java] As you can see, I wanted the MD5 as a string, so I do a conversion. Naturally, you can modify this to return MD5 byte array. This is pretty self-explanatory, but let me know if you have any questions or see any issues in my implementation. Cheers!