Welcome to Srini's blog

Thursday, January 13, 2011

Generate MD5 hash to a given string -- java

Yesterday I had a requirement to compute MD5 hash for a particular string to validate in my code. A quick googling I got lot of sources. Here I am posting the code which I worked out.

public class MD5Hash {
public static void main(String args[]) {
try {
String md5Hash = MD5("Give String");
System.out.println("MD5 hash is : " + md5Hash);
} catch(Exception e) {
//TODO: Nothing
}
}

private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < halfbyte =" (data[i]">>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}

private static String MD5(String text) throws Exception {
MessageDigest md;
md = MessageDigest.getInstance("MD5");
byte[] md5hash = new byte[32];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
md5hash = md.digest();
return convertToHex(md5hash);
}
}

No comments:

Post a Comment