0% found this document useful (0 votes)
7 views5 pages

1

The document defines a PasswordGenerator class for creating secure passwords and a PasswordAnalyzer class for evaluating password strength. It includes methods for generating random passwords, pronounceable passwords, and passphrases, along with a scoring system to analyze password strength based on various criteria. The document also features a demo function to showcase the usage of these password tools.

Uploaded by

hstanzhuo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views5 pages

1

The document defines a PasswordGenerator class for creating secure passwords and a PasswordAnalyzer class for evaluating password strength. It includes methods for generating random passwords, pronounceable passwords, and passphrases, along with a scoring system to analyze password strength based on various criteria. The document also features a demo function to showcase the usage of these password tools.

Uploaded by

hstanzhuo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

import random

import string
import re
import hashlib
import secrets
from enum import Enum
from typing import Dict, List, Tuple

class PasswordStrength(Enum):
VERY_WEAK = 1
WEAK = 2
MEDIUM = 3
STRONG = 4
VERY_STRONG = 5

class PasswordGenerator:
def __init__(self):
self.lowercase = string.ascii_lowercase
self.uppercase = string.ascii_uppercase
self.digits = string.digits
self.symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?"
self.similar_chars = "il1Lo0O"

# 常见密码模式(用于避免)
self.common_patterns = [
"123456", "password", "qwerty", "abc123", "admin",
"letmein", "welcome", "monkey", "dragon", "master"
]

def generate_password(self, length: int = 12, include_symbols: bool = True,


exclude_similar: bool = True, pronounceable: bool = False)
-> str:
"""生成随机密码"""
if length < 4:
raise ValueError("密码长度至少为 4 位")

charset = self.lowercase + self.uppercase + self.digits


if include_symbols:
charset += self.symbols

if exclude_similar:
charset = ''.join(c for c in charset if c not in self.similar_chars)

if pronounceable:
return self._generate_pronounceable_password(length)

# 确保包含各种字符类型
password = []
password.append(secrets.choice(self.lowercase))
password.append(secrets.choice(self.uppercase))
password.append(secrets.choice(self.digits))

if include_symbols:
password.append(secrets.choice(self.symbols))

# 填充剩余长度
for _ in range(length - len(password)):
password.append(secrets.choice(charset))
# 随机打乱顺序
secrets.SystemRandom().shuffle(password)
return ''.join(password)

def _generate_pronounceable_password(self, length: int) -> str:


"""生成相对容易发音的密码"""
consonants = "bcdfghjklmnpqrstvwxyz"
vowels = "aeiou"
result = []

for i in range(length):
if i % 2 == 0: # 偶数位置用辅音
char = secrets.choice(consonants)
if secrets.randbelow(3) == 0: # 1/3 概率大写
char = char.upper()
else: # 奇数位置用元音
char = secrets.choice(vowels)

# 偶尔插入数字或符号
if i > 2 and secrets.randbelow(5) == 0:
if secrets.randbelow(2):
result.append(str(secrets.randbelow(10)))
else:
result.append(secrets.choice("!@#$%"))

result.append(char)

return ''.join(result)[:length]

def generate_passphrase(self, num_words: int = 4, separator: str = "-") -> str:


"""生成密码短语"""
word_list = [
"apple", "beach", "chair", "dream", "eagle", "flame", "guitar",
"house",
"island", "jungle", "knight", "lemon", "mountain", "ocean", "piano",
"queen",
"river", "sunset", "tiger", "umbrella", "village", "window", "yellow",
"zebra",
"castle", "forest", "garden", "library", "rainbow", "thunder",
"wizard", "crystal"
]

words = []
for _ in range(num_words):
word = secrets.choice(word_list)
# 随机大写首字母
if secrets.randbelow(2):
word = word.capitalize()
words.append(word)

# 添加随机数字
words.append(str(secrets.randbelow(100, 999)))

return separator.join(words)

