Function: hmac()
hmac(
data,key,algorithm?):string
Sign data with a key: compute its hmac, a keyed hash that only a holder of the key can produce. Use it to detect tampering (webhooks, signed links); it does not hide the data, and is not a password hash. The Mac provider does the same with configured keys and key rotation.
Parameters
data
string | Uint8Array<ArrayBufferLike>
The data to sign: a string (signed as its UTF-8 bytes) or bytes.
key
string | Uint8Array<ArrayBufferLike>
The secret key: a string (used as its UTF-8 bytes, not decoded) or bytes, not empty. Use a random key of 32 bytes, such as generateSecret returns.
algorithm?
The hash function; 'sha256' by default.
Returns
string
The hmac, base64url encoded without padding.
Throws
When the key is empty.
Example
typescript
import {generateSecret, hmac, verifyHMAC} from 'lakutata/security'
const key: string = process.env.WEBHOOK_KEY ?? generateSecret()
const body: string = JSON.stringify({order: 42, status: 'paid'})
//Sent in a header along with the body
const signature: string = hmac(body, key, 'sha256')
console.log(verifyHMAC(body, signature, key, 'sha256'))