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 theisEqual(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.