How to generate MD5 hash in Java

March 29, 2017

Today, we are going to learn how to generate MD5 hash. This algorithm is useful for verification e.g. files downloaded from the Internet or even hide our beloved password.

However, in this short tutorial, we will read up with the second option.

At the very beginning it is good to set our password:

After that, we can move to the most significant step. We need to tell our program which algorithm to choose. We will use the MessageDigest class.

As we should know, MD5 uses bytes to crypt the text, so we need to give him those. getBytes() and update() will be helpful here:

Now, we can let our algorithm finish the job using digest() method. It is important that the type of the new variable is byte[] (because it’s an array of bytes)

On this moment, our hash is ready. What we want to see is the result of our algorithm. This time, we need to convert array of bytes to integer so BigInteger is our friend:

If we get our conversion ready, we can convert our hash to String

The 16 number is there because we want to have the result in hex system. After all, the last thing to do is to show our new and fresh hash on the screen:

The output of the program will be:


Click here to add a comment

Leave a comment: