Random bytes generation with OpenSSL

Posted on January 31, 2018
Updated on July 20, 2022
Tagged as #shell

Sometimes you just have to generate some random bytes with high entropy. And OpenSSL can help you with this task.

$ openssl rand [options] num

The rand command outputs num pseudo-random bytes. Since in most cases we don’t want to deal with edge bytes, it’s better to use either -hex or -base64 option in order to encode output and thus lead to a valid password.

$ openssl rand 16
fӤ?v ???^@?y??

$ openssl rand -hex 16

$ openssl rand -base64 16

Another problem is the length. When you use -hex or -base64 option the output string is longer than passed num. In order to keep the desired length, you have to chop it. For example, using the cut command.

$ openssl rand -hex 16 | cut -c1-16

$ openssl rand -base64 16 | cut -c1-16

Some useful links: