Java MD5 Hash
How do you get a MD5 hash in Java? Well I am glad you asked! I have somehow managed to create some Java code that does exactly that. Here it is for your cut and pasting pleasure! I have seen some code out there that won’t work correctly if the hashed value starts with zeros (generally because they are using a BigInteger). This version will properly display leading zeroes.
If you run this code the output will be:
hash = 49a9884c3121800a49d64a5389691d1a
Comparing this to obtaining the md5 hash from the command-line shows that I actually managed to put together some code that works. This is on Mac OS, although every unix flavor probably has a md5 command-line utility:
bad:~:7> md5 -s "what is the md5 hash of this?"
MD5 ("what is the md5 hash of this?") = 49a9884c3121800a49d64a5389691d1a
This code actually demonstrates another issue I sometimes have with Java. That being that the JDK itself doesn’t always get the checked vs. unchecked exception nonsense correct. Being a bad programmer might mean that I don’t have a clue what I am talking about, but NoSuchAlgorithmException should not be a checked exception! I can’t reasonably be expected to recover from that exception so it should be unchecked. If a unknown algorithm is being passed to getInstance() then that is a programming error, so again, that should be an unchecked exception.