Skip to content

How to generate random hexadecimal in Linux

homepage-banner

TL; DR

openssl rand -hex n
  • n - the length of string

Introduction

Hexadecimal numbers are often used in computing to represent binary data in a more human-readable form. Sometimes, we need to generate random hexadecimal numbers in Linux for various purposes, such as generating a random password or generating a unique identifier. In this blog post, we will discuss how to generate random hexadecimal in Linux.

Using openssl command

The openssl command is a widely used tool for generating random hexadecimal numbers. The ‘openssl rand’ command can be used for generating random data, and the output can be converted to hexadecimal format using the ‘xxd’ command. To generate a random 16-byte hexadecimal number, we can use the following command:

openssl rand -hex 16

This command will generate a random hexadecimal number of 32 characters. We can change the number of bytes by changing the value after the ‘-hex’ option.

Using dd command

The dd command is another useful tool for generating random hexadecimal numbers. We can use the ‘if=/dev/urandom’ option to read from a pseudo-random number generator and the ‘bs’ and ‘count’ options to specify the number of bytes we want to generate. The output can be converted to hexadecimal format using the ‘xxd’ command. To generate a random 16-byte hexadecimal number, we can use the following command:

dd if=/dev/urandom bs=16 count=1 2>/dev/null | xxd -p

This command will generate a random hexadecimal number of 32 characters. We can change the number of bytes by changing the value of the ‘bs’ option.

Using uuidgen command

The uuidgen command is a tool for generating UUIDs (Universally Unique Identifiers). UUIDs are 128-bit values that are often represented as hexadecimal numbers. We can use the uuidgen command to generate random hexadecimal numbers. To generate a random hexadecimal number, we can use the following command:

uuidgen | tr -d '-'

This command will generate a random hexadecimal number of 32 characters. We can remove the ‘tr -d’ option if we want to include the hyphens in the output.

Conclusion

Generating random hexadecimal numbers is a common task in Linux. In this blog post, we discussed three methods for generating random hexadecimal numbers using the openssl, dd, and uuidgen commands. These commands are easy to use and provide a secure way to generate random hexadecimal numbers for various purposes.

Feedback







Disclaimer
  • Welcome to visit the knowledge base of SRE and DevOps!
  • License under CC BY-NC 4.0
  • Made with Material for MkDocs and improve writing by generative AI tools
  • Copyright issue feedback me#imzye.com, replace # with @