mardi 11 juillet 2023

How to get a random seed from /dev/urandom?

In python 3.11 and ubuntu 22.04 I am trying to get a random seed (as opposed to a random number from a seeded system). I have a system running a process that is looping. At various points in the loop I set all python and system RNG settings to specific seeds for repeatability. At a particular point I need a random seed, separate from the specific seeds used for the system.

The random seed I need is an integer with the upper range of (2^32 -1). Yes there is a function, but it returns a value from the seeded system.

I have a hardware RNG in a USB port that works with the rng5-tools package, but I cannot access it directly. I assume it is used to fill the entropy pool and that os.urandom() pulls bits from that pool.

I tried using os.urandom() to generate an integer, then take the last character of that integer. The distribution of the ten individual characters (0 thru 9) is uniform. I have run samples of 10^3 to 10^7 to verify this.

I do this 10 times, each time adding the single character to a string, then convert the string to an integer. Each time I add an integer to the string, I right-pad it with zeros and test if it is < 4294967296 (2^32 -1). If it fails, the character is discarded and a new character is obtained and tested until it passes the test. If it succeeds I keep it in the string and repeat the process for new characters until a total of ten-characters are obtained. I then convert the string to an integer.

However the distribution of the resulting integers is skewed as shown in the graph. Can anyone shed any light as to why? The code is:

def gen_seed(digits = 10): 

  ssc = ""
  for i in range(digits):
    found_digit = False
    while found_digit == False:
    
      rand=f"{int.from_bytes(os.urandom(1), sys.byteorder)}"
      digit = f"{rand[-1]}"

      ssc_test = int(f"{ssc}{digit}".ljust(10,"0"))

      if ssc_test < 4294967296:
        found_digit = True
        ssc = f"{ssc}{digit}"
  ss = int(ssc)
  return(ss)

Resulting ten-digit integer frequency




Aucun commentaire:

Enregistrer un commentaire