Home Java Message Authentication Code (MAC) Using Java

Message Authentication Code (MAC) Using Java

16 min read

That is the seventh entry on this weblog sequence on utilizing Java Cryptography securely. Ranging from theツ?fundamentals we started diving deeper into numerous fundamental cryptographic primitives similar to Cryptographically Safe Random Quantity Generator, symmetric & uneven encryption/decryption & hashes. After taking a short interval, we caught-up with cryptographic updates within the newest Java model.

Skip to the TL; DR

At this level, we’re properly outfitted to debate a number of the mostly encountered cryptographic schemes. Let???s begin by functions designed round symmetric cryptography, beginning with Message Authentication Code on this submit. Fortunately, Java supplies us with wealthy, easy-to-use APIs for lot of those functions, relieving us to construct up crypto programs from primitives.

Overview: What’s MAC?

Encryption supplies us with the confidentiality service of cryptography. In lots of functions (consider any type of safe communication), receiving events have to be assured of the origin of the message (authenticity) and ensure the message is acquired untampered (integrity).

Hashing does present us with integrity companies however not authenticity. With the intention to get each, we would wish a separate crypto-scheme that may compute authentication tags (a.okay.a Message Authentication Codes or MACs). Message Authentication Code (MAC) crypto scheme, in contrast to hashing, includes a secret key to limit integrity capabilities to solely events which have entry to it, which is whyツ?additionally it is known as keyed hashing or the extra related time period: cryptographic hash/checksum.

MAC might be constructed utilizing ciphers (similar to CMAC & GMAC) or hashes (HMAC). Nonetheless, it’s a bit tough to get cipher-based MACs proper. JDK doesn???t present any cipher-based MAC constructions too. Rule of thumb: keep away from cipher-based MAC, even when encountered in some third social gathering suppliers. We have already got a extra trouble-free choice with HMAC, so why danger it? Going forward, we are going to simply be specializing in HMACs.

HowTo: How Does it Work?

This crypto scheme works round a central MAC algorithm, which takes 2 items of data; symmetric key (okay) and plain textual content message to be authenticated (M) and computes Message Authentication Code. Thus, MAC = HMAC(Okay,M).

The MAC algorithm (HMAC) takes the message (M) of arbitrary size and generates mounted dimension authentication tags (or MACs).

Message Authentication Steps:

  1. A symmetric key(Okay) is established between sender and receiver, usually utilizing a safe channel.
  2. The sender computes MAC, utilizing a safe HMAC algorithm on message M and symmetric key(Okay).
  3. The message is appended with MAC and despatched throughout to the receiver i.e., M || MAC is distributed to the receiver.
  4. Receiver pulls aside M and MAC and recomputes MAC from M utilizing the identical HMAC algorithm as sender and symmetric key(Okay).
  5. If the receiver computed MAC == sender despatched MAC, authenticity, and integrity of acquired M is verified. This suggests messages have reached acquired untampered from the acknowledged sender.

HowTo: Development of HMAC


HowTo: Design

We might primarily must make two safe choices:

HowTo: Which HMAC Algorithm to Use?

It must be clear, HMAC computing algorithm is central on this MAC development. JCA does present a couple of of the not-so-safe HMACs for backward compatibility. Keep away from these. The checklist of safe JCA offered HMAC algorithms are:


Observe:ツ?Collision resistance weak spot of the underlying hash doesn???t impression the safety power of an HMAC scheme. Having mentioned that MD5 is already out of the door[7] by most protocols and requirements, but in addition SHA1 is severely discouraged as a consequence of its decrease output dimension and numerous different causes.

info-iconツ? Use solely the SHA2 or SHA 3 household of underlying hash on your HMAC algorithm.

Your MAC scheme is as safe as your key. Be sure that:

info-iconツ? Key dimension of Symmetric Key(Okay) is >= 128 bits


info-iconツ? A computed Symmetric key must be safeguarded as some other cryptographic keying materials, i.e., it must be accessed solely by concerned events.


HowTo: Implement

Placing this all collectively, let’s take a look at pseudo-code:

  • Step 1: Computing a Symmetric Key (Okay), for the required HMAC algorithm, use advisable key dimension. As mentioned within the submit on encryption/decryption we’d be utilizing KeyGenerator.
KeyGenerator keygen = KeyGenerator.getInstance("HmacSHA512"); // Use a safe underlying hash for HMAC algorithm.  
keygen.init(256); // Explicitly initializing keyGenerator. Specify key dimension, and belief the supplier equipped randomness. 
SecretKey hmacKey = keygen.generateKey(); // SecretKey holds Symmetric Key(Okay)

  • Step 2: Compute MAC utilizing Mac class by offering computed symmetric key (Okay), and plain textual content message M to a safe HMAC algorithm.
