The MD5 algorithm is a widely used hash function producing a 128-bit hash value. This post will discuss different methods to generate MD5 hashcodes in Java using MessageDigest instance, Guava, and Apache Commons library.

Note that MD5 suffers from extensive vulnerabilities and can be cracked by a brute-force attack. We should use SHA-256 instead.

1. Using MessageDigest instance

The idea is to get an instance of MD5 message digest using the java.security.MessageDigest class getInstance() method, which takes digest algorithm. Then we call the digest(input) method that first calls update(input), passing the input array to the update method, then calls digest(). We can make an explicit call to the update() method several times for large inputs.

Note that the java.xml.bind is no longer contained on the default classpath starting Java SE 9. In Java 11, they are completely removed from the JDK.

Download Code

Output:

E4D909C290D0FB1CA068FFADDF22CBD0

2. Using Guava Library

We can also use third-party libraries like Google’s Guava library for generating MD5 hashcodes. This is demonstrated below:

Download Code

Output:

e4d909c290d0fb1ca068ffaddf22cbd0

3. Using Apache Commons Library

Alternatively, Apache Commons library can also be used which provides org.apache.commons.codec.digest.DigestUtils class to replace MessageDigest Class.

Download Code

Output:

e4d909c290d0fb1ca068ffaddf22cbd0

That’s all about generating MD5 hashcode in Java.