ADev
ADev

Reputation: 351

Generate true random numbers in python

Python function that generates true random numbers?

By true random numbers it also means that what every time I run python the seed I generate is different. How do I do this?

Upvotes: 4

Views: 6893

Answers (2)

Egon Kirchof
Egon Kirchof

Reputation: 59

There is a thing called true random numbers.
Check: www.random.org for more information.
Code example:

import requests
source = "https://www.random.org/integers/?num=1&min=1&max=100&col=5&base=10&format=plain&rnd=new"
number = requests.get(source)
number = int(number.text)

Upvotes: 1

Serpent27
Serpent27

Reputation: 332

There are many ways of generating random numbers, with exactly 1 thing in common - they all require external input. Let's say you use a simple RNG like games use. The RNG takes an input (usually the system time, in seconds or milliseconds), and performs various wonky mathematical operations to produce a random-looking output.

Let's say, however, that your computer has hardware that can measure atmospheric noise - you could fairly easily do that with your built-in microphone on any laptop, or an external mic on a desktop... Or you can measure the randomness of the user's input - humans are known to be good sources of entropy... Or you could measure the decay of a subatomic particle - quantum mechanics is as random as it gets.

If you could do any of those things - and you can actually do all of them (#3 requires special hardware) you could pass those through a cryptographic hash (ex. SHA-256) to create a truly random stream of bytes with equal probability for every possible state. If you use SHA-256 it would be a good idea to hash at least 512 bits (64 bytes) of data if you want the most randomness possible.

Also, most modern systems have TRNGs (true random number generators) built into their CPUs; hardware manufacturers started doing this to address the need for better RNGs in cryptography. As such, many systems will default to a TRNG if one is available (using the python secrets module).

You can easily check if you have a TRNG on Linux by running cat /dev/random. If it stops and waits after a few seconds you don't and need to use another technique. If if keeps going the same as /dev/urandom, you have a TRNG already and can make truly-random numbers easily!

Update: The Python secrets module documentation can be found here. A quick example program:

import secrets
low = 10
high = 100
out = secrets.randbelow(high - low) + low # out = random number from range [low, high)
print(out) # Print your number

You can also use secrets to create a hex string directly, or produce a stream of random bytes. You can see its docs to learn more.

Upvotes: 10

Related Questions