HMAC and MAC Explained Simply — Building Secure Auth With JWTs (2024)

HMAC and MAC Explained Simply — Building Secure Auth With JWTs (3)

HMACs and MACs are authentication codes and are often the backbone of JWT authentication systems. Let’s take a look at how they work!

MAC — Message Authentication Code

MACs are exactly what they sound like; small codes that allow receivers of messages to know who the sender was (authentication). A MAC code is calculated by using a message and a secret key as inputs. Anyone who has a copy of that secret key can then verify that that code and message were created by someone with the same key.

HMAC and MAC Explained Simply — Building Secure Auth With JWTs (4)

One way this is accomplished is by using a hash function, like SHA-256. Simply put, a hash function takes an input and returns an output, where:

  • The output is very unlikely to be the same for different inputs
  • The output is always the same for the same inputs
  • The output is not predictable — changing the input in any way results in a seemingly random change to the output

Given this, a naive example of MAC generation by the sender could be:

macCode = sha256('thisIsASecretKey1234' + 'my message here')

Then the verification by the receiver would be:

macCode == sha256('thisIsASecretKey1234' + 'my message here')

Note that MACs don’t necessarily use a hash function, but a hash can be used as a “signing” mechanism. For a further reading look at the MAC Wikipedia article.

HMAC — Hash-Based Message Authentication Code

An HMAC is a kind of MAC. All HMACs are MACs but not all MACs are HMACs. The main difference is that an HMAC uses two rounds of hashing instead of one (or none). Each round of hashing uses a section of the secret key. As a naive example:

sha256('thisIsASe' + sha256('cretKey1234' + 'my message here'))

Which is a simplified version of the function given in RFC-2104.

Why use HMAC? Why do we need to hash twice?

With many hash functions, it is relatively easy to change the message (without knowing the key) and obtain another valid MAC. This is called a length extension attack. No known extension attacks are known against the current HMAC specification.

To read further about HMACs take a look here.

HMACs with JWTs

HMAC and MAC Explained Simply — Building Secure Auth With JWTs (5)

If you’ve ever used JWTs for authentication schemes on a web app, you know that JWTs are wonderful for keeping track of who is who. A JWT (when using HMAC as the signing scheme) is basically just an HMAC message where the message data is a JSON object.

The interesting thing about the JWT system is that the sender and the receiver of the JWT are typically the same entity, that is, the webserver. Let’s look at an example:

  • User gives the server a username and password
  • Server verifies the username and password are correct
  • Server generates a JWT using HMAC:
hmacCode = sha256('thisIsASe' + sha256('cretKey1234' + '{"email":"lane@qvault.io"}'))
  • Server responds with the following (decoded) JWT:
header.{"email":"lane@qvault.io"}.hmacCode
  • User decides to update his/her profile picture by sending the following request:
PUT /users/profile_picture
Authentication: Bearer header.{"email":"lane@qvault.io"}.hmacCode

{"new_picture": "http://linktopicture.com/mypic"}

  • Server parses the JWT. The JWT says the user is “lane@qvault.io”
  • The server verifies that the user really is Lane by validating the HMAC code, because only someone with access to the secret key ‘thisIsASecretKey1234’ could have made the HMAC code that corresponds to the ‘lane@qvault.io’ message
  • If the verification is successful the server updates Lane’s profile picture

This is a very basic example of how JWT’s work, and skips over some implementation details. If you want to learn more about the specifics, take a look at the explanation on jwt.io.

If you feel that I missed anything important, or have any questions, feel free to contact me on twitter!

Lane on Twitter: @wagslane

Lane on Dev.to: wagslane

Lane on Medium: @wagslane

Download Qvault: https://qvault.io

Star our Github: https://github.com/q-vault/qvault

The post HMAC and MAC Explained Simply — Building Secure Auth With JWTs appeared first on Qvault.

HMAC and MAC Explained Simply — Building Secure Auth With JWTs (2024)

FAQs

HMAC and MAC Explained Simply — Building Secure Auth With JWTs? ›

A JWT (when using HMAC as the signing scheme) is basically just an HMAC message where the message data is a JSON object. The interesting thing about the JWT system is that the sender and the receiver of the JWT are typically the same entity, that is, the webserver.

Is HMAC secure for JWT? ›

JSON Web Tokens (JWT) can be integrity protected with a hash-based message authentication code (HMAC). The producer and consumer must posses a shared secret, negotiated through some out-of-band mechanism before the JWS-protected object is communicated (unless the producer secures the JWS object for itself).

What is MAC and HMAC? ›

A message authentication code (MAC) is similar to a cryptographic hash, except that it is based on a secret key. When secret key information is included with the data that is processed by a cryptographic hash function, the resulting hash is known as an HMAC.

Is HMAC more secure than MAC? ›

Second, HMAC provides a higher level of security assurance compared to traditional MAC algorithms. This is due to the additional complexity introduced by the two-pass computation and the use of padding. These additional steps make it harder for an attacker to exploit any weaknesses in the underlying hash function.

What is HMAC for dummies? ›

Hash-based message authentication code (or HMAC) is a cryptographic authentication technique that uses a hash function and a secret key. With HMAC, you can achieve authentication and verify that data is correct and authentic with shared secrets, as opposed to approaches that use signatures and asymmetric cryptography.

Is HMAC still secure? ›

Because the hash is generated with a secret key, a correctly computed HMAC assures the recipient that the message came from a source possessing the correct shared secret key and therefore is authentic. This double-check of both integrity and authenticity provides a high level of security for data transmission.

