Here is a quicky one. I was surprised to see that when i needed a quick way to calculate the MD5 hash of a string it was not in the java.lang.String class. I know things with Java have to be well structured and since MD5 is a hashing algorithm it is fairly logical to be in the security package. On the other hand i think a quick md5 method should be in the String class but that’s just my humble oppinion. Anyways here is how it’s done the Java way.
So what you have to do it to create an instance of the MessageDigest class with the algorithm of MD5, then convert your string to a byte sequence, feed it to the instance that will return a new byte sequence with the MD5 value and convert it accordingly to what we want (here just the hex representation). So let’s get our hands dirty.
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class LMD5Gen {
public static String md5(String input){
String res = "";
try {
MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(input.getBytes());
byte[] md5 = algorithm.digest();
String tmp = "";
for (int i = 0; i < md5.length; i++) {
tmp = (Integer.toHexString(0xFF & md5[i]));
if (tmp.length() == 1) {
res += "0" + tmp;
} else {
res += tmp;
}
}
} catch (NoSuchAlgorithmException ex) {}
return res;
}
}
As you can see this class is a wrapper for the method. All we need to do is feed the string to the method and get the resulting MD5. Just a quick note to all adventurers out there. Note line 16's if. What it does is that it makes sure that the resulting hex is a two digit one. We need to ensure this so our md5 will have 32 characters as it should.
Hope it helps and as always comments are welcome!
Just writing to thank you for this algorithm. Do you have a problem with me using it in a file at work if i credit you?
my friend you are more than welcome to do whatever you want with this code snippet. use it as you wish. if you credit me it will be fine but even if you don’t that will no bother me either. i am really glad it helps!
Thank you! It’s great 😉
Similar version of this code, but calculating MD5 for a file can be found on JavaBlogging: “Sha1 and MD5 checksums in Java”
Thanks. Maybe you should use StringBuffer or StringBuilder. Concatenation of Strings in a loop is not very efficient.