随机密码生成器:12行核心代码揭秘

1. 导入模块

import random
import string
  • random:用于生成随机数/随机选择

  • string:提供常用的字符串常量(如字母、数字等)

2. 函数定义

def generate_password(length=12, complexity='medium'):

定义了一个名为generate_password的函数,有两个可选参数:

  • length:密码长度,默认为12

  • complexity:密码复杂度,默认为'medium'

3. 定义字符集

lowercase = string.ascii_lowercase  # 所有小写字母 'abc...z'
uppercase = string.ascii_uppercase  # 所有大写字母 'ABC...Z'
digits = string.digits              # 所有数字 '012...9'
punctuation = string.punctuation    # 所有标点符号 '!"#$%...'

4. 根据复杂度选择字符集

if complexity == 'low':
    chars = lowercase + digits
elif complexity == 'medium':
    chars = lowercase + uppercase + digits
elif complexity == 'high':
    chars = lowercase + uppercase + digits + punctuation
else:
    raise ValueError("复杂度必须是 'low', 'medium' 或 'high'")

根据用户选择的复杂度,决定使用哪些字符来生成密码。

5. 检查密码长度

if length < 4:
    raise ValueError("密码长度至少为4")

确保密码长度不小于4(因为后面要保证包含多种字符类型)

6. 生成密码核心部分

password = []  # 创建一个空列表来存放密码字符

# 确保至少包含一个小写字母
password.append(random.choice(lowercase))

# 如果是中等或高复杂度,确保包含大写字母和数字
if complexity in ('medium', 'high'):
    password.append(random.choice(uppercase))
    password.append(random.choice(digits))

# 如果是高复杂度,确保包含标点符号
if complexity == 'high':
    password.append(random.choice(punctuation))

# 计算剩余需要生成的字符数
remaining_length = length - len(password)

# 从选定的字符集中随机选择剩余字符
password.extend(random.choice(chars) for _ in range(remaining_length))

# 打乱所有字符的顺序,避免前面固定的字符类型集中在开头
random.shuffle(password)

# 将字符列表合并成字符串返回
return ''.join(password)

7. 示例用法

print("简单密码(8位):", generate_password(8, 'low'))
print("中等密码(12位):", generate_password())
print("复杂密码(16位):", generate_password(16, 'high'))

代码执行流程总结:

  1. 确定要使用哪些字符(根据复杂度)

  2. 确保密码包含至少一个每种类型的字符

  3. 填充剩余长度的随机字符

  4. 打乱所有字符的顺序

  5. 返回最终密码字符串

为什么这样设计?

  • 保证密码包含多种字符类型(提高安全性)

  • 随机打乱顺序(避免模式化)

  • 灵活控制长度和复杂度

8.完整代码

import random
import string

def generate_password(length=12, complexity='medium'):
    """
    生成随机密码
    
    参数:
        length (int): 密码长度 (默认12)
        complexity (str): 密码复杂度 ('low', 'medium', 'high' 默认'medium')
    
    返回:
        str: 生成的随机密码
    """
    # 定义字符集
    lowercase = string.ascii_lowercase
    uppercase = string.ascii_uppercase
    digits = string.digits
    punctuation = string.punctuation
    
    # 根据复杂度选择字符集
    if complexity == 'low':
        chars = lowercase + digits
    elif complexity == 'medium':
        chars = lowercase + uppercase + digits
    elif complexity == 'high':
        chars = lowercase + uppercase + digits + punctuation
    else:
        raise ValueError("复杂度必须是 'low', 'medium' 或 'high'")
    
    # 确保密码长度合理
    if length < 4:
        raise ValueError("密码长度至少为4")
    
    # 生成密码
    password = []
    
    # 确保密码包含至少一个每种类型的字符(根据复杂度)
    password.append(random.choice(lowercase))
    if complexity in ('medium', 'high'):
        password.append(random.choice(uppercase))
        password.append(random.choice(digits))
    if complexity == 'high':
        password.append(random.choice(punctuation))
    
    # 填充剩余字符
    remaining_length = length - len(password)
    password.extend(random.choice(chars) for _ in range(remaining_length))
    
    # 打乱顺序
    random.shuffle(password)
    
    return ''.join(password)

# 示例用法
print("简单密码(8位):", generate_password(8, 'low'))
print("中等密码(12位):", generate_password())
print("复杂密码(16位):", generate_password(16, 'high'))

你可能感兴趣的:(python,开发语言)