HMAC Generator — TypeScript source
Generate a keyed-hash HMAC (SHA-1/256/384/512) for a message and secret. Runs entirely in your browser via Web Crypto, with a shareable link to your exact input.
This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Keyed-hash HMAC via the Web Crypto API (SubtleCrypto). Pure logic - no React,
// no DOM. Deterministic for a given (message, secret, algorithm); async only
// because SubtleCrypto is. Requires a secure context (https or localhost).
//
// Mirrors src/lib/base64.ts (pure, testable surface) and the inline digest
// helper in src/tools/HashGenerator.tsx.
export type HmacAlgorithm = 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512';
/** Lowercase hex of an ArrayBuffer. */
function toHex(buf: ArrayBuffer): string {
return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');
}
/**
* Compute the HMAC of `message` under `secret` and return it as lowercase hex.
* Both inputs are UTF-8 encoded. Rejects if `secret` is empty (SubtleCrypto
* rejects a zero-length key) or if `algorithm` is unsupported.
*/
export async function hmacHex(
message: string,
secret: string,
algorithm: HmacAlgorithm = 'SHA-256',
): Promise<string> {
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
'raw',
encoder.encode(secret),
{ name: 'HMAC', hash: algorithm },
false,
['sign'],
);
const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(message));
return toHex(signature);
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →