gft-engineering
Published in

gft-engineering

MAC and HMAC simply explained (with JavaScript snippets)

[TL;DR] I will easily introduce MAC and HMAC concepts and provide very simple JavaScript sample code that you will be even able to use in your browser console.

MAC stands for Message Authentication Code, and it also known as tag, and in communications sometimes is substituted by MIC or message integrity code.

What is a MAC for?

From a general point of view, a MAC is a piece of information that protects a message by:

  • verifying data integrity, i.e. that the message has not been tampered.
  • verifying its authenticity, confirming that it comes from the stated sender.

This is specially important when the message has to travel through unsecured channels. Specific use cases will be listed below.

How does MAC work?

  1. The sender A wants to send a message M to a receiver B.
  2. The sender A and the receiver B share a key K.
  3. The sender uses a signing algorithm S to calculate a tag T given the shared key K and the message M.
  4. The receiver B uses a verifying algorithm V to verify the authenticity of the message M given the key K and the tag T. That is, the algorithm returns accepted if neither the tag T nor the message M have been tampered with. Otherwise, it returns rejected.

Requisites for a secure message authentication code

It must resist an adversary’s attempt to forge tags for arbitrary, selected or all messages, including under conditions of known- or chosen-message. That is, it must resist the forgery of digital signature.

It should be computationally infeasible to compute a valid tag of the given message without knowledge of the key.

HMAC

HMAC (hash-based message authentication code) is a particular type of message authentication code (MAC). As with any MAC, the hash function can be used for both verifying data integrity and authentication of the message.

The hash function name is used to term the different MAC functions with the pattern HMAC-X, for example HMAC-SHA256 or HMAC-SHA3–512.

JavaScript example

Open your browser dev tools to try the following snippets on the console. These snippets should work also with Node.js.

This function implements the HMAC-SHA256 version:

async function hmacSha256Hex(secret, message) {
const enc = new TextEncoder("utf-8");
const algorithm = { name: "HMAC", hash: "SHA-256" };
const key = await crypto.subtle.importKey(
"raw",
enc.encode(secret),
algorithm,
false, ["sign", "verify"]
);
const hashBuffer = await crypto.subtle.sign(
algorithm.name,
key,
enc.encode(message)
);
const hashArray = Array.from(new Uint8Array(hashBuffer)); const hashHex = hashArray.map(
b => b.toString(16).padStart(2, '0')
).join('');
return hashHex;
}

Using this function is as simple as the following:

await hmacSha256Hex(
"key",
"The quick brown fox jumps over the lazy dog"
);
//f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8

In the previous example, mapping to the MAC explanation, we have that key K has the value “key”, the message M has the value “The quick brown fox jumps over the lazy dog” and the tag T has the value “f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8”.

Usage scenarios for HMAC

So by now, you should understand how HMAC works — if not, please tell me in the comments which is the obscure part so I can improve it. You may wonder which are particular scenarios for this technology. Well, here are a few of them that will help you when you face different challenges:

  • Password reset link. You can send an e-mail with a reset link that is only valid for a certain time. With HMAC, you can do this without additional server states.
  • Links in verifying email addresses in order to create or activate accounts.
  • Authenticating data sent by external applications.
  • Authenticating form data that has been sent to the user browser and the posted back.
  • For internet of things (IoT) due to its low computational cost, in particular for Low-Power Wide-Area Networks.
  • HMAC based authentication (for instance, is the main authentication used by Amazon Web Services for request authentication).
  • As a data pseudonymisation technique, for example to comply with GDPR. This is, by the way, recommended by the European Union Agency for Cybersecurity (ENISA).

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gonzalo Ruiz de Villa

Engineer, Google Developer Expert , co-founder of Adesis Netlife and Kenobi Ventures. CTO @ GFT Group