1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
<span id="secrets-generate-secure-random-numbers-for-managing-secrets"></span><h1>secrets — Generate secure random numbers for managing secrets</h1> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/secrets.py">Lib/secrets.py</a></p> <p>The <a class="reference internal" href="#module-secrets" title="secrets: Generate secure random numbers for managing secrets."><code>secrets</code></a> module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.</p> <p>In particular, <a class="reference internal" href="#module-secrets" title="secrets: Generate secure random numbers for managing secrets."><code>secrets</code></a> should be used in preference to the default pseudo-random number generator in the <a class="reference internal" href="random#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code>random</code></a> module, which is designed for modelling and simulation, not security or cryptography.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0506/"><strong>PEP 506</strong></a></p> </div> <section id="random-numbers"> <h2>Random numbers</h2> <p>The <a class="reference internal" href="#module-secrets" title="secrets: Generate secure random numbers for managing secrets."><code>secrets</code></a> module provides access to the most secure source of randomness that your operating system provides.</p> <dl class="py class"> <dt class="sig sig-object py" id="secrets.SystemRandom">
<code>class secrets.SystemRandom</code> </dt> <dd>
<p>A class for generating random numbers using the highest-quality sources provided by the operating system. See <a class="reference internal" href="random#random.SystemRandom" title="random.SystemRandom"><code>random.SystemRandom</code></a> for additional details.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="secrets.choice">
<code>secrets.choice(sequence)</code> </dt> <dd>
<p>Return a randomly chosen element from a non-empty sequence.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="secrets.randbelow">
<code>secrets.randbelow(n)</code> </dt> <dd>
<p>Return a random int in the range [0, <em>n</em>).</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="secrets.randbits">
<code>secrets.randbits(k)</code> </dt> <dd>
<p>Return an int with <em>k</em> random bits.</p> </dd>
</dl> </section> <section id="generating-tokens"> <h2>Generating tokens</h2> <p>The <a class="reference internal" href="#module-secrets" title="secrets: Generate secure random numbers for managing secrets."><code>secrets</code></a> module provides functions for generating secure tokens, suitable for applications such as password resets, hard-to-guess URLs, and similar.</p> <dl class="py function"> <dt class="sig sig-object py" id="secrets.token_bytes">
<code>secrets.token_bytes([nbytes=None])</code> </dt> <dd>
<p>Return a random byte string containing <em>nbytes</em> number of bytes. If <em>nbytes</em> is <code>None</code> or not supplied, a reasonable default is used.</p> <pre data-language="pycon3">>>> token_bytes(16)
b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b'
</pre> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="secrets.token_hex">
<code>secrets.token_hex([nbytes=None])</code> </dt> <dd>
<p>Return a random text string, in hexadecimal. The string has <em>nbytes</em> random bytes, each byte converted to two hex digits. If <em>nbytes</em> is <code>None</code> or not supplied, a reasonable default is used.</p> <pre data-language="pycon3">>>> token_hex(16)
'f9bf78b9a18ce6d46a0cd2b0b86df9da'
</pre> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="secrets.token_urlsafe">
<code>secrets.token_urlsafe([nbytes=None])</code> </dt> <dd>
<p>Return a random URL-safe text string, containing <em>nbytes</em> random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If <em>nbytes</em> is <code>None</code> or not supplied, a reasonable default is used.</p> <pre data-language="pycon3">>>> token_urlsafe(16)
'Drmhze6EPcv0fN_81Bj-nA'
</pre> </dd>
</dl> <section id="how-many-bytes-should-tokens-use"> <h3>How many bytes should tokens use?</h3> <p>To be secure against <a class="reference external" href="https://en.wikipedia.org/wiki/Brute-force_attack">brute-force attacks</a>, tokens need to have sufficient randomness. Unfortunately, what is considered sufficient will necessarily increase as computers get more powerful and able to make more guesses in a shorter period. As of 2015, it is believed that 32 bytes (256 bits) of randomness is sufficient for the typical use-case expected for the <a class="reference internal" href="#module-secrets" title="secrets: Generate secure random numbers for managing secrets."><code>secrets</code></a> module.</p> <p>For those who want to manage their own token length, you can explicitly specify how much randomness is used for tokens by giving an <a class="reference internal" href="functions#int" title="int"><code>int</code></a> argument to the various <code>token_*</code> functions. That argument is taken as the number of bytes of randomness to use.</p> <p>Otherwise, if no argument is provided, or if the argument is <code>None</code>, the <code>token_*</code> functions will use a reasonable default instead.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>That default is subject to change at any time, including during maintenance releases.</p> </div> </section> </section> <section id="other-functions"> <h2>Other functions</h2> <dl class="py function"> <dt class="sig sig-object py" id="secrets.compare_digest">
<code>secrets.compare_digest(a, b)</code> </dt> <dd>
<p>Return <code>True</code> if strings or <a class="reference internal" href="../glossary#term-bytes-like-object"><span class="xref std std-term">bytes-like objects</span></a> <em>a</em> and <em>b</em> are equal, otherwise <code>False</code>, using a “constant-time compare” to reduce the risk of <a class="reference external" href="https://codahale.com/a-lesson-in-timing-attacks/">timing attacks</a>. See <a class="reference internal" href="hmac#hmac.compare_digest" title="hmac.compare_digest"><code>hmac.compare_digest()</code></a> for additional details.</p> </dd>
</dl> </section> <section id="recipes-and-best-practices"> <h2>Recipes and best practices</h2> <p>This section shows recipes and best practices for using <a class="reference internal" href="#module-secrets" title="secrets: Generate secure random numbers for managing secrets."><code>secrets</code></a> to manage a basic level of security.</p> <p>Generate an eight-character alphanumeric password:</p> <pre data-language="python">import string
import secrets
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for i in range(8))
</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Applications should not <a class="reference external" href="https://cwe.mitre.org/data/definitions/257.html">store passwords in a recoverable format</a>, whether plain text or encrypted. They should be salted and hashed using a cryptographically strong one-way (irreversible) hash function.</p> </div> <p>Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits:</p> <pre data-language="python">import string
import secrets
alphabet = string.ascii_letters + string.digits
while True:
password = ''.join(secrets.choice(alphabet) for i in range(10))
if (any(c.islower() for c in password)
and any(c.isupper() for c in password)
and sum(c.isdigit() for c in password) >= 3):
break
</pre> <p>Generate an <a class="reference external" href="https://xkcd.com/936/">XKCD-style passphrase</a>:</p> <pre data-language="python">import secrets
# On standard Linux systems, use a convenient dictionary file.
# Other platforms may need to provide their own word-list.
with open('/usr/share/dict/words') as f:
words = [word.strip() for word in f]
password = ' '.join(secrets.choice(words) for i in range(4))
</pre> <p>Generate a hard-to-guess temporary URL containing a security token suitable for password recovery applications:</p> <pre data-language="python">import secrets
url = 'https://example.com/reset=' + secrets.token_urlsafe()
</pre> </section> <div class="_attribution">
<p class="_attribution-p">
© 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br>
<a href="https://docs.python.org/3.12/library/secrets.html" class="_attribution-link">https://docs.python.org/3.12/library/secrets.html</a>
</p>
</div>
|