pgcrypto hmac Signed Payload Verify

Sign webhook payloads with pgcrypto hmac and verify by recomputing the keyed digest, which fails the moment payload changes.

SqlSecurity Boundaries

Code

snippet
-- 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

FAQ

Which tables does this file reference?
The references are `webhook_events`.