To generate random bytes with openssl, use the openssl rand utility. This utility utilizes a CSPRNG, a cryptographically secure pseudo-random number generator. As of v1.1.1, openssl will use a trusted entropy source provided by the operating system to seed itself from eliminating the need for the
-writerand flags. By using this utility using a CSPRNG, you can be assured that the generated bytes will be random, unpredictable, and cannot be reproduced.
This function provides a security level of 256 bits.
If no random data can be retrieved from the operating system then this function should throw an error, providing assurance that the generated bytes are indeed random. It is a best practice to rely on the underlying OS for randomness and not provide your own seed. This is for at least two reasons, being portability and accidental reuse of seed.
openssl rand examples
To generate a random password with openssl in hex format, run the following command:
openssl rand -hex 20
-hex 20 specifies the output to be in hex format with 20 bytes. Remember that hexadecimal is a numeral system in base 16, using 16 symbols (0-9, A-F).
To generate the random password in base64, run the following command:
openssl rand -base64 20
-base64 20 specifies the output to be in base64 format with 20 bytes. Base64 is an encoding format, primarily to represent binary data as a String.
To print the output to a file rather than standard output, add the
-out flag to the command like the following:
openssl rand -out output.txt -base64 20
-out output.txt specifies the name of the file to contain the random value. While this example still generates 20 random bytes, the
-out option is generally used when the number of random bytes is much higher and more difficult to read from standout output.
In the examples above, notice that the provided value is the number of random bytes before the hex or base64 encoding. Also, note that the number of random bytes is always the last input.