/*******************************************************************************
 * Copyright (c) 2005-2011
 * University of Augsburg, Germany <www.ds-lab.org>
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Wolf Fischer, Programming distributed Systems Lab, University of Augsburg 
 *    	- initial API and implementation
 *******************************************************************************/

package org.eclipse.jwt.we.misc.util.internal;

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


/**
 * Simple class for MD5 Fingerprint generation.
 * 
 * @author Wolf Fischer, Programming distributed Systems Lab, University of Augsburg,
 *         Germany, www.ds-lab.org
 */
public class MD5Fingerprint
{

	/**
	 * A simple Fingerprint Provider
	 */
	private static String FINGERPRINT_PROVIDER = "MD5"; //$NON-NLS-1$


	/**
	 * Creates an MD5 fingerprint for a byte array
	 * 
	 * @param bytes
	 *            the bytes that the MD5 fingerprint should be generated on
	 * @return byte Array
	 * @throws NoSuchAlgorithmException
	 *             if the MD5 provider is not available on the system
	 */
	public static byte[] createMD5Fingerprint(byte[] bytes)
			throws NoSuchAlgorithmException
	{
		MessageDigest md = MessageDigest.getInstance(FINGERPRINT_PROVIDER);
		return md.digest(bytes);
	}


	/**
	 * Creates an MD5 fingerprint for a file
	 * 
	 * @param filename
	 *            The Filename that should be read
	 * @return byte array
	 * @throws FileNotFoundException
	 *             if the file is not available
	 * @throws IOException
	 *             if the file cannot be read
	 * @throws NoSuchAlgorithmException
	 *             if the MD5 provider is not available on the system
	 */
	public static byte[] createMD5Fingerprint(String filename)
			throws FileNotFoundException, IOException, NoSuchAlgorithmException
	{
		File f = new File(filename);
		FileInputStream fr = new FileInputStream(filename);
		byte[] data = new byte[(int) f.length()];
		fr.read(data, 0, (int) f.length());
		return createMD5Fingerprint(data);
	}
}
