Generating random numbers

Randomness is a key element in cryptography (seeds and shared secrets), TCP (ISNs), and can be useful when simulating client access patterns in test scripts. If an OS supports the /dev/random pseudo-device, the dd, od, and awk utiltiies can be used to generate random values:

$ dd if=/dev/random count=1 2>/dev/null | od -t u1 | awk ‘NR==1 {print $2}’
007

$ dd if=/dev/random count=1 2>/dev/null | od -t u1 | awk ‘NR==1 {print $2$3}’
035170

$ dd if=/dev/random count=1 2>/dev/null | od -t u1 | awk ‘NR==1 {print $2$3$4}’
018183199

This will pipe a string of entropy to od, which will use od’s type field to generate an unsigned random integer, which will then be piped into awk to print the second value in the string. You can also use openssl to generate entropy on a system:

$ openssl rand -base64 1 | od -t u1 | awk ‘NR==1 {print $2}’
51

$ openssl rand -base64 1 | od -t u1 | awk ‘NR==1 {print $2}’
120

I am sure there are more efficient ways to do this, and would love to get feedback. :)

Leave a Reply

Your email address will not be published. Required fields are marked *