Generate Random Data with OpenSSL
openssl rand emits cryptographically secure pseudo-random bytes (a CSPRNG with a 256-bit security level per the docs) — the standard Unix one-liner for API keys, salts, tokens, and key material when no dedicated secrets tool is at hand. If the generator cannot seed itself from the OS entropy source, the command fails with a nonzero exit code instead of producing weak output.
Generate secrets
openssl rand -base64 32 # 32 bytes of entropy -> 44-character Base64 secret
openssl rand -hex 16 # 16 bytes -> 32 hex characters (salt, token)
openssl rand -out key.bin 32 # 32 raw bytes to a file (key material)Output formats
The trailing number is always the count of random bytes, not the output length:
-base64encodes the bytes in Base64 — roughly 4/3 as many characters as bytes (32 bytes → 44 characters). Output wraps at 64 columns and ends with a newline, likeopenssl base64— but unlikeopenssl base64there is no-Aflag (it errors out), so single-line output needsopenssl rand -base64 $N | tr -d '\n'.-hexprints exactly twice as many characters as bytes, on one line, with a trailing newline.- With neither flag the raw bytes go out unchanged, with no newline appended.
Command substitution strips the trailing newline, so SECRET=$(openssl rand -hex 16) comes out clean.
Common pitfalls
- Bytes, not characters.
openssl rand -base64 32is 32 bytes of entropy (256 bits) rendered as 44 characters — don’t confuse the output length with the security level. - Long Base64 output wraps. Anything over 48 input bytes produces wrapped multi-line output; strip the newlines for single-line contexts.
- Pseudo-random is the point here. The CSPRNG is the right tool for keys, salts, and nonces. For anything needing reproducible randomness (tests, simulations), seed an ordinary generator explicitly instead.
Related
- openssl-hashing —
openssl rand -hexoutput is ready-madehexkey:material for HMAC - openssl-file-encryption — raw bytes as key material (
-K) or a-Ssalt for openssl enc - openssl-base64-encoding — the Base64 wrapping format in detail
- openssl-rsa-passphrase — protecting the keys these bytes generate