You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Fernet/os.urandom生成符合指定规则的12位安全密码

实现方案

核心思路是先强制取出要求的四类字符各1个,再补全剩余长度的随机字符,最后打乱整体顺序避免字符位置固定,全程用os.urandom实现密码学安全的随机选择。

完整可运行代码

import os
import string

# 定义四类字符池
UPPERCASE = string.ascii_uppercase
LOWERCASE = string.ascii_lowercase
DIGITS = string.digits
SYMBOLS = string.punctuation
ALL_CHARS = UPPERCASE + LOWERCASE + DIGITS + SYMBOLS

def generate_secure_password(length: int = 12) -> str:
    if length < 4:
        raise ValueError("密码长度至少需要4位,以满足四类字符各至少一个的要求")
    
    password_chars = []
    # 先各取1个要求的字符,保证四类都存在
    for char_pool in (UPPERCASE, LOWERCASE, DIGITS, SYMBOLS):
        # 用os.urandom生成安全随机索引
        idx = int.from_bytes(os.urandom(2), byteorder="little") % len(char_pool)
        password_chars.append(char_pool[idx])
    
    # 补全剩余长度的字符
    remaining = length - 4
    for _ in range(remaining):
        idx = int.from_bytes(os.urandom(2), byteorder="little") % len(ALL_CHARS)
        password_chars.append(ALL_CHARS[idx])
    
    # 打乱字符顺序,避免前四位固定类型
    for i in range(len(password_chars)-1, 0, -1):
        j = int.from_bytes(os.urandom(2), byteorder="little") % (i+1)
        password_chars[i], password_chars[j] = password_chars[j], password_chars[i]
    
    return "".join(password_chars)

# 测试调用
if __name__ == "__main__":
    print(generate_secure_password())

注意事项

  • 这里用2字节生成随机索引,覆盖的取值范围远大于字符池长度,模运算不会明显降低随机性
  • 手动实现洗牌逻辑而不调用random.shuffle,避免引入非密码学安全的随机源
  • 可以根据需求调整字符池,比如剔除容易混淆的l、I、1、0、O等字符

内容的提问来源于stack exchange,提问作者Zeta Sephin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 00:27:02