secrets — 生成用于管理保密的安全随机数

Added in version 3.6.

源代码: 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.

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.

另请参阅

PEP 506

随机数

The secrets module provides access to the most secure source of randomness that your operating system provides.

class secrets. SystemRandom

A class for generating random numbers using the highest-quality sources provided by the operating system. See random.SystemRandom 了解额外细节。

secrets. choice ( seq )

Return a randomly chosen element from a non-empty sequence.

secrets. randbelow ( exclusive_upper_bound )

Return a random int in the range [0, exclusive_upper_bound ).

secrets. randbits ( k )

Return a non-negative int with k random bits.

生成令牌

The secrets module provides functions for generating secure tokens, suitable for applications such as password resets, hard-to-guess URLs, and similar.

secrets. token_bytes ( [ nbytes=None ] )

Return a random byte string containing nbytes number of bytes. If nbytes is None or not supplied, a reasonable default is used.

>>> token_bytes(16)
b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b'