What is the difference between HMAC and token based authentication? ›

Use Cases: Token-based authentication is often preferred for web applications and APIs that require user authentication and authorization. HMAC authentication is commonly used for securing API endpoints, especially in scenarios where direct user interaction is not involved (e.g., machine-to-machine communication).

Is HMAC obsolete? ›

This method is obsolete in . NET 5 and later versions. By default, this overload uses the SHA-1 implementation of HMAC. If you want to specify a different implementation, use the Create(String) overload, which lets you specify an algorithm name, instead.

What is the secret key in HMAC? ›

The secret cryptographic key is what enables a user to make an encrypted message readable after it has been encrypted by an algorithm. In an HMAC transaction, the client and server must agree on the secret key. This provides a way to decode messages, which must stay secret, to maintain the transaction's integrity.

What is the main advantage of HMAC? ›

Ultimately, HMAC provides a great layer of security for companies that have sensitive data that needs protecting. It's an important measure to protect data integrity from attackers and offers a clear indication if data has been compromised.

What is the difference between SHA-256 and HMAC? ›

HMAC stands for "Hash-based Message Authentication Code," and SHA-256 refers to the Secure Hash Algorithm 256-bit variant. HMAC-SHA-256 combines the strength of SHA-256's cryptographic hashing with HMAC's ability to authenticate the integrity and source of a message.

Does TLS use HMAC? ›

HMAC is used within the IPsec, SSH and TLS protocols and for JSON Web Tokens.

What is the difference between HMAC and AES? ›

AES encryption is used to encrypt data while HMAC is used to authenticate data. Both operations use the same symmetric key, but they use the key in different ways. AES encryption uses the key to encrypt the data, while HMAC uses the key to generate a message authentication code (MAC) for the data.

Is HMAC sha512 Secure? ›

HMACs provide security against tampering because knowledge of the secret key is required to change the message and reproduce the correct hash value. HMACSHA512 accepts keys of any size, and produces a hash sequence of length 512 bits.

What is the safest JWT algorithm? ›

Some of the most popular and secure algorithms include:
  • HS256 (HMAC with SHA-256): This is a symmetric algorithm that uses a shared secret key to sign and verify tokens. ...
  • HS384 (HMAC with SHA-384): This is another symmetric algorithm with a longer key size, providing increased security compared to HS256.

Which is not secure enough for any JWT HMAC SHA algorithm? ›

"The specified key byte array is 192 bits which is not secure enough for any JWT HMAC-SHA algorithm. The JWT JWA Specification (RFC 7518, Section 3.2) states that keys used with HMAC-SHA algorithms MUST have a size >= 256 bits (the key size must be greater than or equal to the hash output size). Consider using the io.

What does HMAC protect against? ›

HMAC is a technique for cryptographic authentication. It uses both a cryptographic hash function and a shared secret key to encrypt information and protect it from unauthorized access.

Top Articles
Luxury hotels, boutique hotels and fine dining restaurants
Is 35k a good salary in the UK? | 35k after tax
Foxy Roxxie Coomer
Gamevault Agent
Algebra Calculator Mathway
25X11X10 Atv Tires Tractor Supply
St Als Elm Clinic
Hallowed Sepulchre Instances & More
No Credit Check Apartments In West Palm Beach Fl
Es.cvs.com/Otchs/Devoted
Roster Resource Orioles
Roof Top Snipers Unblocked
Msu 247 Football
Busted Newspaper Fauquier County Va
Gayla Glenn Harris County Texas Update
Qhc Learning
Evil Dead Rise Showtimes Near Regal Sawgrass & Imax
Craigslist Houses For Rent In Milan Tennessee
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
8005607994
Www.paystubportal.com/7-11 Login
Prey For The Devil Showtimes Near Ontario Luxe Reel Theatre
Scripchat Gratis
Unable to receive sms verification codes
Motorcycle Blue Book Value Honda
Leben in Japan – das muss man wissen - Lernen Sie Sprachen online bei italki
Weather October 15
O'reilly's In Monroe Georgia
Play It Again Sports Forsyth Photos
Uno Fall 2023 Calendar
Our Leadership
Motor Mounts
Plasma Donation Racine Wi
Craig Woolard Net Worth
Math Minor Umn
Appleton Post Crescent Today's Obituaries
Scanning the Airwaves
Streameast.xy2
Poe Flameblast
877-292-0545
140000 Kilometers To Miles
Obituaries in Hagerstown, MD | The Herald-Mail
The Nikki Catsouras death - HERE the incredible photos | Horror Galore
My Gsu Portal
Adams-Buggs Funeral Services Obituaries
Rheumatoid Arthritis Statpearls
Doelpuntenteller Robert Mühren eindigt op 38: "Afsluiten in stijl toch?"
Craigslist Anc Ak
Minute Clinic Mooresville Nc
Where and How to Watch Sound of Freedom | Angel Studios
Buildapc Deals
Used Curio Cabinets For Sale Near Me
Latest Posts
Article information

Author: Manual Maggio

Last Updated:

Views: 6261

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Manual Maggio

Birthday: 1998-01-20

Address: 359 Kelvin Stream, Lake Eldonview, MT 33517-1242

Phone: +577037762465

Job: Product Hospitality Supervisor

Hobby: Gardening, Web surfing, Video gaming, Amateur radio, Flag Football, Reading, Table tennis

Introduction: My name is Manual Maggio, I am a thankful, tender, adventurous, delightful, fantastic, proud, graceful person who loves writing and wants to share my knowledge and understanding with you.