How to generate an MD5 hash from a string in Java?

If you’re already using Guava in your project, why not leverage its hashing utilities? It offers a clean and readable way to generate MD5 hashes."*

Using Guava (Google’s Library) If your project already uses Google Guava, you can use its Hashing class to generate Java MD5 hashes effortlessly.

First, add the Maven dependency:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>

Then, use this code:

import com.google.common.hash.Hashing;
import java.nio.charset.StandardCharsets;

public class MD5GuavaExample {
    public static void main(String[] args) {
        String hash = Hashing.md5()
                .hashString("HelloWorld", StandardCharsets.UTF_8)
                .toString();
        System.out.println(hash);
    }
}

:small_blue_diamond: Why this is great?

:white_check_mark: Simple & readable syntax.

:white_check_mark: Ideal if you’re already using Google Guava.

:white_check_mark: Convenient for working with multiple hashing algorithms.