HMAC in Java Example

HMAC is a specific type of message authentication code MAC,it is keyed-hash message authentication code it is mainly used to verify data integrity and authentication of a cane be used with hashing functions like MD5(Message Digest 5) and SHA(Secure Hash Algorithm).it can be used to secure our web service by providing Hashed value of the payload(message) in Header or in request body.

Example code.

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;

public class HMACExample {

 public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {

 String secretKey="123456";//your key
 String algorithm="HMACSHA256"; //your HMAC algorithm
 String message="Hello How are you";

 SecretKeySpec keySpec=new SecretKeySpec(secretKey.getBytes("UTF-8"), algorithm);

 Mac mac=Mac.getInstance(algorithm);
 byte[] hmacData=mac.doFinal(message.getBytes("UTF-8"));

System.out.println("hash : "+new BASE64Encoder().encode(hmacData));



hash : 1T+pDJvQV+yUPLdN4YejisWsWBzz2oq+qg8cF2uodZw=

The above code will generate different hash for different message and hash will be same for same message.

Note:For web service private key and algorithm are shared with client and client will send message along with the hash generated for the message and at server end again hash value is calculated for the message using key and algorithm, if the hash generated at server end matches with hash send by the client then it is consider as the message is from real client and it can be processed,if the hash does not match then it is considered as the message has been tampered and is not from real client.

This entry was posted in Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s