pgcrypto hmac Signed Payload Verify
Sign webhook payloads with pgcrypto hmac and verify by recomputing the keyed digest, which fails the moment payload changes.
Code
-- pgcrypto's hmac: a keyed digest that keeps a signed payload tamper-proof
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE webhook_events (
event_id int PRIMARY KEY,
payload text NOT NULL,
signature text NOT NULL
);
INSERT INTO webhook_events (event_id, payload, signature)
VALUES (1, 'order.created:1001', encode(hmac('order.created:1001', 'shared-secret', 'sha256'), 'hex'));
-- verify: recompute the hmac and compare it byte for byte with the stored signature; a one-character payload change fails immediately
SELECT event_id,
encode(hmac(payload, 'shared-secret', 'sha256'), 'hex') = signature AS valid,
encode(hmac(payload || 'x', 'shared-secret', 'sha256'), 'hex') = signature AS tampered
FROM webhook_events
WHERE event_id = 1;How the snippet works
Mechanically, the statements are built from: a WHERE clause limiting a statement to the rows that qualify.
Applying it
Run the statement against the webhook_events table.
Statements that matter
SELECT event_id,
encode(hmac(payload, 'shared-secret', 'sha256'), 'hex') = signature AS valid,
encode(hmac(payload || 'x', 'shared-secret', 'sha256'), 'hex') = signature AS tampered
FROM webhook_events
WHERE event_id = 1;
INSERT INTO webhook_events (event_id, payload, signature)
VALUES (1, 'order.created:1001', encode(hmac('order.created:1001', 'shared-secret', 'sha256'), 'hex'));
CREATE TABLE webhook_events (
event_id int PRIMARY KEY,
payload text NOT NULL,
signature text NOT NULL
);
Interactive Tools for This Topic
HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.TOTP URI Builder & Code GeneratorBuild valid otpauth://totp QR provisioning URIs and compute RFC 6238 HMAC-SHA1, SHA-256, or SHA-512 verification codes locally using Web Crypto.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.
FAQ
- Which tables does this file reference?
- The references are `webhook_events`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.