generate cryptographically strong pseudorandom numbers suitable for managing secrets such as account authentication tokens and similar see pep 506 for more information https peps python orgpep0506 return a random int in the range 0 n if exclusiveupperbound 0 raise valueerrorupper bound must be positive return sysrand randbelowexclusiveupperbound defaultentropy 32 number of bytes to return by default def tokenbytesnbytesnone if nbytes is none nbytes defaultentropy return sysrand randbytesnbytes def tokenhexnbytesnone return tokenbytesnbytes hex def tokenurlsafenbytesnone tok tokenbytesnbytes return base64 urlsafeb64encodetok rstripb decode ascii return a random int in the range 0 n number of bytes to return by default 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 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 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
__all__ = ['choice', 'randbelow', 'randbits', 'SystemRandom',
           'token_bytes', 'token_hex', 'token_urlsafe',
           'compare_digest',
           ]


import base64

from hmac import compare_digest
from random import SystemRandom

_sysrand = SystemRandom()

randbits = _sysrand.getrandbits
choice = _sysrand.choice

def randbelow(exclusive_upper_bound):
    
    if exclusive_upper_bound <= 0:
        raise ValueError("Upper bound must be positive.")
    return _sysrand._randbelow(exclusive_upper_bound)

DEFAULT_ENTROPY = 32  

def token_bytes(nbytes=None):
    
    if nbytes is None:
        nbytes = DEFAULT_ENTROPY
    return _sysrand.randbytes(nbytes)

def token_hex(nbytes=None):
    
    return token_bytes(nbytes).hex()

def token_urlsafe(nbytes=None):
    
    tok = token_bytes(nbytes)
    return base64.urlsafe_b64encode(tok).rstrip(b'=').decode('ascii')