python生成密钥

95 阅读1分钟

使用 python 内置库 secrets 生成密钥

import secrets

# 生成长度为 16 的随机字符串
print(secrets.token_hex(16))

生成指定长度的密钥

import secrets
import string
  
def generate_key(length = 32):
    alphabet = string.ascii_letters + string.digits
    return ''.join(secrets.choice(alphabet) for _ in range(length))

print(generate_key(64))

使用 os 生成

import os

key = os.urandom(16)
print(key) # 原始字节
print(key.hex()) # 16进制字符串

效果

b'P\xe9\xe6\xf1\xfd\xe1\xe2,\xc9\r\xf1e\xb7!\xc2\x9f'
50e9e6f1fde1e22cc90df165b721c29f

使用 hashlib 配合 os.urandom() 生成固定长度密钥

import os
import hashlib

random_bytes = os.urandom(32)
secret_key = hashlib.sha256(random_bytes).hexdigest()
print(secret_key)

生成加密安全令牌

import secrets

token = secrets.token_urlsafe(32)
print(token)

使用 uuid 生成

import uuid

unique_key = str(uuid.uuid4())
print(unique_key)