Java Mac

Jakob Jenkov
Last update: 2017-12-19

The Java Mac (javax.crypto.Mac class can create a Message Authentication Code (MAC) from binary data. A MAC is a message digest which has been encrypted with a secret key. Only if you have the secret key can you verify the MAC.

Creating a Mac Instance

Before you can use the Java Mac class you must create a Mac instance. Creating a Mac instance is done using the getInstance() method. Here is a Java Mac instantiation example:

Mac mac = Mac.getInstance("HmacSHA256");

The String parameter passed to the Mac getInstance() method contains the name of the MAC algorithm to use. In this case the MAC algorithm is HmacSHA256.

Initializing the Mac

Once created, the Java Mac instance must be initialized. You initialize the Mac instance by calling its init() method passing as parameter the secret key to be used by the Mac instance. Here is a Java Mac initialization example:

byte[] keyBytes   = new byte[]{0,1,2,3,4,5,6,7,8 ,9,10,11,12,13,14,15};
String algorithm  = "RawBytes";
SecretKeySpec key = new SecretKeySpec(keyBytes, algorithm);

mac.init(key);

The Mac init() method takes a Key instance. In this example a SecretKeySpec is used which implements the Key interface.

Calculating the MAC

Once the Java Mac instance is initialized you can start calculating MAC values with it. To calculate a MAC value you call the Mac update() or doFinal() method. If you only have a single block of data to calculate the MAC for, you can call doFinal() directly, like this:

byte[] data  = "abcdefghijklmnopqrstuvxyz".getBytes("UTF-8");
byte[] macBytes = mac.doFinal(data);

If you have multiple blocks of data to calculate the MAC for, e.g. if you are reading a file block by block, then you must call the update() method with each block, and finish with a call to doFinal(). Here is an example:

byte[] data  = "abcdefghijklmnopqrstuvxyz".getBytes("UTF-8");
byte[] data2 = "0123456789".getBytes("UTF-8");

mac.update(data);
mac.update(data2);

byte[] macBytes = mac.doFinal();

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next