gen_random_bytes Hex API Tokens
Issue API tokens from cryptographically random bytes with gen_random_bytes, stored as hex with a unique constraint.
Code
-- gen_random_bytes: cryptographic random bytes for API tokens, encoded to hex for storage
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE api_tokens (
token_id int PRIMARY KEY,
owner text NOT NULL,
token_hex text NOT NULL UNIQUE
);
INSERT INTO api_tokens (token_id, owner, token_hex)
VALUES (1, 'ci-worker', encode(gen_random_bytes(32), 'hex')),
(2, 'deploy-bot', encode(gen_random_bytes(16), 'hex'));
-- 32 bytes -> 64 hex characters, 16 bytes -> 32; hex changes only the representation, entropy is untouched
SELECT owner,
length(token_hex) AS hex_chars,
substring(token_hex, 1, 8) AS prefix
FROM api_tokens
ORDER BY token_id;Inside the snippet
What runs here is SELECT / INSERT / CREATE — api_tokens are the objects involved.
Breaking the statements into their working parts: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out.
Putting it to use
Run the statement against the api_tokens table.
Core lines
INSERT INTO api_tokens (token_id, owner, token_hex)
VALUES (1, 'ci-worker', encode(gen_random_bytes(32), 'hex')),
(2, 'deploy-bot', encode(gen_random_bytes(16), 'hex'));
SELECT owner,
length(token_hex) AS hex_chars,
substring(token_hex, 1, 8) AS prefix
FROM api_tokens
ORDER BY token_id;
CREATE TABLE api_tokens (
token_id int PRIMARY KEY,
owner text NOT NULL,
token_hex text NOT NULL UNIQUE
);
Interactive Tools for This Topic
Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.Passphrase GeneratorGenerate memorable multi-word passphrases from a fixed 150-word list with crypto randomness, separators, and capitalization options.Password GeneratorGenerate random passwords from selectable character classes using crypto.getRandomValues with rejection sampling and class guarantees.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.
FAQ
- What are the relations in play here?
- `api_tokens` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.