← Back to Node.js, page 4

nodejs-0080 · Easy fresher

How do you create hashes and HMACs with the crypto module, and how do you verify a webhook signature?

crypto.createHash('sha256') produces a fixed-size fingerprint of data. It cannot be reversed, and the same input always gives the same output. An HMAC (createHmac) mixes in a secret key, so only someone with the key can create or check the value. Services use HMACs to sign webhooks. Verify them with crypto.timingSafeEqual.

Full answer

Hash: a function that turns any amount of data into a short fixed-size value (SHA-256 gives 32 bytes). A tiny change in the input changes the output completely. Uses: checksums, cache keys, file integrity, content addressing. Not for passwords (use scrypt or argon2 for those).

Choosing an algorithm: SHA-256 or SHA-512 for general use. MD5 and SHA-1 are broken for security purposes, though still seen in old checksums.

API:

  • crypto.createHash('sha256').update(data).digest('hex'). update can be called many times, so a file can be hashed as a stream.
  • crypto.hash('sha256', data, 'hex') is a one-shot helper in recent Node versions.
  • Encodings for the result: hex, base64, base64url, or a Buffer when no encoding is given.

HMAC (hash-based message authentication code): hash(key, message) built so that the result proves two things: the message was not changed, and the sender knew the key. API: crypto.createHmac('sha256', secret).update(body).digest('hex').

Webhook verification, step by step:

  1. The provider sends the body and a signature header, computed as HMAC of the raw body with a shared secret.
  2. Your server must use the raw bytes of the body, not the re-serialized JSON. Parsing and stringifying can change spacing and key order.
  3. Compute the HMAC with your copy of the secret.
  4. Compare with crypto.timingSafeEqual on buffers of equal length, never with ===.
  5. Also check a timestamp in the signed data to stop replay of old requests.

Hashing is not encryption. Nothing can be recovered from a hash.

javascript
const crypto = require('node:crypto');

// 1. A hash is deterministic and fixed in size.
const text = 'abc';
console.log('sha256("abc"):', crypto.createHash('sha256').update(text).digest('hex'));
console.log('one-shot helper gives the same:', crypto.hash('sha256', text) === crypto.createHash('sha256').update(text).digest('hex'));
console.log('a small change changes everything:', crypto.createHash('sha256').update('abd').digest('hex').slice(0, 16), '...');
console.log('hash length is always 32 bytes:', crypto.createHash('sha256').update('x'.repeat(10000)).digest().length);

// 2. Hashing in pieces gives the same result as hashing all at once.
const parts = crypto.createHash('sha256').update('a').update('b').update('c').digest('hex');
console.log('hashing in pieces matches:', parts === crypto.createHash('sha256').update('abc').digest('hex'));

// 3. Signing and verifying a webhook body.
const secret = 'shared-webhook-secret';
function sign(rawBody) {
  return crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
}
function verify(rawBody, signatureHex) {
  const expected = Buffer.from(sign(rawBody), 'hex');
  const received = Buffer.from(signatureHex, 'hex');
  return expected.length === received.length && crypto.timingSafeEqual(expected, received);
}

const body = '{"event":"result.published","studentId":42}';
const signature = sign(body); // the sender computes this and sends it in a header
console.log('valid signature accepted:', verify(body, signature));
console.log('changed body rejected:   ', !verify(body.replace('42', '43'), signature));
console.log('wrong signature rejected:', !verify(body, 'a'.repeat(64)));

The hash of 'abc' is a well-known test value, so you can compare the first line with any SHA-256 reference. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): sha256("abc"): ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad one-shot helper gives the same: true a small change changes everything: a52d159f262b2c6d ... hash length is always 32 bytes: 32 hashing in pieces matches: true valid signature accepted: true changed body rejected: true wrong signature rejected: true

Key points

  • Hashes are one-way fingerprints. Use SHA-256 or stronger.
  • HMAC adds a secret key for authentication.
  • Verify webhooks on the raw body with timingSafeEqual.
  • Add a timestamp check against replay.

Common mistakes

  • Using MD5 or SHA-1 for security decisions.
  • Hashing passwords with plain SHA-256.
  • Verifying the HMAC over a re-serialized JSON body.
  • Comparing signatures with === or ==.

Follow-ups

  • What is a length extension attack, and why does HMAC avoid it?
  • How do you hash a 5 GB file in Node.js?
  • How would you rotate a webhook secret without downtime?

Tips

  • Keep hash, HMAC and encryption separate in your explanation.
  • Say 'raw body' for webhooks.
  • Mention timestamps against replay.