gen_random_bytes Hex API Tokens

Issue API tokens from cryptographically random bytes with gen_random_bytes, stored as hex with a unique constraint.

SqlSecurity Boundaries

Code

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

FAQ

What are the relations in play here?
`api_tokens` — referenced directly, no join needed.