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. :)

This article was posted by Matty on 2005-05-07 13:22:00 -0400 -0400