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.
npm install sodium-hmacVerified import paths — ran on the pinned version, not inferred.
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.
Ensure `hmac.init(key)` is invoked once after creating the HMAC instance and before processing any data chunks.
When supplying a custom hash function (e.g., from `libsodium` or other crypto libraries), ensure it exposes all required methods and properties. Refer to the `sha256` or `sha512` exports as examples.
Always assign the result of `hmac.final()` to a variable, e.g., `const output = hmac.final();`.
Convert all string or other data types to `Buffer.from('your-data')` or `b4a.from('your-data')` before passing them to HMAC functions.Verify that the custom hash object passed to `new HMAC(hash)` includes all required methods: `init`, `update`, `final`, and properties: `BYTES`, `STATEBYTES`. Use `sha256` or `sha512` exports as a reference.
Call `hmac.init(Buffer.from('your-key'))` immediately after creating the `HMAC` instance and before calling `hmac.update(data)`.Ensure all input data, including the key and message parts, are converted to `Buffer` or `Uint8Array` instances, for example, using `Buffer.from('string')` or `b4a.from('string')`.No dependency data recorded yet.