Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

MD5 hash in Java

farenda 2017-04-21 0

To calculate MD5 hash in Java we can use pure Java approach or use libraries. In this post we’re going to show how to calculate Message Digest in different ways.

MD5 algorithm should not be used for serious cryptography, because it’s insecure and can be broken very fast using even commodity hardware. Nevertheless you may encounter it in various systems used for different purposes, therefore it’s good to know how to work with it. In this post we’re going to show how to calculate MD5 hash (Message Digest) of given string.

MD5 Hash in Java

Message Digest (MD5 hash sum) is usually represented as a sequence of 32 hex digits. To calculate the MD5 hash we can use java.security.MessageDigest class that provides different Message Digest algorithms. One of them is MD5. Let’s calculate MD5 hash of Hello World string:

package com.farenda.java.security;

import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import static java.nio.charset.StandardCharsets.UTF_8;

public class SecurityPlayground {

    public static void main(String[] args)
            throws NoSuchAlgorithmException {
        String data = "Hello World";
        System.out.printf("MD5 of '%s': %s%n", data, md5(data));
    }

    private static String md5(String data)
            throws NoSuchAlgorithmException {
        // Get the algorithm:
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        // Calculate Message Digest as bytes:
        byte[] digest = md5.digest(data.getBytes(UTF_8));
        // Convert to 32-char long String:
        return String.format("%032x%n", new BigInteger(1, digest));
    }
}

The most tricky part is the conversion from digest bytes into 32 chars long String. We just create very big number from the bytes and then format it into 32 chars long String, with zero padding in case of smaller result, to always have 32 chars.

The code prints the following MD5 hash:

MD5 of 'Hello World': b10a8db164e0754105b7a99be72e3fe5

MD5 hash using Guava

Another, even simpler, approach to calculating MD5 Hash is to use Hashing class from Google Guava library. The library is often used in Java projects, so most probably it’s available in yours.

import com.google.common.hash.Hashing;

//... rest of the code is like the above

private static String guavaMd5(String data) {
    return Hashing.md5().hashString(data, UTF_8).toString();
}

public static void main(String[] args)
        throws NoSuchAlgorithmException {
    String data = "Hello World";
    System.out.printf("MD5 in Guava of '%s': %s%n",
        data, guavaMd5(data));
}

When we execute this code it will print the following text:

MD5 in Guava of 'Hello World': b10a8db164e0754105b7a99be72e3fe5

So the MD5 hash is the same as in pure Java version.

Test using md5sum command

Let’s calculate MD5 hash using md5sum command available in Linux and compare with the Message Digest calculated by our program:

echo -n "Hello World" | md5sum

We’ve used -n option to not include the new line character, automatically added by echo. And the result is:

b10a8db164e0754105b7a99be72e3fe5  -

This confirms that our program calculated MD5 as expected.

References:

  • MD5 at Wikipedia
Share with the World!
Categories Java Tags java, security
Previous: MongoDB join collections
Next: Shuffle Algorithm in Java

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored