SQL cryptographic random
Produces unpredictable bytes for tokens and keys; the seeded or plain random() functions are predictable and must never be used for secrets.
- Category
- Math
- Returns
binary / blob- In this category
- 77 of 82
Syntax
RANDOM_BYTES(n) -- MySQL
CRYPT_GEN_RANDOM(n) -- SQL Server
randomblob(n) -- SQLite
Each block is a separate form. The support table and the examples show which engine takes which.
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Yes | CRYPT_GEN_RANDOM(n [, seed]) is built in |
| PostgreSQL | Different name or syntax | No core function: gen_random_bytes(n) comes from the pgcrypto extension (gen_random_uuid() is core since 13) |
| MySQL | Yes | RANDOM_BYTES(n) since 5.6.17, backed by the TLS library's generator; n from 1 to 1024 |
| SQLite | Different name or syntax | randomblob(N) returns N random bytes, not documented as CSPRNG-grade, but widely used for tokens |
| Oracle | Different name or syntax | DBMS_CRYPTO.RANDOMBYTES(n) in PL/SQL; DBMS_RANDOM is not cryptographic |
Examples
MySQL
SELECT HEX(RANDOM_BYTES(16)) AS token;
SQL Server
SELECT CRYPT_GEN_RANDOM(16) AS token_bytes;
SQLite
SELECT hex(randomblob(16)) AS token;
PostgreSQL
SELECT encode(gen_random_bytes(16), 'hex') AS token; -- after CREATE EXTENSION pgcrypto
Good to know
- RAND(), random() and DBMS_RANDOM are predictable: seeded or weak generators. Tokens and keys come from the crypto functions only.
- 16 bytes (128 bits) is enough for a session token, 32 for a 256-bit key. RANDOM_BYTES caps at 1024 on MySQL and CRYPT_GEN_RANDOM at 8000 on SQL Server.
- On PostgreSQL the pgcrypto extension must be installed first: CREATE EXTENSION pgcrypto; (gen_random_bytes is not core, though gen_random_uuid() became core in 13).
Questions about random bytes
Can I use RAND() to generate tokens?
No. RAND() and random() are predictable, and a seeded sequence is fully reproducible by anyone who learns the seed. Use RANDOM_BYTES (MySQL), CRYPT_GEN_RANDOM (SQL Server), gen_random_bytes (PostgreSQL via pgcrypto) or randomblob (SQLite).
How do I get cryptographic random bytes in PostgreSQL?
gen_random_bytes(n) from the pgcrypto extension: CREATE EXTENSION pgcrypto first. The core gen_random_uuid() (13+) also draws crypto-grade randomness.
Is SQLite's randomblob secure?
SQLite documents random() and randomblob as pseudo-random, not as a CSPRNG guarantee, fine for shuffling and ids, but check your threat model before using it for secrets.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.