Message Authentication Code (MAC)

The javax.crypto.Mac API is used to access a "Message Authentication Code" (MAC) algorithm. These algorithms are used to check the integrity of messages upon receipt. There are two classes of MAC algorithms in general, those that are based on message digests (known as HMAC algorithms) and those on encryption algorithms. In both cases a shared secret is required.

A Mac is used in the same fashion as a Cipher. First, use the factory method Mac.getInstance() to get the provider implementation of the required algorithm, then initialize the algorithm with the appropriate key via the Mac.init() method. Then, use the Mac.update() method to process the message, and finally, use the Mac.doFinal() method to calculate the MAC for the message.

To verify the message, follow the same procedure and compare the supplied MAC with the calculated MAC.

Note that it is not necessary to use the Mac.init() method to check multiple messages if the shared secret has not changed. The Mac will be reset after the call to Mac.doFinal() (or a call to Mac.reset()).

   /*
    * on the sender
    */
   Mac senderMac = Mac.getInstance("HMAC-SHA1");
   senderMac.init(shaMacKey);
   byte[] mac = senderMac.doFinal(data);

   /*
    * now transmit message and mac to receiver
    */
   Mac recMac = Mac.getInstance("HMAC-SHA1");
   recMac.init(shaMacKey);
   byte[] calcMac = recMac.doFinal(data);

   for (int i = 0; i < calcMac.length; i ++)
   {
      if (calcMac[i] != mac[i])
      {
         /* bogus MAC! */
         return false;
      }
   }

   /* all okay */
   return true;