Java MD5 Hashing String

Tags: MD5 MD5Utils

In this Java tutorial, we learn how to hash a String using MD5 algorithm in Java programming language.

How to use MD5 algorithm to hash a String in Java

Firstly, we create a new Java class named MD5Utils.

In this new class, implement a new static method named md5(String inputData), this method use the MD5 algorithm to hash the input text into a byte array and then convert the byte array to a hex String as a return value of method.

import java.math.BigInteger;

public class MD5Utils {

     * This method to hash a String using MD5 algorithm
     * @param inputData input text
     * @return hashed text
    public static String md5(String inputData) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] hashedData = messageDigest.digest();
            // convert byte array to hex String
            BigInteger bigInteger = new BigInteger(1, hashedData);
            String hashedText = bigInteger.toString(16);
            return hashedText;
        } catch (NoSuchAlgorithmException e) {
        return null;


In the following example Java code, we learn how to use the above MD5Utils.md5() method to MD5 hash a String in Java program.

public class MD5UtilsExample {
    public static void main(String... args) {
        String inputText = "Simple Solution";

        // Hash a String using MD5 algorithm
        String hashedText = MD5Utils.md5(inputText);

        System.out.println("Input text: " + inputText);
        System.out.println("MD5 hashed text: " + hashedText);
The output as below.
Input text: Simple Solution
MD5 hashed text: 6cd04c53878b462e5d7d400a11ac19cf

Happy Coding 😊

Java SHA-1 Hashing String

Java AES 256 Encryption and Decryption

Java AES Advanced Encryption Standard Encryption and Decryption