Message authentication
Authenticate API requests or webhook payloads with a shared secret.
Node.js · Function
Creates an Hmac object configured with a digest algorithm and secret key. Use the returned object to update data and produce the HMAC digest.
createHmac constructs an Hmac object using the requested digest algorithm and secret key. Feed data with update(), then call digest() to obtain the computed authentication code, optionally choosing an output encoding.
crypto.createHmac(algorithm, key[, options])| Name | Type | Description |
|---|---|---|
algorithm | string | Digest algorithm name, such as sha256 or sha512; supported values depend on the platform's OpenSSL version. |
key | string | Buffer | TypedArray | DataView | Secret HMAC key used to generate the cryptographic HMAC hash. |
options | Object | Optional stream.Transform options that configure stream behavior. |
<Hmac>
import { createHmac } from 'node:crypto';
const digest = createHmac('sha256', 'a secret')
.update('message')
.digest('hex');
console.log(digest);Creates a SHA-256 HMAC for the message with the supplied secret and prints its hexadecimal digest.
Authenticate API requests or webhook payloads with a shared secret.
Generate a deterministic integrity code for serialized data.
Process large input incrementally through the returned transform stream.
createHmac(algorithm, key[, options]) returns an Hmac object configured with the selected algorithm and key. The resulting object can process input with update() and produce the final digest with digest().
Follow-up: How can stream behavior be configured? Pass an options object; the documentation describes it as controlling stream behavior through stream.Transform options.
The algorithm is a string such as sha256 or sha512, and the key is the HMAC secret. The algorithm availability depends on the OpenSSL implementation used by the platform.
Follow-up: What should be checked when an algorithm fails? Check the algorithms supported by the platform's OpenSSL version.
Call update() with the data to authenticate, then call digest() to finalize and retrieve the HMAC. The digest can be requested in an encoding such as hexadecimal when using the Hmac API.
Follow-up: Can the same Hmac be finalized repeatedly? No; finalize one computation and create another Hmac for a new digest.
HmacHmac.prototype.update()Hmac.prototype.digest()crypto.getHashes()