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 the most recent version to use them.
HmacSign
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.
| Parameter | Type | Requirement | Explanation |
|---|---|---|---|
algorithm | string | required | HMAC algorithm: sha256 or sha512 |
key | string | required | The shared secret key |
data | string | required | The message to sign |
| Return value | Explanation |
|---|---|
| string | Lowercase hex-encoded HMAC |
Example
var mac = HmacSign('sha256', GetSecret('webhook-signing-key'), payload);
Log('Signature: ' + mac);HmacVerify
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.
| Parameter | Type | Requirement | Explanation |
|---|---|---|---|
algorithm | string | required | HMAC algorithm: sha256 or sha512 |
key | string | required | The shared secret key |
data | string | required | The message that was signed |
signature | string | required | The hex-encoded HMAC to verify |
| Return value | Explanation |
|---|---|
true | The signature is valid |
false | The signature does not match |
Example
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.
// 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.');
}