java.security.MessageDigest Example
The Java Cryptographic services include signature, message digest, cipher, mac and key stores. The MessageDigest class supports message digest algorithms – MD2, MD5,SHA-1, SHA-256,SHA-384 and SHA-512. SHA-256 is a 256-bit hash function to provide 128 bits of security against collision attacks. SHA-512 is a 512 bit hash function to provide 256 bits of security. A 384-bit hash is obtained by truncating the SHA-512 output.
Message Digests use arbitrary sized data as input and fixed length value as output. The data is provided using update methods to an initialized MessageDigest instance from a static method. The Message Digest class implements the cloneable interface.
MessageDigestClass is abstract and extends from MessageDigestSpi.The class has methods getInstance (static method) to get the instance. Message Digest is initialized and data is processed through the update methods. Reset method is called to reset the digest. The Hash computation is completed when the digest method is called after the update call.
Source Code Example
The example below shows a sample for the MessageDigest implementation and usage.
MessageDigestExample.java
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | package com.javacodegeeks.util.security; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * @author Bhagvan Kommadi * Message Digest Example demonstrates the usage of Message Digest * */ public class MessageDigestExample { /** * @param args */ public static void main(String[] args) { String data = "This is a message to be digested using MD5" ; MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance( "MD5" ); messageDigest.update(data.getBytes()); byte [] messageDigestMD5 = messageDigest.digest(); StringBuffer stringBuffer = new StringBuffer(); for ( byte bytes : messageDigestMD5) { stringBuffer.append(String.format( "%02x" , bytes & 0xff )); } System.out.println( "data:" + data); System.out.println( "digestedMD5(hex):" + stringBuffer.toString()); } catch (NoSuchAlgorithmException exception) { // TODO Auto-generated catch block exception.printStackTrace(); } } } |
Output
1 2 | data:This is a message to be digested using MD5 digestedMD5(hex):96d013c1a391809462fb7a2cbd0b2583 |
The Message Digest class is used for the generation of a digest using secure one-way hash functions.
Conclusion
The Message Digest class is used for the creation of digest using algorithms – MD2, MD5,SHA-1, SHA-256,SHA-384 and SHA-512.
You can download the source code of the example here: MessageDigestExample.zip