bpo-40286: Add randbytes() method to random.Random (GH-19527)

Add random.randbytes() function and random.Random.randbytes()
method to generate random bytes.

Modify secrets.token_bytes() to use SystemRandom.randbytes()
rather than calling directly os.urandom().

Rename also genrand_int32() to genrand_uint32(), since it returns an
unsigned 32-bit integer, not a signed integer.

The _random module is now built with Py_BUILD_CORE_MODULE defined.
This commit is contained in:
Victor Stinner 2020-04-17 19:05:35 +02:00 committed by GitHub
parent 22386bb4ef
commit 9f5fe7910f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 177 additions and 12 deletions

View file

@ -739,6 +739,12 @@ class SystemRandom(Random):
x = int.from_bytes(_urandom(numbytes), 'big')
return x >> (numbytes * 8 - k) # trim excess bits
def randbytes(self, n):
"""Generate n random bytes."""
# os.urandom(n) fails with ValueError for n < 0
# and returns an empty bytes string for n == 0.
return _urandom(n)
def seed(self, *args, **kwds):
"Stub method. Not used for a system random number generator."
return None
@ -819,6 +825,7 @@ weibullvariate = _inst.weibullvariate
getstate = _inst.getstate
setstate = _inst.setstate
getrandbits = _inst.getrandbits
randbytes = _inst.randbytes
if hasattr(_os, "fork"):
_os.register_at_fork(after_in_child=_inst.seed)