blob: 27fa4503d75606aa025c870fad68b6d940f2ff95 [file] [log] [blame]
Steven D'Aprano95702722016-04-15 01:51:31 +10001"""Generate cryptographically strong pseudo-random numbers suitable for
2managing secrets such as account authentication, tokens, and similar.
Steven D'Aprano4ad46542016-04-17 13:13:36 +10003
Steven D'Aprano95702722016-04-15 01:51:31 +10004See PEP 506 for more information.
Steven D'Aprano95702722016-04-15 01:51:31 +10005https://www.python.org/dev/peps/pep-0506/
6
Steven D'Aprano95702722016-04-15 01:51:31 +10007"""
8
9__all__ = ['choice', 'randbelow', 'randbits', 'SystemRandom',
10 'token_bytes', 'token_hex', 'token_urlsafe',
11 'compare_digest',
12 ]
13
14
15import base64
16import binascii
17import os
18
Steven D'Aprano6dda1b12016-04-16 04:33:55 +100019from hmac import compare_digest
Steven D'Aprano95702722016-04-15 01:51:31 +100020from random import SystemRandom
21
22_sysrand = SystemRandom()
23
24randbits = _sysrand.getrandbits
25choice = _sysrand.choice
26
27def randbelow(exclusive_upper_bound):
Steven D'Aprano4ad46542016-04-17 13:13:36 +100028 """Return a random int in the range [0, n)."""
Steven D'Aprano95702722016-04-15 01:51:31 +100029 return _sysrand._randbelow(exclusive_upper_bound)
30
31DEFAULT_ENTROPY = 32 # number of bytes to return by default
32
33def token_bytes(nbytes=None):
Steven D'Aprano4ad46542016-04-17 13:13:36 +100034 """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 """
Steven D'Aprano95702722016-04-15 01:51:31 +100043 if nbytes is None:
44 nbytes = DEFAULT_ENTROPY
45 return os.urandom(nbytes)
46
47def token_hex(nbytes=None):
Steven D'Aprano4ad46542016-04-17 13:13:36 +100048 """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 """
Steven D'Aprano95702722016-04-15 01:51:31 +100058 return binascii.hexlify(token_bytes(nbytes)).decode('ascii')
59
60def token_urlsafe(nbytes=None):
Steven D'Aprano4ad46542016-04-17 13:13:36 +100061 """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 """
Steven D'Aprano95702722016-04-15 01:51:31 +100070 tok = token_bytes(nbytes)
71 return base64.urlsafe_b64encode(tok).rstrip(b'=').decode('ascii')