Java - Generating a MD5 hash
Word of warning: MD5 hashes are ONE-WAY; you cannot convert a hash back into it’s previous form. You might be thinking that this would be great for storing passwords in a database, but in the world of cryptography this is a big mistake. If this is your intention I highly recommend that you look into salting and cryptographic hashes, the reasons why are numerous and covered at great length over at Security Overflow.
Java offers a fairly easy way of generating an MD5 using java.security
. Let’s take a look at converting a string to an MD5 hash. Notice that we need to catch the NoSuchAlgorithmException that is potentially thrown by MessageDigest.getInstance()
.
String value = "MD5 is a one-way hash";
byte[] valueBytes = value.getBytes();
String valueHashedString = "UNABLE TO CALCULATE MD5";
try {
MessageDigest mdFiver = MessageDigest.getInstance("MD5");
byte[] valueHashedBytes = mdFiver.digest(valueBytes);
// Convert hashed bytes to String
valueHashedString = new String(valueHashedBytes);
} catch (NoSuchAlgorithmException e ) {
// You must always catch this exception from MessageDigest.getInstance()
}
System.out.println("The MD5 of \"" + value + "\" is " + valueHashedString);
The output of this code snippet will be:
The MD5 of "MD5 is a one-way hash is a one-way hash" is e5ef5eae0847e53a995adf14124d910c
Get the code on GitHub