Skip to content

Function: verifyHMAC() ​

verifyHMAC(data, signature, key, algorithm?): boolean

Check that a signature is the HMAC of data with a key, in a time that does not depend on the signature (see constantTimeEqual).

Parameters ​

data ​

string | Uint8Array<ArrayBufferLike>

The signed data, exactly as it was signed (the raw request body, not a re-serialized copy).

signature ​

string

The signature to check, base64url encoded without padding as hmac returns it; a hex or padded signature does not match.

key ​

string | Uint8Array<ArrayBufferLike>

The secret key the data was signed with: a string (used as its UTF-8 bytes) or bytes, not empty.

algorithm? ​

HMACAlgorithm

The hash function the data was signed with; 'sha256' by default.

Returns ​

boolean

true when the signature matches.

Throws ​

When the key is empty.

Example ​

typescript
import {InvalidSignatureException, verifyHMAC} from 'lakutata/security'

declare const rawBody: string
declare const signatureHeader: string
declare const webhookKey: string

if (!verifyHMAC(rawBody, signatureHeader, webhookKey)) {
    throw new InvalidSignatureException('The signature of the webhook is not valid')
}

Released under the MIT License.