Random Strings
pg rand generates random strings for passwords, API tokens, session secrets
and similar values. Characters come from crypto/rand; output is raw, one
string per line, with no labels or extra formatting, so it can be captured
directly in shell scripts.
The default is a 24-character alphanumeric string (a-z A-Z 0-9), about 143
bits of entropy.
Options
| Flag | Default | Description |
|---|---|---|
-l, --length N |
24 |
Characters per string (1–4096) |
-n, --count N |
1 |
Number of strings to print, one per line (1–1000) |
--charset NAME |
alnum |
Preset character set (see below) |
--extra-chars CHARS |
empty | Extra printable ASCII characters appended to the preset |
Character sets
| Name | Characters | Use for |
|---|---|---|
alnum |
a-z A-Z 0-9 |
Passwords and tokens accepted by the widest range of systems (default) |
alpha |
a-z A-Z |
Secrets that must not contain digits |
lower |
a-z |
Case-insensitive identifiers |
upper |
A-Z |
Case-insensitive identifiers |
digits |
0-9 |
Numeric PINs and codes |
hex |
0-9 a-f |
API keys, checksums, config values |
base64url |
a-z A-Z 0-9 - _ |
URL, cookie and JWT-safe tokens |
password |
alnum plus !@#$%^&*()-_=+[]{}<>?:;,.~ |
Passwords that must satisfy symbol requirements |
--extra-chars adds your own characters to any preset. Duplicates are ignored,
so every character keeps the same probability:
Examples
When a generated password contains symbols, always quote it in shell commands
and SQL. For ALTER ROLE ... PASSWORD, pass it as a quoted string literal or
use a parameterized client.
Is 24 characters enough?
Yes for most uses. The default alnum set has 62 characters, so each character
carries log2(62) ≈ 5.95 bits; 24 characters give about 143 bits, above
the 128-bit standard commonly used for API tokens and session secrets, and far
above the entropy of a human-chosen password. A 24-character string remains
infeasible to brute-force even at very high attempt rates.
Two cases deserve a different setting:
hex: each character carries only 4 bits, so 24 characters give 96 bits. Use-l 32for a 128-bit hex token.- Long-lived, high-value secrets such as root credentials or encryption
keys:
-l 32gives additional margin at negligible cost.
If a system enforces a “must contain uppercase, lowercase, digit and symbol”
policy, use --charset password (24 characters give about 155 bits) instead of
the default. Length is only one factor: server-side rate limiting and password
hashing matter at least as much as raw entropy.
Security notes
- Randomness comes from
crypto/rand, suitable for secrets; it is not reproducible and has no seed flag. - Entropy per character is
log2(len(charset)): about 5.95 bits foralnum, 6.46 forpassword, and 4 forhex. The 24-character default is roughly 143 bits withalnum. - Output is printed to stdout only;
pg randdoes not read or writepg.yamland does not require a database instance.