Created
September 14, 2022 12:22
-
-
Save le0pard/5bc89cbdc0fb4654f2d8456026370660 to your computer and use it in GitHub Desktop.
Hmac sha-256 hexadecimal on webcrypto
This file contains 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
const ALGORITHM = { | |
name: 'HMAC', | |
hash: 'SHA-256' | |
} | |
const bufferToHex = (buffer) => ( | |
[...new Uint8Array(buffer)] | |
.map(b => b.toString(16).padStart(2, '0')) | |
.join('') | |
) | |
const hmac256 = async (secret, data) => { | |
const enc = new TextEncoder('utf-8') | |
const key = await crypto.subtle.importKey('raw', enc.encode(secret), ALGORITHM, false, ['sign', 'verify']) | |
const signature = await crypto.subtle.sign(ALGORITHM.name, key, enc.encode(data)) | |
return bufferToHex(signature) | |
} | |
export default hmac256 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment