Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a random string of 32 hexadecimal digits through command line?

Tags:

bash

random

I'd like to put together a command that will print out a string of 32 hexadecimal digits. I've got a Python script that works:

python -c 'import random ; print "".join(map(lambda t: format(t, "02X"), [random.randrange(256) for x in range(16)]))' 

This generates output like:

6EF6B30F9E557F948C402C89002C7C8A  

Which is what I need.

On a Mac, I can even do this:

uuidgen | tr -d '-' 

However, I don't have access to the more sophisticated scripting languages ruby and python, and I won't be on a Mac (so no uuidgen). I need to stick with more bash'ish tools like sed, awk, /dev/random because I'm on a limited platform. Is there a way to do this?

like image 486
Ana Avatar asked Dec 17 '15 07:12

Ana


People also ask

How do you generate random strings?

A random string is generated by first generating a stream of random numbers of ASCII values for 0-9, a-z and A-Z characters. All the generated integer values are then converted into their corresponding characters which are then appended to a StringBuffer.

How do you generate a random hexadecimal in Java?

To generate Random Hexadecimal Bytes, first, a random byte can be generated in decimal form using Java. util. Random. nextInt() and then it can be converted to hexadecimal form using Integer.

What is a string hexadecimal?

By string of hexadecimal digits what they mean is a combination of the digits 0-9 and characters A-F, just like how a binary string is a combination of 0's and 1's. Eg: "245FC" is a hexadecimal string.


2 Answers

If you have hexdump then:

hexdump -n 16 -e '4/4 "%08X" 1 "\n"' /dev/urandom 

should do the job.

Explanation:

  • -n 16 to consume 16 bytes of input (32 hex digits = 16 bytes).
  • 4/4 "%08X" to iterate four times, consume 4 bytes per iteration and print the corresponding 32 bits value as 8 hex digits, with leading zeros, if needed.
  • 1 "\n" to end with a single newline.
like image 148
Renaud Pacalet Avatar answered Oct 06 '22 16:10

Renaud Pacalet


If you are looking for a single command and have openssl installed, see below. Generate random 16 bytes (32 hex symbols) and encode in hex (also -base64 is supported).

openssl rand -hex 16 
like image 32
touzoku Avatar answered Oct 06 '22 14:10

touzoku