package net.oni2.aeinstaller.backend;

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

/**
 * @author Christian Illy
 */
public class FileChecksum {

	/**
	 * Calculate MD5 checksum of file
	 * 
	 * @param f
	 *            File to calc checksum on
	 * @return Checksum
	 */
	public static byte[] calculateFileMD5(File f) {
		MessageDigest md = null;
		InputStream is = null;
		InputStream dis = null;
		byte[] md5 = null;
		try {
			md = MessageDigest.getInstance("MD5");
			is = new FileInputStream(f);
			dis = new DigestInputStream(is, md);
			byte data[] = new byte[1024];
			while (dis.read(data) > 0) {
			}
			md5 = md.digest();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (dis != null) {
				try {
					dis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return md5;
	}

}
