Random Number Generation In Python

- 1 answer

Is this a valid way to generate n random bytes that are cryptographically random?

def cryptographically_secure_random_bytes(n):
    return ''.join(chr(random.SystemRandom().randint(0,256)) for _ in range(n))

I know random.SystemRandom() is the same as os.urandom(), and I know that os.urandom() is definitely a cryptographically secure way of generating random numbers.

However, the chr(random.SystemRandom().randint(0,256)) part throws me off a bit. Since chr() doesn't support unicode, I'm assuming that this function is discarding some characters that would otherwise be produced by random.SystemRandom().

I'm not sure what to think of randint(0,256) either, since that is the size of a byte.



random.randint(a, b)

Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

So it is inclusive you could get something bigger than a byte.