Saturday, April 26, 2014

Message Digest in Java

Message Digest is a function to verify a message integrity. A sender sends a message along with its message digest. The recipient then has to generate a new message digest from the original message. If the two message digests are equal then the message is verified. There are several algorithms we can use to generate message digest hash code including MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512. Let's now try to generate a message digest using MessageDigest class.


First we create the message and convert it to array of byte.


Then we create a MessageDigest object by passing an algorithm name of our preference. In the code above we passed "SHA-512". Next we update the object with our original message.


We then call digest() method of MessageDigest object against our original message to generate the message digest byte. Converting the byte to String using UTF8 encoding enables us to display the generated message digest to console as shown below.


This message digest is sent along with the original message. The recipient has to generate a new message digest against the original message as we did before. If the two message digests are equal then the original message is verified. Message digest is used to guarantee that the original message is intact because if the original message is changed even a bit, the MessageDigest will generate a completely different digest.

0 comments:

 

©2009 Stay the Same | by TNB