CodeBlanks Logo Icon CodeBlanks

HMAC

Learn HMAC with crypto.createHmac.

HMAC

HMAC (Hash-based Message Authentication Code) adds a key to a hash. Only those with the right key can verify the hash; so it is used for data integrity and authentication.

Example: crypto.createHmac("sha256", "key").update("data").digest("hex"). Here "key" is a symmetric secret shared by sender and receiver. The difference from createHash: a hash can be produced by anyone, an HMAC only by the key holder. It is common for webhook signing, JWT (JSON Web Token) and API request verification. The receiver computes the same HMAC with their key; if it matches, the data is untampered and from a trusted source. If the key leaks the HMAC is useless; so the key is kept in an environment variable.

HMAC verification

After producing an HMAC, to verify it the receiver computes the same hash with the same key and compares the two. If they match, the data is safe.

Example: const expected = crypto.createHmac("sha256", key).update(data).digest("hex"); if (expected === received) console.log("Valid");. For comparison crypto.timingSafeEqual is safer than ===; it prevents timing attacks. A timing attack leaks information from comparison duration. The HMAC key must be the same on both sides; if different, the hash differs. The key length should not be smaller than the algorithm's block size; for sha256 32 bytes is recommended. In production the key is read from process.env.HMAC_KEY.

Practice Sign data with HMAC

Import with const crypto = require("node:crypto");. Sign with const hmac = crypto.createHmac("sha256", "anahtar").update("veri").digest("hex");. Print the length with console.log("HMAC length: " + hmac.length).

Starter code

index.js
// Import the crypto module
// write here

// Sign "veri" with HMAC
// write here

// Print "HMAC length: ..."
// write here

Sample solution

index.js
const crypto = require("node:crypto");
const hmac = crypto.createHmac("sha256", "anahtar").update("veri").digest("hex");
console.log("HMAC length: " + hmac.length);

Expected output

HMAC uzunluğu: 64

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many parameters does createHmac take?

index.js
crypto.createHmac("sha256", "anahtar")
  • 1: algoritma
  • 3: algoritma, anahtar, veri
  • 0: parametre yok
  • 2: algoritma ve anahtar Correct answer

Explanation: createHmac takes two: algorithm and key.

2 Match each piece to its role

Term Meaning
createHmac Creates keyed hash
key Shared secret
update Feeds data
timingSafeEqual Safe comparison

3 Complete the createHmac call

Question
const hmac = crypto.____("sha256", "anahtar").update("veri").digest("hex");
Answer
const hmac = crypto.createHmac("sha256", "anahtar").update("veri").digest("hex");

Explanation: createHmac creates a keyed hash.

All lessons in Intermediate