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
The secret key for signing
Optional hash algorithm: ‘sha256’ (default), ‘sha256-base64’, ‘sha512’, or ‘sha512-base64’
Return Value
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);
Signed Download Links
-- 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
| Algorithm | Output Format | Use Case |
|---|
sha256 | Hex (64 chars) | General purpose, webhooks |
sha256-base64 | Base64 (44 chars) | Shorter signatures |
sha512 | Hex (128 chars) | Higher security |
sha512-base64 | Base64 (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