nullUser
nullUser

Reputation: 1833

What is the distribution of /dev/urandom? Code to verify?

Everywhere I look it says /dev/urandom on linux is "random", but no source I can find cites what kind of random "random" is. My hope is that it is close to uniform on 0x01 to 0xff bytewise. If I wanted to test this, what would be the best way to get an estimate of the distribution? Solution in bash preferred.

Upvotes: 0

Views: 1032

Answers (2)

dawg
dawg

Reputation: 104082

Here is a Python program that shows it is pretty darned uniform (at least on macOS):

import os
cnt, start=[10000000]*2
buckets={}
while cnt:
    c=os.urandom(1)
    buckets.setdefault(c, 0)
    buckets[c]+=1
    cnt-=1

ideal=1/256.0
if len(buckets) != 256: print('{} missing keys'.format(256-len(buckets)))
for k, v in sorted(buckets.items()):
    actual=float(buckets[k])/start
    print('{:8} {:10.4%} {:10.4%}'.format(repr(k), actual, actual-ideal ))

Prints:

b'\x00'     0.3892%   -0.0014%
b'\x01'     0.3950%    0.0044%
b'\x02'     0.3856%   -0.0050%
b'\x03'     0.3901%   -0.0006%
b'\x04'     0.3894%   -0.0013%
b'\x05'     0.3881%   -0.0025%
b'\x06'     0.3912%    0.0006%
b'\x07'     0.3912%    0.0005%
b'\x08'     0.3951%    0.0044%
b'\t'       0.3928%    0.0022%
b'\n'       0.3877%   -0.0029%
...
b'\xf7'     0.3914%    0.0008%
b'\xf8'     0.3906%   -0.0001%
b'\xf9'     0.3917%    0.0011%
b'\xfa'     0.3910%    0.0004%
b'\xfb'     0.3884%   -0.0022%
b'\xfc'     0.3915%    0.0009%
b'\xfd'     0.3904%   -0.0002%
b'\xfe'     0.3894%   -0.0013%
b'\xff'     0.3914%    0.0008%

Upvotes: 2

nullUser
nullUser

Reputation: 1833

To answer my own question:

cat /dev/urandom | hexdump -n 100000000 -v -e '/1 "0x%02X\n"' | sort -n | uniq -c | awk '{print $1/100000000"\t"$2;}'

works well enough.

Also RFC 1750: https://www.rfc-editor.org/rfc/rfc1750. The output is not uniform, but its goal is to be close.

Upvotes: 1

Related Questions