Node.js-style HMACs for Browsers

1.1.7 · maintenance · verified Sun Apr 19

create-hmac is a foundational package within the crypto-browserify ecosystem, designed to provide a Node.js-compatible API for HMAC (Hash-based Message Authentication Code) functionality, primarily for browser environments. It shims the Node.js `crypto.createHmac` API, allowing code written for Node.js to function in the browser without modification. For Node.js environments, it utilizes the native `crypto` module, ensuring optimal performance. The current stable version is 1.1.7. Due to the static nature of cryptographic algorithms implemented and its status as a shim for a well-defined API, its release cadence is infrequent, focusing on stability rather than active feature development. Its key differentiator is providing API compatibility, enabling universal JavaScript codebases to perform HMAC operations across different runtimes reliably, though modern browser applications might prefer the Web Crypto API for native performance and security benefits.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates both synchronous and streaming usage of `createHmac` with SHA-256 and SHA-512 algorithms, showcasing how to generate a digest and how to process data as a stream, similar to Node.js's native crypto module.

const createHmac = require('create-hmac');
const { Buffer } = require('buffer'); // Polyfill for browser environments

// Example 1: Synchronous HMAC generation
const secretKeySync = Buffer.from('supersecret', 'utf8');
const hmacSync = createHmac('sha256', secretKeySync);
hmacSync.update('This is the message to sign.');
const digestSync = hmacSync.digest('hex');
console.log('Synchronous HMAC (SHA256, hex):', digestSync);

// Example 2: HMAC as a stream
const secretKeyStream = Buffer.from('another-secret', 'utf8');
const hmacStream = createHmac('sha512', secretKeyStream);

hmacStream.on('data', chunk => {
  console.log('Stream chunk:', chunk.toString('hex'));
});

hmacStream.on('end', () => {
  console.log('Stream HMAC generation complete.');
});

hmacStream.write('Part one of the streamed data.');
hmacStream.write('Part two of the streamed data.');
hmacStream.end();

view raw JSON →