Skip to main content
Computes an HMAC (Hash-based Message Authentication Code) for data using a secret key.

Signature

sqlpage.hmac(data TEXT, key TEXT, algorithm TEXT DEFAULT 'sha256') -> TEXT

Parameters

data
TEXT
required
The input data to sign
key
TEXT
required
The secret key for signing
algorithm
TEXT
Optional hash algorithm: ‘sha256’ (default), ‘sha256-base64’, ‘sha512’, or ‘sha512-base64’

Return Value

return
TEXT
The HMAC signature as hex or base64 string

Description

The hmac() function creates cryptographic signatures to verify data authenticity and integrity. Commonly used for webhooks, API authentication, and secure tokens.

Examples

Verify Webhook Signature

SET body = sqlpage.request_body();
SET secret = sqlpage.environment_variable('WEBHOOK_SECRET');
SET expected = sqlpage.hmac($body, $secret, 'sha256');
SET actual = sqlpage.header('X-Webhook-Signature');

SELECT 'redirect' as component,
    '/error.sql?msg=invalid_signature' as link
WHERE $expected != $actual OR $actual IS NULL;

-- Process webhook data
INSERT INTO webhook_events (data) VALUES ($body);
-- Generate signed link
SET expires = datetime('now', '+1 hour');
SET token = sqlpage.hmac(
    $file_id || '|' || $expires,
    sqlpage.environment_variable('DOWNLOAD_SECRET'),
    'sha256'
);

SELECT '/download.sql?file=' || $file_id || '&exp=' || $expires || '&token=' || $token AS download_url;
Verify the link:
-- Verify signed link
SET expected = sqlpage.hmac(
    $file_id || '|' || $exp,
    sqlpage.environment_variable('DOWNLOAD_SECRET'),
    'sha256'
);

SELECT 'redirect' as component, '/error.sql' as link
WHERE $expected != $token OR $token IS NULL OR $exp < datetime('now');

Secure API Requests

SET timestamp = CAST(strftime('%s', 'now') AS TEXT);
SET message = 'POST' || $timestamp || '/api/endpoint' || $request_body;
SET signature = sqlpage.hmac($message, $api_secret, 'sha256');

SET request = json_object(
    'url', 'https://api.example.com/endpoint',
    'method', 'POST',
    'headers', json_object(
        'X-Signature', $signature,
        'X-Timestamp', $timestamp
    ),
    'body', $request_body
);

SET response = sqlpage.fetch($request);

Algorithm Options

AlgorithmOutput FormatUse Case
sha256Hex (64 chars)General purpose, webhooks
sha256-base64Base64 (44 chars)Shorter signatures
sha512Hex (128 chars)Higher security
sha512-base64Base64 (88 chars)High security, compact

Security Best Practices

Keep Secrets Safe

-- WRONG - Secret in code
SET sig = sqlpage.hmac($data, 'my-secret-key', 'sha256');

-- CORRECT - Secret in environment
SET sig = sqlpage.hmac($data, sqlpage.environment_variable('SECRET_KEY'), 'sha256');

Always Check for NULL

-- WRONG - Won't catch missing signature
WHERE sqlpage.hmac(...) != $signature

-- CORRECT - Handles NULL properly
WHERE sqlpage.hmac(...) != $signature OR $signature IS NULL

Build docs developers (and LLMs) love