In GENERAL, on Linux, UNIX, BSD, cygwin systems, how can I get random numbers from /dev/urandom inside a given range, example:
217 < X < 34523
OR other example:
36856 < X < 76543
I am afraid to even try to search for solutions, since this is not just "google and first hit", because it has to be 100% correct from randomness point of view.
I tried to write it my own:
$ cat randomfournumbers.sh
#!/bin/bash
working=true
howmanyneeded=0
while "$working"; do
fivedigit=$(tr -cd "[:digit:]"</dev/urandom|fold -w5|head -1)
if [ "$fivedigit" -ge 300 ]; then
if [ "$fivedigit" -le 33000 ]; then
echo "$fivedigit"
howmanyneeded=$((howmanyneeded+1))
if [ "$howmanyneeded" -ge 4 ]; then
working=false
fi
fi
fi
done
$ sh randomfournumbers.sh
11442
26742
13905
23547
$
But afaik cryptography, randomness.. I am sure it contains an error that I cannot see (no problem with urandom, rather the logic).
/dev/urandom
), on specific Unix-like operating systems or environments ("Linux, UNIX, BSD, cygwin systems"). I am amazed that you regard it as off-topic. – Jan 06 '18 at 19:26urandom
gives random byte values. An interface like that is not unique to Unix, other systems have that too, e.g.CryptGenRandom
on Windows,RAND_bytes
in OpenSSL. All that's Unix-specific here is the name of the interface, and we already know that. After that, it's just mathematics on how to turn random bytes to random numbers in a given range, while getting the required properties (uniform distribution). – ilkkachu Jan 06 '18 at 20:51CryptGenRandom
as input. – Jan 07 '18 at 15:35