Java md5 hash

For uni I wrote a little program that implements a sort of md5 hash. Just a 10 min program but quite nice and useful I would hope. It takes in a file and outputs the md5 sum and the file name. Used this to compare files on a computer with the version on a server. There must be better versions out there but it works

/*
* See
* http://java.sun.com/j2se/1.4.2/docs/api/java/security/MessageDigest.html
* Basically a wrapper for the sun class
*/

import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.util.Scanner;

public class mdFive {

/**
* This function is passed a File name and it returns a md5 hash of
* this file.
* !!!! MADE STATIC SO I HAVE ONE FILE !!!!!
* !!!! NEVER DO THIS PLEASE REMOVE !!!!!
* @param FileToMd5
* @return The md5 string
*/
public static String md5File(String FileToMd5){
String outPutString = new String();
try {
MessageDigest algoToCrypt = MessageDigest.getInstance("MD5");
Scanner fileToCrypt = new Scanner(new File(FileToMd5));
/* Just to be on the safe side */
byte[] fileBuffer = null;
while( fileToCrypt.hasNextByte()){
algoToCrypt.update(fileBuffer, 0, fileToCrypt.nextByte());
}
/* Int would be to small and apparentelly you have to use a sign and magnitude */
BigInteger bigInt = new BigInteger(1, algoToCrypt.digest());
outPutString = bigInt.toString(16);
fileToCrypt.close();
} catch (Exception e) {
/* Not a big enough error to exit but still should tell someone */
System.err.println("Error while creating MD5 sum");
}
return outPutString;
}

/**
* The main programm
* @param args The arguments from the command line
*/
public static void main(String[] args) {
if(args.length == 0){
System.out.println("A MD5 Hascher \nUsage java mdFive ");
}else{
System.out.println( md5File(args[0]) + " , " + args[0]);
}
}
}

2 comments:

Anonymous said...

It seems like you didn't bother to initialize the fileBuffer variable ... does the update method take care of that as you scan through the file byte by byte?

Ribalba said...

fileBuffer = null ;)

It will just overwrite what ever it needs.