Skip to content

Instantly share code, notes, and snippets.

@le0pard
Created September 14, 2022 12:22
Show Gist options
  • Save le0pard/5bc89cbdc0fb4654f2d8456026370660 to your computer and use it in GitHub Desktop.
Save le0pard/5bc89cbdc0fb4654f2d8456026370660 to your computer and use it in GitHub Desktop.
Hmac sha-256 hexadecimal on webcrypto
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