blob: e4e9714ac038a1806f2f10c51f79b34f27e325ce [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.
3See PEP 506 for more information.
4
5https://www.python.org/dev/peps/pep-0506/
6
7
8Random numbers
9==============
10
11The ``secrets`` module provides the following pseudo-random functions, based
12on SystemRandom, which in turn uses the most secure source of randomness your
13operating system provides.
14
15
16 choice(sequence)
17 Choose a random element from a non-empty sequence.
18
19 randbelow(n)
20 Return a random int in the range [0, n).
21
22 randbits(k)
23 Generates an int with k random bits.
24
25 SystemRandom
26 Class for generating random numbers using sources provided by
27 the operating system. See the ``random`` module for documentation.
28
29
30Token functions
31===============
32
33The ``secrets`` module provides a number of functions for generating secure
34tokens, suitable for applications such as password resets, hard-to-guess
35URLs, and similar. All the ``token_*`` functions take an optional single
36argument specifying the number of bytes of randomness to use. If that is
37not given, or is ``None``, a reasonable default is used. That default is
38subject to change at any time, including during maintenance releases.
39
40
41 token_bytes(nbytes=None)
42 Return a random byte-string containing ``nbytes`` number of bytes.
43
44 >>> secrets.token_bytes(16) #doctest:+SKIP
45 b'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b'
46
47
48 token_hex(nbytes=None)
49 Return a random text-string, in hexadecimal. The string has ``nbytes``
50 random bytes, each byte converted to two hex digits.
51
52 >>> secrets.token_hex(16) #doctest:+SKIP
53 'f9bf78b9a18ce6d46a0cd2b0b86df9da'
54
55 token_urlsafe(nbytes=None)
56 Return a random URL-safe text-string, containing ``nbytes`` random
57 bytes. On average, each byte results in approximately 1.3 characters
58 in the final result.
59
60 >>> secrets.token_urlsafe(16) #doctest:+SKIP
61 'Drmhze6EPcv0fN_81Bj-nA'
62
63
64(The examples above assume Python 3. In Python 2, byte-strings will display
65using regular quotes ``''`` with no prefix, and text-strings will have a
66``u`` prefix.)
67
68
69Other functions
70===============
71
72 compare_digest(a, b)
73 Return True if strings a and b are equal, otherwise False.
74 Performs the equality comparison in such a way as to reduce the
75 risk of timing attacks.
76
77 See http://codahale.com/a-lesson-in-timing-attacks/ for a
78 discussion on how timing attacks against ``==`` can reveal
79 secrets from your application.
80
81
82"""
83
84__all__ = ['choice', 'randbelow', 'randbits', 'SystemRandom',
85 'token_bytes', 'token_hex', 'token_urlsafe',
86 'compare_digest',
87 ]
88
89
90import base64
91import binascii
92import os
93
Steven D'Aprano6dda1b12016-04-16 04:33:55 +100094from hmac import compare_digest
Steven D'Aprano95702722016-04-15 01:51:31 +100095from random import SystemRandom
96
97_sysrand = SystemRandom()
98
99randbits = _sysrand.getrandbits
100choice = _sysrand.choice
101
102def randbelow(exclusive_upper_bound):
103 return _sysrand._randbelow(exclusive_upper_bound)
104
105DEFAULT_ENTROPY = 32 # number of bytes to return by default
106
107def token_bytes(nbytes=None):
108 if nbytes is None:
109 nbytes = DEFAULT_ENTROPY
110 return os.urandom(nbytes)
111
112def token_hex(nbytes=None):
113 return binascii.hexlify(token_bytes(nbytes)).decode('ascii')
114
115def token_urlsafe(nbytes=None):
116 tok = token_bytes(nbytes)
117 return base64.urlsafe_b64encode(tok).rstrip(b'=').decode('ascii')