secrets
— Generate secure random numbers for managing secrets生成用于管理机密的安全随机数¶
New in version 3.6.版本3.6中新增。
Source code: Lib/secrets.py
The secrets
module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.secrets
模块用于生成加密强随机数,适用于管理密码、帐户身份验证、安全令牌和相关机密等数据。
In particular, 特别是,与secrets
should be used in preference to the default pseudo-random number generator in the random
module, which is designed for modelling and simulation, not security or cryptography.random
模块中的默认伪随机数生成器相比,应优先使用secrets
,random
模块是为建模和仿真而设计的,而不是为了安全或加密。
See also参阅
Random numbers随机数¶
The secrets
module provides access to the most secure source of randomness that your operating system provides.secrets
模块提供对操作系统提供的最安全的随机性源的访问。
-
class
secrets.
SystemRandom
¶ A class for generating random numbers using the highest-quality sources provided by the operating system.使用操作系统提供的最高质量源生成随机数的类。Seerandom.SystemRandom
for additional details.
-
secrets.
choice
(sequence)¶ Return a randomly-chosen element from a non-empty sequence.从非空序列中返回随机选择的元素。
-
secrets.
randbelow
(n)¶ Return a random int in the range [0, n).返回[0, n)范围内的随机整数。
-
secrets.
randbits
(k)¶ Return an int with k random bits.返回一个带有k个随机位的整数。
Generating tokens生成令牌¶
The secrets
module provides functions for generating secure tokens, suitable for applications such as password resets, hard-to-guess URLs, and similar.secrets
模块提供生成安全令牌的功能,适用于密码重置、难以猜测的URL等应用程序。
-
secrets.
token_bytes
([nbytes=None])¶ Return a random byte string containing nbytes number of bytes.返回一个随机字节字符串,其中包含nbytes的字节数。If nbytes is如果未提供nbytes或提供了None
or not supplied, a reasonable default is used.None
,则使用合理的默认值。>>> token_bytes(16)
b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b'
-
secrets.
token_hex
([nbytes=None])¶ Return a random text string, in hexadecimal.返回随机文本字符串(十六进制)。The string has nbytes random bytes, each byte converted to two hex digits.字符串有nbytes随机字节,每个字节转换为两个十六进制数字。If nbytes is如果未提供nbytes或提供了None
or not supplied, a reasonable default is used.None
,则使用合理的默认值。>>> token_hex(16)
'f9bf78b9a18ce6d46a0cd2b0b86df9da'
-
secrets.
token_urlsafe
([nbytes=None])¶ Return a random URL-safe text string, containing nbytes random bytes.返回一个随机URL安全文本字符串,包含nbytes随机字节。The text is Base64 encoded, so on average each byte results in approximately 1.3 characters.文本是Base64编码的,因此平均每个字节产生大约1.3个字符。If nbytes is如果未提供nbytes或提供了None
or not supplied, a reasonable default is used.None
,则使用合理的默认值。>>> token_urlsafe(16)
'Drmhze6EPcv0fN_81Bj-nA'
How many bytes should tokens use?令牌应该使用多少字节?¶
To be secure against brute-force attacks, 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 截至2015年,据信32字节(256位)的随机性足以满足secrets
module.secrets
模块的典型用例。
For those who want to manage their own token length, you can explicitly specify how much randomness is used for tokens by giving an 对于那些想要管理自己的令牌长度的人,您可以通过给各种int
argument to the various token_*
functions. token_*
函数提供一个int
参数来显式指定令牌使用了多少随机性。That argument is taken as the number of bytes of randomness to use.该参数被视为要使用的随机性字节数。
Otherwise, if no argument is provided, or if the argument is 否则,如果未提供参数,或者参数为None
, the token_*
functions will use a reasonable default instead.None
,则token_*
函数将使用合理的默认值。
Note
That default is subject to change at any time, including during maintenance releases.该默认值随时可能更改,包括在维护版本期间。
Other functions其他功能¶
-
secrets.
compare_digest
(a, b)¶ Return如果字符串a和b相等,则返回True
if strings a and b are equal, otherwiseFalse
, in such a way as to reduce the risk of timing attacks.True
,否则返回False
,以降低定时攻击的风险。See有关更多详细信息,请参阅hmac.compare_digest()
for additional details.hmac.compare_digest()
。
Recipes and best practices食谱和最佳实践¶
This section shows recipes and best practices for using 本节展示了使用secrets
to manage a basic level of security.secrets
管理基本安全级别的方法和最佳实践。
Generate an eight-character alphanumeric password:生成八个字符的字母数字密码:
import string
import secrets
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for i in range(8))
Note
Applications should not store passwords in a recoverable format, whether plain text or encrypted. 应用程序不应以可恢复格式存储密码,无论是纯文本还是加密格式。They should be salted and hashed using a cryptographically-strong one-way (irreversible) hash function.应该使用加密强单向(不可逆)散列函数对它们进行加密和散列。
Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits:生成包含至少一个小写字符、至少一个大写字符和至少三位数字的十字符字母数字密码:
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
Generate an XKCD-style passphrase:生成XKCD样式的密码短语:
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))
Generate a hard-to-guess temporary URL containing a security token suitable for password recovery applications:生成包含适用于密码恢复应用程序的安全令牌的难以猜测的临时URL:
import secrets
url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()