class PasswordAnalyzer:
def __init__(self):
self.common_passwords = set([
"123456", "password", "123456789", "12345678", "12345",
"qwerty", "abc123", "football", "1234567", "monkey"
])

def analyze_strength(self, password: str) -> Tuple[PasswordStrength, Dict[str,


any]]:
"""分析密码强度"""
score = 0
details = {
"length": len(password),
"has_lowercase": bool(re.search(r'[a-z]', password)),
"has_uppercase": bool(re.search(r'[A-Z]', password)),
"has_digits": bool(re.search(r'\d', password)),
"has_symbols": bool(re.search(r'[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]',
password)),
"has_patterns": self._check_patterns(password),
"is_common": password.lower() in self.common_passwords,
"entropy": self._calculate_entropy(password)
}

# 评分系统
if details["length"] >= 8:
score += 1
if details["length"] >= 12:
score += 1
if details["length"] >= 16:
score += 1

if details["has_lowercase"]:
score += 1
if details["has_uppercase"]:
score += 1
if details["has_digits"]:
score += 1
if details["has_symbols"]:
score += 2

if not details["has_patterns"]:
score += 1
if not details["is_common"]:
score += 1

if details["entropy"] > 50:


score += 1

# 转换为强度等级
if score <= 3:
strength = PasswordStrength.VERY_WEAK
elif score <= 5:
strength = PasswordStrength.WEAK
elif score <= 7:
strength = PasswordStrength.MEDIUM
elif score <= 9:
strength = PasswordStrength.STRONG
else:
strength = PasswordStrength.VERY_STRONG

details["score"] = score
return strength, details
def _check_patterns(self, password: str) -> bool:
"""检查是否包含常见模式"""
patterns = [
r'123', r'abc', r'qwe', r'asd', r'zxc', # 键盘序列
r'(.)\1{2,}', # 重复字符
r'1234', r'abcd' # 连续字符
]

for pattern in patterns:


if re.search(pattern, password.lower()):
return True
return False

def _calculate_entropy(self, password: str) -> float:


"""计算密码熵值"""
charset_size = 0
if re.search(r'[a-z]', password):
charset_size += 26
if re.search(r'[A-Z]', password):
charset_size += 26
if re.search(r'\d', password):
charset_size += 10
if re.search(r'[^a-zA-Z0-9]', password):
charset_size += 32

import math
if charset_size > 0:
return len(password) * math.log2(charset_size)
return 0

def demo_password_tools():
"""演示密码工具的使用"""
generator = PasswordGenerator()
analyzer = PasswordAnalyzer()

print("🔐 智能密码生成器和分析器")
print("=" * 50)

# 生成不同类型的密码
passwords = {
"标准密码": generator.generate_password(12),
"高强度密码": generator.generate_password(16, include_symbols=True),
"易读密码": generator.generate_password(12, exclude_similar=True,
pronounceable=True),
"密码短语": generator.generate_passphrase(4)
}

for name, pwd in passwords.items():


print(f"\n{name}: {pwd}")
strength, details = analyzer.analyze_strength(pwd)

# 显示强度
strength_colors = {
PasswordStrength.VERY_WEAK: "🔴",
PasswordStrength.WEAK: "🟠",
PasswordStrength.MEDIUM: "🟡",
PasswordStrength.STRONG: "🟢",
PasswordStrength.VERY_STRONG: "🟣"
}
print(f" 强度: {strength_colors[strength]} {strength.name}")
print(f" 评分: {details['score']}/10")
print(f" 熵值: {details['entropy']:.1f} bits")

# 显示建议
suggestions = []
if details['length'] < 12:
suggestions.append("增加密码长度")
if not details['has_symbols']:
suggestions.append("添加特殊符号")
if details['has_patterns']:
suggestions.append("避免常见模式")

if suggestions:
print(f" 建议: {', '.join(suggestions)}")

if __name__ == "__main__":
demo_password_tools()

You might also like