ยปCore Development>Code coverage>Lib/secrets.py

Python code coverage for Lib/secrets.py

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