MAC and HMAC simply explained (with JavaScript snippets)

Gonzalo Ruiz de Villa
gft-engineering
Published in
3 min readOct 26, 2021

--

[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…

--

--

Gonzalo Ruiz de Villa
gft-engineering

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