How do I generate an MD5 digest for a file?
Author: Deron Eriksson
Description: This Java tutorial describes how to generate an MD5 digest for a file.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


Page:    1 2 >

The MessageDigestForFile class demonstrates the generation of an MD5W digest for a file. The MD5 digest is displayed in hex using the Hex class from the ApacheSW CommonsSW Codec library. The call to MessageDigest.getInstance("MD5") specifies to use the MD5 algorithm. Other common algorithms are MD2 and SHA.

The getDigest() method of MessageDigestForFile has three parameters. The first is the InputStream of the file that we're going to read from. The second parameter is our MessageDigest. The third parameter is the size of the byte array that we'll use to read from the InputStream and update the MessageDigest. The getDigest() method first resets the MessageDigest to be sure that it is fresh. It reads the bytes of the file to update the MessageDigest. We get the resulting digest from the MessageDigest and convert this to a String that we return from the method.

MessageDigestForFile.java

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;

public class MessageDigestForFile {

	public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException, IOException {

		String file = "httpd-2.2.6-win32-src-r2.zip";
		MessageDigest md = MessageDigest.getInstance("MD5");
		String digest = getDigest(new FileInputStream(file), md, 2048);

		System.out.println("MD5 Digest:" + digest);

	}

	public static String getDigest(InputStream is, MessageDigest md, int byteArraySize)
			throws NoSuchAlgorithmException, IOException {

		md.reset();
		byte[] bytes = new byte[byteArraySize];
		int numBytes;
		while ((numBytes = is.read(bytes)) != -1) {
			md.update(bytes, 0, numBytes);
		}
		byte[] digest = md.digest();
		String result = new String(Hex.encodeHex(digest));
		return result;
	}

}

(Continued on page 2)

Page:    1 2 >