Generate MD5 hashcode in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import javax.xml.bind.DatatypeConverter; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; class Main { public static void main(String[] args) throws Exception { String password = "The quick brown fox jumps over the lazy dog."; MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digest = md.digest(password.getBytes(StandardCharsets.UTF_8)); String md5 = DatatypeConverter.printHexBinary(digest); // print MD5 Message-Digest System.out.println(md5); } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import com.google.common.base.Charsets; import com.google.common.hash.HashCode; import com.google.common.hash.Hashing; class Main { public static void main(String[] args) throws Exception { String password = "The quick brown fox jumps over the lazy dog."; HashCode md5 = Hashing.md5() .hashString(password, Charsets.UTF_8); System.out.println(md5); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import org.apache.commons.codec.digest.DigestUtils; class Main { public static void main(String[] args) throws Exception { String password = "The quick brown fox jumps over the lazy dog."; String md5 = DigestUtils.md5Hex(password); System.out.println(md5); } } |
Output:
e4d909c290d0fb1ca068ffaddf22cbd0
That’s all about generating MD5 hashcode in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)