package jp.ac.osaka_u.ist.sel.similarity.commons;

import java.io.FileInputStream;
import java.security.MessageDigest;

/**
 * Calculate the MD5 digest from a file content.
 * 
 * Hint:
 * http://www.atmarkit.co.jp/fjava/javatips/117java021.html
 * http://en.wikipedia.org/wiki/Cryptographic_hash_function
 * 
 * @author ysk-ssk
 *
 */
public class MD5Digest {
	/**
	 * is an utility class.
	 */
	private MD5Digest() {
	}
	
	/**
	 * Calculate the MD5 digest from a file content.
	 * 
	 * @param filename
	 * @return
	 * @throws Exception
	 */
	public static byte[] getFileDigest(String filename) throws Exception {
		MessageDigest md = MessageDigest.getInstance("MD5");
		FileInputStream in = new FileInputStream(filename);
		byte[] dat = new byte[256];
		int len;
		while ((len = in.read(dat)) >=0) {
			//calculate the digest of dat[0..len]
			md.update(dat, 0, len);
		}
		in.close();
		return md.digest();
	}
	
}