Mac mac = Mac.getInstance("HmacSHA512"); // get entry to Mac object which implements HmacSHA512 algorithm. mac.init(new SecretKeySpec(hmacKey.getEncoded(), "HmacSHA512")); // Initialize Mac object with symmetric key(Okay), identical as with sender
mac.replace(message.getBytes()); // add message knowledge (M) to Mac object to compute Mac. 
String senderMac = mac.doFinal(); // Compute MAC

  • Step 3: Ship MAC to receiver aspect Message and computed MAC despatched from sender to receiver.
  • Step 4: On the receiver???s aspect, re-compute MAC by offering symmetric key (Okay), plain textual content message (M) to the identical safe HMAC algorithm used on the sender aspect.
Mac mac = Mac.getInstance("HmacSHA512"); // get entry to Mac object which implements identical algorithm used on sender aspect 
mac.init(new SecretKeySpec(hmacKey.getEncoded(), "HmacSHA512")); // Initialize Mac object with symmetric key(Okay), identical as with sender
mac.replace(message.getBytes()); // add message knowledge (M) to Mac object to compute Mac. 
String receivedMac = mac.doFinal(); // Compute MAC

For those who acquired MAC, and re-computed MAC are an identical on the receiver aspect, M is acquired untampered from the anticipated sender (social gathering with symmetric key(Okay)).

if (macComputationAPI.computeMac(hmacKey, knowledge).equals(mac)){
    return "Authentication and Integrity checked cleared on Obtained message " + M;
} else {
    return "Message " + M + " acquired on receiver aspect is tampered with, or would not come from the anticipated sender";

Observe: Peeping into the upcoming Java 16 launch notes, there are not any new additions other than some backend solar supplier assist, which shouldn’t impression any of those discussions.

Refer toツ?MACComputationAPI for an entire code instance.

HowTo: Do’s and Don’ts


  • Use solely safe underlying hashes as HMAC algorithm.
  • The important thing dimension for use must be >= 128ツ?bits.
  • Symmetric Key(Okay) used on sender and receiver sides, must be safeguarded as any secret key.


  • Don???t use underlying hash algorithms from the 90s similar to HmacMD5 & HmacSHA1, even when JDK supplies these.

HowTo: The place is it Used (Functions)?

MACs are essential in most safe communication protocols, similar to tls, ssh, and so on. Simply specializing in trendy functions, which most builders would encounter in some unspecified time in the future, can be for authorization mechanisms. MACs are very generally used for authorization functions when it comes to API Keys, JWT (Json Internet Tokens)[3][4] & session IDs. Taking the instance of JWT and seeing the way it matches; Server indicators a json payload with one of many signing algorithms, HMAC-SHA256 being one in all them. This signature is connected to the encoded payload and handed to the shopper. The shopper in flip contains this unique payload (authenticity) and signature in every request thereafter speaking to the server. The server verifies this signature to determine integrity.

You may experiment with sender and receiver endpoints of a MAC by invoking corresponding endpoints from Java Crypto MicroService.

This concludes our related dialogue on utilizing Message Authentication Codes. We are going to proceed speaking about a couple of extra cryptographic functions and constructions in future posts. Keep tuned!


  • MAC supplies authenticity and integrity safety companies.
  • Keep away from cipher (CMAC) based mostly MACs, use solely Hash-based MACs.
  • MACs are generated for a given message, utilizing a symmetric key shared by each sending and receiving events.
  • Use solely safe hashes from SHA2 and SHA3 households of hashing algorithms.
  • Be sure that Secret Key (Okay) is safeguarded and is of minimal 128 bits in size.
  • Generally used for authorization mechanisms in trendy functions.


Oracle/Java Documentation:

1. Java Cryptographic Structure

2. Java Safety Commonplace Algorithm Names


3. RFC 7519 discusses JWT customary

4. RFC 7518 part 3.1 mentions checklist of signing algorithms.

5. NIST FIPS 198-1 discusses keyed-HMAC.

6. NIST SP 800-107 Part 5.3, discusses safety power of HMAC scheme.

7. RFC 6151: Safety Issues for the MD5 Message-Digest and the HMAC-MD5 Algorithms


8. JWT Introduction: Json Internet Tokens

9. E book Title – Severe Cryptography – Jean Philippe Aumasson

10. E book Title – Understanding Cryptography – Christof Paar & Jan Pelzl

*** It is a Safety Bloggers Community syndicated weblog from Utility Safety Analysis, Information, and Schooling Weblog authored by msheth@veracode.com (msheth). Learn the unique submit at: https://www.veracode.com/weblog/secure-development/message-authentication-code-mac-using-java

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also

Washoe County Community Development Public Workshop (via Zoom) on March 10, 2021 from 5:30 to 7:00 pm

Washoe County Neighborhood Growth Public Workshop (by way of Zoom) on March 10, 2021…