Python密码强度检查函数异常:"Secret999!"被误判为WEAK
问题分析
输入密码"Secret999!"时函数返回WEAK,核心问题是原代码对WEAK密码的第二个判断逻辑不符合规则:
- 规则(b)中WEAK的第二个条件是「英文单词后跟一个或多个数字」,要求密码结构是纯英文单词前缀 + 纯数字后缀,且后缀至少1位。
- 原代码仅检查「存在某个前缀子串是英文单词」且「密码包含数字」,完全忽略了后缀可能存在非数字字符的情况。对于"Secret999!",前缀"Secret"是英文单词、密码包含数字,但后缀有感叹号,不符合规则,却被错误判定为WEAK。
修正方案
修改WEAK密码的判断逻辑,严格验证「前缀为英文单词,后缀全为数字且长度≥1」;同时移除ILLEGAL判断中冗余的strip()(包含空格的情况已单独判断)。
修正后的代码:
def password_strength(password): # 检查是否为ILLEGAL密码 if password.lower() in ENGLISH_WORDS or "\t" in password or "\n" in password or " " in password: return "ILLEGAL" # 检查是否为WEAK密码 is_weak = False if len(password) < 8: is_weak = True else: # 遍历所有可能的分割点,验证前缀是英文单词、后缀全为数字且非空 for split_idx in range(1, len(password)): prefix = password[:split_idx].lower() suffix = password[split_idx:] if prefix in ENGLISH_WORDS and suffix.isdigit(): is_weak = True break if is_weak: return "WEAK" # 检查是否为STRONG密码 special_chars = "~`!@#$%^&*(){}[]|\\/:;\";<>.?" has_lower = any(c.islower() for c in password) has_upper = any(c.isupper() for c in password) has_digit = any(c.isdigit() for c in password) has_special = any(c in special_chars for c in password) if len(password) >= 12 and has_lower and has_upper and has_digit and has_special: return "STRONG" # 剩余情况为MEDIUM return "MEDIUM"
验证说明
- 输入"Secret999!":长度≥8,遍历所有分割点后,后缀包含感叹号无法满足「全为数字」,不触发WEAK条件;长度不足12,不满足STRONG条件,最终返回MEDIUM,符合预期。
- 输入"Secret123":分割点在6时,前缀"secret"是英文单词、后缀"123"全为数字,会被判定为WEAK,符合规则。
- 输入" secret ":包含空格,判定为ILLEGAL,符合规则。
内容的提问来源于stack exchange,提问作者Sebastian
相关产品推荐
相关产品推荐

