| 1 |
:mod:`!secrets` --- Generate secure random numbers for managing secrets |
| 2 |
======================================================================= |
| 3 |
|
| 4 |
.. module:: secrets |
| 5 |
:synopsis: Generate secure random numbers for managing secrets. |
| 6 |
|
| 7 |
.. moduleauthor:: Steven D'Aprano <[email protected]> |
| 8 |
.. sectionauthor:: Steven D'Aprano <[email protected]> |
| 9 |
.. versionadded:: 3.6 |
| 10 |
|
| 11 |
.. testsetup:: |
| 12 |
|
| 13 |
from secrets import * |
| 14 |
__name__ = '<doctest>' |
| 15 |
|
| 16 |
**Source code:** :source:`Lib/secrets.py` |
| 17 |
|
| 18 |
------------- |
| 19 |
|
| 20 |
The :mod:`!secrets` module is used for generating cryptographically strong |
| 21 |
random numbers suitable for managing data such as passwords, account |
| 22 |
authentication, security tokens, and related secrets. |
| 23 |
|
| 24 |
In particular, :mod:`!secrets` should be used in preference to the |
| 25 |
default pseudo-random number generator in the :mod:`random` module, which |
| 26 |
is designed for modelling and simulation, not security or cryptography. |
| 27 |
|
| 28 |
.. seealso:: |
| 29 |
|
| 30 |
:pep:`506` |
| 31 |
|
| 32 |
|
| 33 |
Random numbers |
| 34 |
-------------- |
| 35 |
|
| 36 |
The :mod:`!secrets` module provides access to the most secure source of |
| 37 |
randomness that your operating system provides. |
| 38 |
|
| 39 |
.. class:: SystemRandom |
| 40 |
|
| 41 |
A class for generating random numbers using the highest-quality |
| 42 |
sources provided by the operating system. See |
| 43 |
:class:`random.SystemRandom` for additional details. |
| 44 |
|
| 45 |
.. function:: choice(seq) |
| 46 |
|
| 47 |
Return a randomly chosen element from a non-empty sequence. |
| 48 |
|
| 49 |
.. function:: randbelow(exclusive_upper_bound) |
| 50 |
|
| 51 |
Return a random int in the range [0, *exclusive_upper_bound*). |
| 52 |
|
| 53 |
.. function:: randbits(k) |
| 54 |
|
| 55 |
Return a non-negative int with *k* random bits. |
| 56 |
|
| 57 |
|
| 58 |
Generating tokens |
| 59 |
----------------- |
| 60 |
|
| 61 |
The :mod:`!secrets` module provides functions for generating secure |
| 62 |
tokens, suitable for applications such as password resets, |
| 63 |
hard-to-guess URLs, and similar. |
| 64 |
|
| 65 |
.. function:: token_bytes(nbytes=None) |
| 66 |
|
| 67 |
Return a random byte string containing *nbytes* number of bytes. |
| 68 |
|
| 69 |
If *nbytes* is not specified or ``None``, :const:`DEFAULT_ENTROPY` |
| 70 |
is used instead. |
| 71 |
|
| 72 |
.. doctest:: |
| 73 |
|
| 74 |
>>> token_bytes(16) # doctest: +SKIP |
| 75 |
b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b' |
| 76 |
|
| 77 |
|
| 78 |
.. function:: token_hex(nbytes=None) |
| 79 |
|
| 80 |
Return a random text string, in hexadecimal. The string has *nbytes* |
| 81 |
random bytes, each byte converted to two hex digits. |
| 82 |
|
| 83 |
If *nbytes* is not specified or ``None``, :const:`DEFAULT_ENTROPY` |
| 84 |
is used instead. |
| 85 |
|
| 86 |
.. doctest:: |
| 87 |
|
| 88 |
>>> token_hex(16) # doctest: +SKIP |
| 89 |
'f9bf78b9a18ce6d46a0cd2b0b86df9da' |
| 90 |
|
| 91 |
.. function:: token_urlsafe(nbytes=None) |
| 92 |
|
| 93 |
Return a random URL-safe text string, containing *nbytes* random |
| 94 |
bytes. The text is Base64 encoded, so on average each byte results |
| 95 |
in approximately 1.3 characters. |
| 96 |
|
| 97 |
If *nbytes* is not specified or ``None``, :const:`DEFAULT_ENTROPY` |
| 98 |
is used instead. |
| 99 |
|
| 100 |
.. doctest:: |
| 101 |
|
| 102 |
>>> token_urlsafe(16) # doctest: +SKIP |
| 103 |
'Drmhze6EPcv0fN_81Bj-nA' |
| 104 |
|
| 105 |
|
| 106 |
How many bytes should tokens use? |
| 107 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 108 |
|
| 109 |
To be secure against |
| 110 |
`brute-force attacks <https://en.wikipedia.org/wiki/Brute-force_attack>`_, |
| 111 |
tokens need to have sufficient randomness. Unfortunately, what is |
| 112 |
considered sufficient will necessarily increase as computers get more |
| 113 |
powerful and able to make more guesses in a shorter period. As of 2015, |
| 114 |
it is believed that 32 bytes (256 bits) of randomness is sufficient for |
| 115 |
the typical use-case expected for the :mod:`!secrets` module. |
| 116 |
|
| 117 |
For those who want to manage their own token length, you can explicitly |
| 118 |
specify how much randomness is used for tokens by giving an :class:`int` |
| 119 |
argument to the various ``token_*`` functions. That argument is taken |
| 120 |
as the number of bytes of randomness to use. |
| 121 |
|
| 122 |
Otherwise, if no argument is provided, or if the argument is ``None``, |
| 123 |
the ``token_*`` functions use :const:`DEFAULT_ENTROPY` instead. |
| 124 |
|
| 125 |
.. data:: DEFAULT_ENTROPY |
| 126 |
|
| 127 |
Default number of bytes of randomness used by the ``token_*`` functions. |
| 128 |
|
| 129 |
The exact value is subject to change at any time, including during |
| 130 |
maintenance releases. |
| 131 |
|
| 132 |
|
| 133 |
Other functions |
| 134 |
--------------- |
| 135 |
|
| 136 |
.. function:: compare_digest(a, b) |
| 137 |
|
| 138 |
Return ``True`` if strings or |
| 139 |
:term:`bytes-like objects <bytes-like object>` |
| 140 |
*a* and *b* are equal, otherwise ``False``, |
| 141 |
using a "constant-time compare" to reduce the risk of |
| 142 |
`timing attacks <https://codahale.com/a-lesson-in-timing-attacks/>`_. |
| 143 |
See :func:`hmac.compare_digest` for additional details. |
| 144 |
|
| 145 |
|
| 146 |
Recipes and best practices |
| 147 |
-------------------------- |
| 148 |
|
| 149 |
This section shows recipes and best practices for using :mod:`!secrets` |
| 150 |
to manage a basic level of security. |
| 151 |
|
| 152 |
Generate an eight-character alphanumeric password: |
| 153 |
|
| 154 |
.. testcode:: |
| 155 |
|
| 156 |
import string |
| 157 |
import secrets |
| 158 |
alphabet = string.ascii_letters + string.digits |
| 159 |
password = ''.join(secrets.choice(alphabet) for i in range(8)) |
| 160 |
|
| 161 |
|
| 162 |
.. note:: |
| 163 |
|
| 164 |
Applications should not |
| 165 |
:cwe:`store passwords in a recoverable format <257>`, |
| 166 |
whether plain text or encrypted. They should be salted and hashed |
| 167 |
using a cryptographically strong one-way (irreversible) hash function. |
| 168 |
|
| 169 |
|
| 170 |
Generate a ten-character alphanumeric password with at least one |
| 171 |
lowercase character, at least one uppercase character, and at least |
| 172 |
three digits: |
| 173 |
|
| 174 |
.. testcode:: |
| 175 |
|
| 176 |
import string |
| 177 |
import secrets |
| 178 |
alphabet = string.ascii_letters + string.digits |
| 179 |
while True: |
| 180 |
password = ''.join(secrets.choice(alphabet) for i in range(10)) |
| 181 |
if (any(c.islower() for c in password) |
| 182 |
and any(c.isupper() for c in password) |
| 183 |
and sum(c.isdigit() for c in password) >= 3): |
| 184 |
break |
| 185 |
|
| 186 |
|
| 187 |
Generate an `XKCD-style passphrase <https://xkcd.com/936/>`_: |
| 188 |
|
| 189 |
.. testcode:: |
| 190 |
|
| 191 |
import secrets |
| 192 |
# On standard Linux systems, use a convenient dictionary file. |
| 193 |
# Other platforms may need to provide their own word-list. |
| 194 |
with open('/usr/share/dict/words') as f: |
| 195 |
words = [word.strip() for word in f] |
| 196 |
password = ' '.join(secrets.choice(words) for i in range(4)) |
| 197 |
|
| 198 |
|
| 199 |
Generate a hard-to-guess temporary URL containing a security token |
| 200 |
suitable for password recovery applications: |
| 201 |
|
| 202 |
.. testcode:: |
| 203 |
|
| 204 |
import secrets |
| 205 |
url = 'https://example.com/reset=' + secrets.token_urlsafe() |
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
.. |
| 210 |
# This modeline must appear within the last ten lines of the file. |
| 211 |
kate: indent-width 3; remove-trailing-space on; replace-tabs on; encoding utf-8; |