brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: openssl rand -base64 32 makes a strong random secret in one line

Openssl
~/tips/tip-security-openssl-rand-base64

openssl rand -base64 32

Prints random bytes from a secure generator, encoded as base64 or hex, for use as a password or key.

A secret key, a database password or a webhook token should come from a random generator, not from my imagination. OpenSSL has one in every install.

openssl rand -base64 32
openssl rand -hex 32

The number is the amount of random bytes. -base64 encodes the output as base64 text, and -hex shows it as a hex string. So -hex 32 prints 64 hex characters. The manual says the bytes come from a cryptographically secure generator, and gives them a security level of 256 bits when the system entropy source worked.

It is a good way to fill an .env file:

echo "SECRET_KEY=$(openssl rand -hex 32)" >> .env

In current OpenSSL versions the length can have a suffix like K or M for larger amounts, in binary multiples, and the suffix is case sensitive.

The caveat is that the output is only as private as the place where you print it. A secret typed in a shell leaves traces in your shell history if you paste it into a command, and base64 output can contain +, / and =, which some systems do not accept in a password or a URL. Use -hex there, or the URL-safe alphabet of a different tool. Keep the secret out of git.

Further reading: OpenSSL: openssl-rand

More Openssl tips openssl s_client -connect 203.0.113.10:443 -servername example.com </dev/null | openssl x509 -noout -subject openssl x509 -in cert.pem -days 365 -signkey key.pem -out cert-new.pem printf %s hello | openssl dgst -sha256 -hmac secret openssl pkcs12 -legacy -in old.pfx -nokeys echo 'aGVsbG8gd29ybGQ=' | openssl base64 -d All Openssl tips (34) All topics

Link