String to MD5 hash in Java

In this example we will create a MD5 hash from a String. This can be useful when you for example want to keep passwords secure in a database so no one can read them in plain text. The MD5 is a one-way hash so it’s not possible to restore the original value again. You must hash another value and compare with the previously hashed value to see if they match.

To hash a String with MD5 we get an instance of the MessageDigest class calling the getInstance() method and provide the String “MD5” as parameter.
Then we need to create an inputstream from the String we want to use and pass that inputstream to an instance of DigestInputStream – along with the MessageDigest instance. Once that is done we need to read the content of the stream and this is an important step. If we don’t read in the bytes from the inputstream the hashed value will always be the same. Since we don’t need to do anything explicit with the content read from the inputstream but only read it, we don’t supply a body for the while-loop.

Finally we call the digest() method of the MessageDigest instance which will return a byte array.

If we want to store our hashed password in a database column of type varchar (or the like) we need to convert the byte array to a String. In this case we will convert it to a hexadecimal String which is done in the main method when the call to stringToMD5 returns. Apache Commons codec library has a neat class called ‘Hex’ for doing that.
Then we print out our hexadecimal value, and the length of it. Try to hash different values and you’ll see that the length of the hash array will always be 16 and the length of the generated hex string will always be 32 characters long.

The output from the code above:

Search for more Java info on this site here:
Custom Search

Please type any questions here.