Created
April 23, 2025 23:35
-
-
Save ali-master/8e8251992b39ce555a777ca2cfc24087 to your computer and use it in GitHub Desktop.
Javascript HMAC with Crypto Subtle example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as b64ArrBufferConvertor from "base64-arraybuffer"; | |
const SECRET_HMAC_KEY = | |
"209C5BBE79E2752FD1E4E687AD410778DD098546CC9B15ECAB1AEB4F21A46EF2"; | |
async function importHmacSecretKey(secret: string) { | |
return crypto.subtle.importKey( | |
"raw", | |
new TextEncoder().encode(secret), | |
{ name: "HMAC", hash: "SHA-256" }, | |
false, | |
["sign", "verify"] | |
); | |
} | |
async function sign(text: string, secret = SECRET_HMAC_KEY) { | |
const key = await importHmacSecretKey(secret); | |
const signature = await crypto.subtle.sign( | |
"HMAC", | |
key, | |
stringToArrayBuffer(text) | |
); | |
return arrayBufferToBase64(signature); | |
} | |
async function verify(text: string, hash: string, secret = SECRET_HMAC_KEY) { | |
const key = await importHmacSecretKey(secret); | |
return await crypto.subtle.verify( | |
"HMAC", | |
key, | |
base64ToArrayBuffer(hash), | |
stringToArrayBuffer(text) | |
); | |
} | |
(async () => { | |
const text = "Hello World"; | |
const signedMessageSignature = await sign(text); | |
console.log(signedMessageSignature); | |
const isVerified = await verify(text, signedMessageSignature); | |
console.log(isVerified); | |
document.getElementById("app").innerHTML = ` | |
<h1>Subtle HMAC</h1> | |
<div> | |
<p>Secret Key: ${SECRET_HMAC_KEY}</p> | |
<p>Message: ${text}</p> | |
<p>Signed Message(Signature): ${signedMessageSignature}</p> | |
<p>Is verified? : ${isVerified}</p> | |
</div> | |
`; | |
})(); | |
// Convert Base64 to Array Buffer | |
export function base64ToArrayBuffer(base64String: string): ArrayBuffer { | |
return b64ArrBufferConvertor.decode(base64String); | |
} | |
// Convert Array Buffer to Base64 string | |
export function arrayBufferToBase64(arrayBuffer: ArrayBufferLike): string { | |
return b64ArrBufferConvertor.encode(arrayBuffer); | |
} | |
export function stringToArrayBuffer(data: string): ArrayBuffer { | |
return new TextEncoder().encode(data); | |
} | |
export function arrayBufferToString(data: ArrayBuffer): string { | |
return new TextDecoder().decode(data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment