Skip to content

HmacSign / HmacVerify (HMAC signatures)

SyncJS provides two functions for computing and verifying HMAC (Hash-based Message Authentication Code) signatures. HMACs are used to prove both the integrity and the authenticity of a message: only someone who holds the shared secret key can produce a valid MAC.

NOTE

These functions are available as of Syncplify Server! v7.1.1. If you are running an older version, upgrade to v7.1.1 or later to use them.

HmacSign

ts
function HmacSign(algorithm: string, key: string, data: string): string;

Computes an HMAC over data using key and returns the result as a lowercase hexadecimal string.

ParameterTypeRequirementExplanation
algorithmstringrequiredHMAC algorithm: sha256 or sha512
keystringrequiredThe shared secret key
datastringrequiredThe message to sign
Return valueExplanation
stringLowercase hex-encoded HMAC

Example

ts
var mac = HmacSign('sha256', GetSecret('webhook-signing-key'), payload);
Log('Signature: ' + mac);

HmacVerify

ts
function HmacVerify(
  algorithm: string,
  key:       string,
  data:      string,
  signature: string
): boolean;

Checks whether signature is the correct HMAC of data under key. Uses constant-time comparison internally to prevent timing-based attacks.

ParameterTypeRequirementExplanation
algorithmstringrequiredHMAC algorithm: sha256 or sha512
keystringrequiredThe shared secret key
datastringrequiredThe message that was signed
signaturestringrequiredThe hex-encoded HMAC to verify
Return valueExplanation
trueThe signature is valid
falseThe signature does not match

Example

ts
var valid = HmacVerify('sha256', GetSecret('webhook-signing-key'), payload, receivedSig);
if (!valid) {
  Log('Invalid signature. Rejecting request.');
} else {
  Log('Signature OK.');
}

Verifying incoming webhook payloads

Many webhook providers (GitHub, Stripe, etc.) sign their payloads with an HMAC so the receiver can confirm the request came from the legitimate sender.

ts
// Verifying a GitHub webhook delivery
var body  = '...raw request body...';
var theirSig = '...X-Hub-Signature-256 header value, strip the "sha256=" prefix...';
var valid = HmacVerify('sha256', GetSecret('github-webhook-secret'), body, theirSig);
if (!valid) {
  Log('Webhook signature mismatch.');
}