Message Authentication Code (MAC) is a cryptography primitive that ensures data integrity by combining a standard hash function with a secret key.

The inner workings of hash functions are public knowledge. Anyone can use standard hash functions to create digests for arbitrary inputs, and there is no way to verify the authenticity and integrity of the messages and the digests when transmitted over the network. This challenge is not uncommon. Like many cryptography primitives, using only one technique to achieve practical use is often insufficient — we need to combine different primitives. MAC is designed to overcome the integrity problem by using hash functions with a secret key.

For example, when a user signs into a website and obtains an authentication token (often stored in a cookie) for subsequent requests, if the cookie is the standard hash digest of the user’s username and a timestamp, anyone can replace the username and create a different hash to pretend to be a different user. The server cannot tell if the cookie is tempered, as it will get the same hash when it runs the standard hash functions on the tampered message. To provide integrity verification of the cookie, the web server can use MACs. That is, to combine the username with a secret key in the format of key || username or username || key, hash it ( hash(‘kye’ || ‘username’), and then use the output as the authentication token (the output of MAC algorithms is called an authentication tag). The user cannot forge a valid hash for a different username without knowing the secret key; therefore, the data integrity of the authentication token is protected. This is especially suitable for web services that rely on stateless HTTP requests and distributed web servers, which often consist of many physical nodes, and any request from any user could be sent to any node at any time. With authentication tags, as long as all the nodes share the same secret key, there is no need to communicate with each other to verify authenticated users, e.g., storing authentication cookies in a shared database.