How does Linux generate random Numbers and strings

  • 2020-10-23 21:18:39
  • OfStack

Generate random Numbers

1. Use the system's $RANDOM variable


> echo $RANDOM 
14587 

2. Use date +%s%N


> date +%s%N
1529584024896587259

3. Use /dev/random or /dev/urandom

/dev/random stores real-time data of the current operating environment of the system. It is a blocking random number generator. Sometimes reading needs to wait, so avoid using it as much as possible.

/dev/urandom non-blocking random number generator, read operation does not produce blocking.


> cat /dev/urandom | head -n 10 | cksum | awk -F ' ' '{print $1}'
1198074148

Generate random strings

1. Use linux uuid, the full name of which is the universal 1 identifier. The format contains 32 hexadecimal digits, divided into 5 segments by the '-' connection number. 32 characters in the form 8-4-4-4-12.


> cat /proc/sys/kernel/random/uuid
6fcae1aa-ab46-435a-8531-250ccb54ed8e

2. Use md5sum


# use date  generate 10 Bit random string  
> date +%s%N | md5sum | head -c 10
bb791e69d4

# use  /dev/urandom generate 10 Bit random string  
> cat /dev/urandom | head -n 10 | md5sum | head -c 10
909587db4c

> head -c 10 /dev/random | base64
tBIDqQcaQ+qvkA==

3. Use openssl


> openssl rand -hex 10
3822e40bdcc2d1c6ee5f

Related articles: