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:

  • -base64 encodes 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, like openssl base64 — but unlike openssl base64 there is no -A flag (it errors out), so single-line output needs openssl rand -base64 $N | tr -d '\n'.
  • -hex prints 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 32 is 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.

Sources