1 """Generate cryptographically strong pseudo-random numbers suitable for
2 managing secrets such as account authentication, tokens, and similar.
3
4 See PEP 506 for more information.
5 https://peps.python.org/pep-0506/
6
7 """
8
9 __all__ = ['choice', 'randbelow', 'randbits', 'SystemRandom',
10 'token_bytes', 'token_hex', 'token_urlsafe',
11 'compare_digest',
12 ]
13
14
15 import base64
16
17 from hmac import compare_digest
18 from random import SystemRandom
19
20 _sysrand = SystemRandom()
21
22 randbits = _sysrand.getrandbits
23 choice = _sysrand.choice
24
25 def randbelow(exclusive_upper_bound):
26 """Return a random int in the range [0, n)."""
27 if exclusive_upper_bound <= 0:
28 raise ValueError("Upper bound must be positive.")
29 return _sysrand._randbelow(exclusive_upper_bound)
30
31 DEFAULT_ENTROPY = 32 # number of bytes to return by default
32
33 def token_bytes(nbytes=None):
34 """Return a random byte string containing *nbytes* bytes.
35
36 If *nbytes* is ``None`` or not supplied, a reasonable
37 default is used.
38
39 >>> token_bytes(16) #doctest:+SKIP
40 b'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b'
41
42 """
43 if nbytes is None:
44 nbytes = DEFAULT_ENTROPY
45 return _sysrand.randbytes(nbytes)
46
47 def token_hex(nbytes=None):
48 """Return a random text string, in hexadecimal.
49
50 The string has *nbytes* random bytes, each byte converted to two
51 hex digits. If *nbytes* is ``None`` or not supplied, a reasonable
52 default is used.
53
54 >>> token_hex(16) #doctest:+SKIP
55 'f9bf78b9a18ce6d46a0cd2b0b86df9da'
56
57 """
58 return token_bytes(nbytes).hex()
59
60 def token_urlsafe(nbytes=None):
61 """Return a random URL-safe text string, in Base64 encoding.
62
63 The string has *nbytes* random bytes. If *nbytes* is ``None``
64 or not supplied, a reasonable default is used.
65
66 >>> token_urlsafe(16) #doctest:+SKIP
67 'Drmhze6EPcv0fN_81Bj-nA'
68
69 """
70 tok = token_bytes(nbytes)
71 return base64.urlsafe_b64encode(tok).rstrip(b'=').decode('ascii')