Python生成加密随机数

Python 生成加密随机数

当需要生成安全信息,比如令牌账户验证和密码

1
pip install secrets
1
2
3
4
import secrets

random = secrets.randbelow(100) # 0 到 100 包含两端的
print(random)
1
2
3
# 第一中方法choice方法
random_choice = secrets.choice([1,2,3,4,5])
print(random_choice)

密码生成

1
2
3
4
5
6
7
8
import secrets
import string

def generate_password(length: int):
chars: str = string.ascii_letters + string.digits + string.punctuation
password: str = ''.join(secrets.choice(chars) for _ in range(length))

print('password:', password)

通过比特位生成随机数

1
2
3
4
5
import secrets

random = secrets.randbits(16) # 0 到 2^n - 1 包含两端的

print(random)

生成令牌 tokens

1
2
3
4
5
import secrets

token = secrets.token_bytes(32) # 就会使用32字节的随机熵值
tokens = secrets.token_hex(32)
print(length(tokens))
1
2
3
4
import secrets
token = secrets.token_urlsafe(16) # token URL安全生成方法

print(f'www.website.com/{token}')

密码

1
2
3
4
5
6
7
import secrets

user_input = 'abc123'
password = 'abc123'

if secrets.compare_digest(user_input, password):
print('You are logged in')