crypto.createHmac()
Creates an HMAC (keyed hash) object for message authentication.
Syntax
crypto.createHmac(algorithm, key[, options]) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
algorithm | string | Yes | The hash algorithm, e.g. `'sha256'`. |
key | string | Buffer | KeyObject | Yes | The secret key. |
options | object | No | Stream options. |
Returns
Hmac — An Hmac stream you update and digest.
Examples
import { createHmac } from 'node:crypto';
const sig = createHmac('sha256', 'my-secret')
.update('payload')
.digest('hex');
console.log(sig.slice(0, 12));
Output
8b5f7e2a9c1d
import { createHmac, timingSafeEqual } from 'node:crypto';
function verify(body, header, secret) {
const expected = createHmac('sha256', secret).update(body).digest();
const got = Buffer.from(header, 'hex');
return expected.length === got.length && timingSafeEqual(expected, got);
}
Notes
Used for webhook signature verification (Stripe, GitHub) and signed
cookies. Always compare signatures with `timingSafeEqual`, never
`===`, to avoid timing attacks.