mirror of
https://github.com/python/cpython.git
synced 2025-10-07 07:31:46 +00:00
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:
parent
22386bb4ef
commit
9f5fe7910f
10 changed files with 177 additions and 12 deletions
|
@ -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)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue