用于生成安全随机数的 Python 模块
在本文中,我们将了解如何生成可有效用作密码的安全随机数。除了随机数外,我们还可以添加字母和其他字符使其更好。
使用 secrets
secrets 模块有一个名为 choice 的函数,它可用于使用 for 循环和 range 函数生成所需长度的密码。
示例
import secrets
import string
allowed_chars = string.ascii_letters + string.digits + string.printable
pswd = ''.join(secrets.choice(allowed_chars) for i in range(8))
print("The generated password is: \n",pswd)输出
运行以上代码后,我们会得到以下结果 −
The generated password is: $pB7WY
使用 at least 条件
我们还可以强制要求小写字母和大写字母以及数字成为密码生成器的一部分。这里我们再次使用 secrets 模块。
示例
import secrets
import string
allowed_chars = string.ascii_letters + string.digits + string.printable
while True:
pswd = ''.join(secrets.choice(allowed_chars) for i in range(8))
if (any(c.islower() for c in pswd) and any(c.isupper()
for c in pswd) and sum(c.isdigit() for c in pswd) >= 3):
print("The generated pswd is: \n", pswd)
break输出
运行以上代码后,我们会得到以下结果 −
The generated pswd is: p7$7nS2w
随机令牌
在处理 URL 时,如果你希望出现一个随机令牌成为 URL 的一部分,我们可以使用 secrets 模块中的以下方法。
示例
import secrets
# A random byte string
tkn1 = secrets.token_bytes(8)
# A random text string in hexadecimal
tkn2 = secrets.token_hex(8)
# random URL-safe text string
url = 'https://thename.com/reset=' + secrets.token_urlsafe()
print("A random byte string:\n ",tkn1)
print("A random text string in hexadecimal: \n ",tkn2)
print("A text string with url-safe token: \n ",url)输出
运行以上代码后,我们会得到以下结果 −
A random byte string: b'\x0b-\xb2\x13\xb0Z#\x81' A random text string in hexadecimal: d94da5763fce71a3 A text string with url-safe token: https://thename.com/reset=Rd8eVookY54Q7aTipZfdmz-HS62rHmRjSAXumZdNITo
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP