Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carloswm85/b5e93989f9049d9a2935a78c0d4677d5 to your computer and use it in GitHub Desktop.
Save carloswm85/b5e93989f9049d9a2935a78c0d4677d5 to your computer and use it in GitHub Desktop.

I'm trying to make this work.

https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/sign#hmac_2

async function sha256_2(key, message) {
	// Step 1
	const msgUint8_key = new TextEncoder().encode(key); // encode as (utf-8)
	const msgUint8_message = new TextEncoder().encode(message); // encode as (utf-8)
	// Step 2
	const importedKey = await crypto.subtle.importKey('raw', msgUint8_key, {
		name: 'HMAC',
		hash: 'SHA-256'
	}, true, ['sign']);
	// Step 3
	const signedKey = await crypto.subtle.sign('HMAC', importedKey, msgUint8_message);
	const hashArray = Array.from(new Uint8Array(signedKey)); // convert buffer to byte array
	const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string
	return hashHex;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment