🛠️ToolsShed

密码生成器

使用可自定义选项生成强密码。

6128

密码生成器使用浏览器内置的随机数生成器(Web Crypto API)创建加密安全的随机密码。这意味着密码完全在您的设备上生成——它们从不通过网络发送或存储在任何地方,即使对于高度敏感的账户也可以安全使用此工具。

配置长度(8-128 个字符)和字符集以符合您创建账户的服务要求。大多数安全专家建议使用大写字母、小写字母、数字和符号混合的至少 16 个字符的密码。

密码管理器是密码生成器的最佳伴侣。Bitwarden、1Password 或 KeePass 等工具可让您为每个网站生成和存储唯一的随机密码,而无需记忆它们。切勿在多个服务中重复使用密码。

常见问题

代码实现

import secrets
import string

def generate_password(
    length: int = 16,
    use_upper: bool = True,
    use_lower: bool = True,
    use_digits: bool = True,
    use_symbols: bool = True,
) -> str:
    """Generate a cryptographically secure random password."""
    charset = ""
    required = []

    if use_lower:
        charset += string.ascii_lowercase
        required.append(secrets.choice(string.ascii_lowercase))
    if use_upper:
        charset += string.ascii_uppercase
        required.append(secrets.choice(string.ascii_uppercase))
    if use_digits:
        charset += string.digits
        required.append(secrets.choice(string.digits))
    if use_symbols:
        symbols = "!@#$%^&*()-_=+[]{}|;:,.<>?"
        charset += symbols
        required.append(secrets.choice(symbols))

    if not charset:
        raise ValueError("At least one character type must be selected")

    # Fill the rest of the password
    remaining = [secrets.choice(charset) for _ in range(length - len(required))]
    password_list = required + remaining

    # Shuffle to avoid predictable positions
    secrets.SystemRandom().shuffle(password_list)
    return "".join(password_list)

# Examples
print(generate_password(16))
print(generate_password(24, use_symbols=False))
print(generate_password(8, use_upper=False, use_symbols=False))

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.