HMAC signatures in Java

A tutorial on how to create HMAC signatures in Java
 

HMAC stands for Hash Message Authentication Code and it is used for verifying the integrity of data exchanged between two applications etc.In general,any hash function -such as MD5 or SHA1- can be used in order to create an HMAC signature but for this tutorial we will use hash function SHA256.

In order to create the HMAC we will need a key and javax.crypto.Mac class.

package com.javaonly.hmac.test;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import javax.crypto.Mac;

public class HMACTest {

	public static void main(String args[]) throws NoSuchAlgorithmException,
			KeyManagementException,
			 InvalidKeyException,
			IllegalBlockSizeException, BadPaddingException {

		
		
		String macKey = "The HMAC key";
		String macData ="the data string"
		System.out.println("MACDATA:"+macData);

		Mac mac = Mac.getInstance("HmacSHA256");
                //get the bytes of the hmac key and data string
		byte[] secretByte = macKey.getBytes("UTF-8");
		byte[] dataBytes = macData.getBytes("UTF-8");
		SecretKey secret = new SecretKeySpec(secretByte, "HMACSHA256");

		mac.init(secret);
		byte[] doFinal = mac.doFinal(dataBytes);
		byte[] hexB = new Hex().encode(doFinal);
		String checksum = Hex.encodeHex(doFinal);
		
	}
}

 In the above code snippet Mac is the class that will create the HMAC signature.It is initialized with a SecretKeySpec object that implements SecretKey interface.SecretKeySepc object is used to create a key in a vendor-independent way.Finally,The HMAC signature's bytes are encoded into a Hexademical String through the org.apache.commons.codec.binary.Hex class

Copyright © 2012 Design and Development Nikos Lianeris

  • 4
  • 19