Sodium HMAC Utility

2.1.0 · active · verified Tue Apr 21

sodium-hmac is a JavaScript utility library for creating Hash-based Message Authentication Codes (HMAC). Currently at stable version 2.1.0, this package provides both a streaming API for processing data in chunks and a simplified one-shot API for common SHA256 and SHA512 HMAC operations. Its key differentiator is the flexibility to integrate custom hash functions, provided they adhere to a specific interface (init, update, final, BYTES, STATEBYTES), allowing users to leverage various cryptographic primitives like Blake2b via external libraries such as `sodium`. Maintained by the Holepunch ecosystem, it focuses on reliable cryptographic primitives for secure data integrity and authentication. The library does not enforce specific external dependencies for its hash functions, making it adaptable to different environments and cryptographic backends.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates both the streaming and one-shot HMAC APIs, using built-in SHA256/SHA512 and conceptually showing how to integrate a custom hash function.

import { HMAC, sha256, sha512 } from 'sodium-hmac';
import b4a from 'b4a'; // A common Buffer-compatible utility for universal environments

const key = b4a.from('a-very-secret-key-of-at-least-32-bytes');
const dataPart1 = b4a.from('This is the first part ');
const dataPart2 = b4a.from('and this is the second part of the message.');

// 1. Using the streaming API with SHA256
const hmacSha256 = new HMAC(sha256);
hmacSha256.init(key);
hmacSha256.update(dataPart1);
hmacSha256.update(dataPart2);
const outputSha256 = hmacSha256.final();
console.log('HMAC-SHA256 (streaming):', outputSha256.toString('hex'));

// 2. Using the simple one-shot API with SHA512
const fullData = b4a.concat([dataPart1, dataPart2]);
const outputSha512 = HMAC.sha512(fullData, key);
console.log('HMAC-SHA512 (one-shot):', outputSha512.toString('hex'));

// 3. Demonstrating custom hash function integration (conceptual, requires 'sodium' or similar)
// Assuming 'sodium' is installed and provides a compatible blake2b hash interface.
/*
import sodium from 'sodium-native'; // or 'libsodium-wrappers'
const blake2b = {
  init: (state, key) => sodium.crypto_generichash_init(state, key, 64), // 64 bytes for BLAKE2b
  update: sodium.crypto_generichash_update,
  final: (state, out) => sodium.crypto_generichash_final(state, out, 64),
  BYTES: 64,
  STATEBYTES: sodium.crypto_generichash_STATEBYTES
};

const hmacBlake2b = new HMAC(blake2b);
hmacBlake2b.init(key);
hmacBlake2b.update(fullData);
const outputBlake2b = hmacBlake2b.final(b4a.alloc(blake2b.BYTES));
console.log('HMAC-BLAKE2b (custom hash):', outputBlake2b.toString('hex'));
*/

view raw JSON →