2016-04-14 12:51:31 -03:00
|
|
|
"""Generate cryptographically strong pseudo-random numbers suitable for
|
|
|
|
managing secrets such as account authentication, tokens, and similar.
|
|
|
|
|
2016-04-17 00:13:36 -03:00
|
|
|
See PEP 506 for more information.
|
2022-03-30 08:00:27 -03:00
|
|
|
https://peps.python.org/pep-0506/
|
2016-04-14 12:51:31 -03:00
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
__all__ = ['choice', 'randbelow', 'randbits', 'SystemRandom',
|
|
|
|
'token_bytes', 'token_hex', 'token_urlsafe',
|
|
|
|
'compare_digest',
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
import base64
|
|
|
|
import binascii
|
|
|
|
|
2016-04-15 15:33:55 -03:00
|
|
|
from hmac import compare_digest
|
2016-04-14 12:51:31 -03:00
|
|
|
from random import SystemRandom
|
|
|
|
|
|
|
|
_sysrand = SystemRandom()
|
|
|
|
|
|
|
|
randbits = _sysrand.getrandbits
|
|
|
|
choice = _sysrand.choice
|
|
|
|
|
|
|
|
def randbelow(exclusive_upper_bound):
|
2016-04-17 00:13:36 -03:00
|
|
|
"""Return a random int in the range [0, n)."""
|
2016-12-30 01:54:25 -04:00
|
|
|
if exclusive_upper_bound <= 0:
|
|
|
|
raise ValueError("Upper bound must be positive.")
|
2016-04-14 12:51:31 -03:00
|
|
|
return _sysrand._randbelow(exclusive_upper_bound)
|
|
|
|
|
|
|
|
DEFAULT_ENTROPY = 32 # number of bytes to return by default
|
|
|
|
|
|
|
|
def token_bytes(nbytes=None):
|
2016-04-17 00:13:36 -03:00
|
|
|
"""Return a random byte string containing *nbytes* bytes.
|
|
|
|
|
|
|
|
If *nbytes* is ``None`` or not supplied, a reasonable
|
|
|
|
default is used.
|
|
|
|
|
|
|
|
>>> token_bytes(16) #doctest:+SKIP
|
|
|
|
b'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b'
|
|
|
|
|
|
|
|
"""
|
2016-04-14 12:51:31 -03:00
|
|
|
if nbytes is None:
|
|
|
|
nbytes = DEFAULT_ENTROPY
|
2020-04-17 14:05:35 -03:00
|
|
|
return _sysrand.randbytes(nbytes)
|
2016-04-14 12:51:31 -03:00
|
|
|
|
|
|
|
def token_hex(nbytes=None):
|
2016-04-17 00:13:36 -03:00
|
|
|
"""Return a random text string, in hexadecimal.
|
|
|
|
|
|
|
|
The string has *nbytes* random bytes, each byte converted to two
|
|
|
|
hex digits. If *nbytes* is ``None`` or not supplied, a reasonable
|
|
|
|
default is used.
|
|
|
|
|
|
|
|
>>> token_hex(16) #doctest:+SKIP
|
|
|
|
'f9bf78b9a18ce6d46a0cd2b0b86df9da'
|
|
|
|
|
|
|
|
"""
|
2016-04-14 12:51:31 -03:00
|
|
|
return binascii.hexlify(token_bytes(nbytes)).decode('ascii')
|
|
|
|
|
|
|
|
def token_urlsafe(nbytes=None):
|
2016-04-17 00:13:36 -03:00
|
|
|
"""Return a random URL-safe text string, in Base64 encoding.
|
|
|
|
|
|
|
|
The string has *nbytes* random bytes. If *nbytes* is ``None``
|
|
|
|
or not supplied, a reasonable default is used.
|
|
|
|
|
|
|
|
>>> token_urlsafe(16) #doctest:+SKIP
|
|
|
|
'Drmhze6EPcv0fN_81Bj-nA'
|
|
|
|
|
|
|
|
"""
|
2016-04-14 12:51:31 -03:00
|
|
|
tok = token_bytes(nbytes)
|
|
|
|
return base64.urlsafe_b64encode(tok).rstrip(b'=').decode('ascii')
|