Random bytes generation with OpenSSL
A quick tip for generating high-entropy random bytes using OpenSSL's rand command. Learn how to use hex or base64 encoding to create valid random strings for passwords, and how to handle the output length when encoding changes the byte count.
Sometimes you need to generate random bytes with high entropy - perhaps for a password, a secret key, or testing purposes. OpenSSL provides a simple command for this task: rand.
The basic syntax is straightforward:
$ openssl rand [options] num
The rand command outputs num pseudo-random bytes. However, since raw bytes often contain unprintable characters, it's better to use either -hex or -base64 encoding to ensure the output is a valid, printable string suitable for passwords and keys.
$ openssl rand 16 fӤ?v ???^@?y?? $ openssl rand -hex 16 b4ef65a47a327727bf4ad77d8d3352b2 $ openssl rand -base64 16 o1DqThmx1DWGoPAidi6DKQ==
One thing to note: when you use -hex or -base64 encoding, the output string is longer than the num parameter you specified. This is because encoding increases the data size. If you need a specific output length, you can truncate the result using the cut command.
$ openssl rand -hex 16 | cut -c1-16 ce8ad63b50cbe611 $ openssl rand -base64 16 | cut -c1-16 4HIcmt4vTcmchbHU
#1Further reading
- Rand command manual – Official OpenSSL documentation for the rand command
- OpenSSL random numbers – Understanding random number generation in OpenSSL
- Password Haystack – Analysing password strength and entropy