diff options
author | Victor Stinner <vstinner@python.org> | 2020-04-17 17:05:35 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-04-17 17:05:35 (GMT) |
commit | 9f5fe7910f4a1bf5a425837d4915e332b945eb7b (patch) | |
tree | 5f652699332e33a81cf6baa5ff5b6fecadea1903 /Lib/random.py | |
parent | 22386bb4ef740ee92d34c87b8cb90d681423a853 (diff) | |
download | cpython-9f5fe7910f4a1bf5a425837d4915e332b945eb7b.zip cpython-9f5fe7910f4a1bf5a425837d4915e332b945eb7b.tar.gz cpython-9f5fe7910f4a1bf5a425837d4915e332b945eb7b.tar.bz2 |
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.
Diffstat (limited to 'Lib/random.py')
-rw-r--r-- | Lib/random.py | 7 |
1 files changed, 7 insertions, 0 deletions
diff --git a/Lib/random.py b/Lib/random.py index e24737d..82345fa 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -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) |