To generate random bytes with openssl, use the openssl rand utility which is the openssl random number generator. 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 -rand
and -writer
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.
This post strives to provide a useful openssl rand example for both base64 and hex with a detailed explanation for each.
openssl rand examples
Each of the following examples will use openssl to generate random bytes.
openssl rand hex
To generate a random password with openssl in hex format, run the following command:
openssl rand -hex 20
Where -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), so the final result is a generated random hex string.
openssl rand base64
To generate the random password in base64 with openssl, run the following command:
openssl rand -base64 20
Where -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
Where -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.
Conclusion
We hope to have provided helpful openssl rand examples and demonstrated how you can use the openssl random number generator for your own use cases. Leave a comment if you have any questions or would like to see additional examples on how to use openssl rand.
Read more of our content or head over to our OpenSSL page.
Leave a Reply