How to hash a string with MD5 in Java

In this tutorial, we are going to see how to use the MD5 algorithm to hash a string in Java.

To calculate the cryptographic hash value in Java, the MessageDigest class is used, under the package.

The MD5 algorithm is initialized in a static method called getInstance(). After selecting the algorithm, it calculates the hash value and returns the results in a byte array.

Java Program to hash a string with MD5:
import java.nio.charset.*;

public class Main {
    public static void main(String[] args) throws Exception {

        String str = "StackHowTo";

        MessageDigest msg = MessageDigest.getInstance("MD5");
        byte[] hash = msg.digest(str.getBytes(StandardCharsets.UTF_8));

        // convert bytes to hexadecimal
        StringBuilder s = new StringBuilder();
        for (byte b : hash) {
            s.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *