security

Check message consistency using hash functions

In this example we shall show you how to check message consistency using hash functions. We are using the java.security.MessageDigest Class, that provides the functionality of a message digest algorithm. It takes arbitrary-sized data and outputs a fixed-length hash value. To check the consistency of two messages using the MessageDigest hash function, one should perform the following steps:

  • Create a MessageDigest Object that implements the “MD5” algorithm.
  • Update the digest with the byte array from a given String, using the update(byte[] input) API method.
  • Complete the hash computation, using the digest API method and return the computated hash value in a byte array.
  • Invoke the above steps for two different Strings, as shown in the getDigest(String str) method of the example, and then use the isEqual(byte[] digesta, byte[] digestb) API method to compare the two results, in order to check their consistency.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.security.MessageDigest;

public class Main {

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


  String str1 = "javacodegeeks.com";

  String str2 = "javacodegeeks";

  byte[] fDigest = getDigest(str1);

  byte[] sDigest = getDigest(str2);


  if (MessageDigest.isEqual(fDigest, sDigest)) {


System.out.println("str1 is equal to str2");

  } else {


System.out.println("str1 is NOT equal to str2");

  }
    }

    public static byte[] getDigest(String str) throws Exception {

  MessageDigest hash = MessageDigest.getInstance("MD5");
     

  byte[] data = str.getBytes();

 

  hash.update(data);


  return hash.digest();
    }
}

Output:

str1 is NOT equal to str2

 
This was an example of how to check message consistency using the MessageDigest hash function in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button