/*
 * Program to implement message digest algorithms like MD5, SHA-1 and analyzing
 * them w.r.t message size, key length etc. parameters
 */

/* 
 * Importing various packages
 */

import java.io.*;
import java.util.*;
import java.security.*;



/*
 * This is the main class in which the main function has been defined. The 
 * parameters which the user should pass are the name of the file of which
 * the digest has to be generated, the name of the algorithm to be used(MD5 
 * or SHA-1) and the size of the message to take.
 */ 
class Digest{

	public static void main(String args[]) throws IOException,NoSuchAlgorithmException 
	 {
		if(args.length != 3)
		 {
			System.out.println("Usage : java Digest <filename> <Algo> <msgsize>");
			return;
		 }

		/**Take the various command line parameters */
		String	strFilename	= new String(args[0]);
		String  strAlgoName	= new String(args[1]);
		int	msgSize		= Integer.parseInt(args[2]);

		int	msgLenTmp;
		int	length;
		long	timeStart, timeEnd, timeTotal=0;
		byte	hash[];

		byte	message[]	= new byte[5000];
		FileInputStream fis	= new FileInputStream(strFilename);
		BufferedInputStream bis	= new BufferedInputStream(fis);



		try{

			/** Take the start time */
			timeStart = Calendar.getInstance().getTimeInMillis();
			MessageDigest	mDigest = MessageDigest.getInstance(strAlgoName);
			msgLenTmp = msgSize;
			while(bis.available()!=0 && msgLenTmp > 0)
			 {
				length = bis.read(message);
				mDigest.update(message, 0, length);
				msgLenTmp = msgLenTmp - length;
			 }
			bis.close();
			
			hash	  = mDigest.digest();
			/** Hash has been calculted, so take the end time stamp */
			timeEnd	  = Calendar.getInstance().getTimeInMillis();
			timeTotal = timeEnd - timeStart;

			/** Write the value to the file */
			FileOutputStream fos	 = new FileOutputStream(strFilename+"."+strAlgoName+".digest");
			BufferedOutputStream bos = new BufferedOutputStream(fos);
			bos.write(hash);
			bos.close();

			/** Catch the exception  NoSuchAlgorithmException */
		 }catch(Exception NoSuchAlgorithmException){
			System.out.println("The algorithm " + strAlgoName + "is not implemented");
		 }

		System.out.println(strAlgoName + "\t\t\t" + msgSize + "\t\t" + timeTotal);
		
	 }


 }






	


