Skip to main content
 首页 » 编程设计

python之在 Python 中测试密码的强度

2025年05月04日20cloudgamer

如果满足以下条件,则字符串是弱密码: 或者,它的长度少于 8 个字符, 或者,它是一个英文单词,函数 is_english_word( ) 为真。

如果满足以下条件,则字符串是强密码: 它包含至少 11 个字符 AND 它包含至少 1 个小写字母 并且它包含至少 1 个大写字母 并且它包含至少 1 个数字。

如果字符串不是弱密码且不是强密码,则它是中等密码。

def is_english_word( string ): 
    with open("english_words.txt") as f: 
        word_list = [] 
        for line in f.readlines(): 
            word_list.append(line.strip()) 
        if string in word_list:  
            return True 
        elif string == string.upper() and string.lower() in word_list: 
            return True 
        elif string == string.title() and string.lower() in word_list: 
            return True 
        else: 
            return False 
 
def password_strength( string ): 
    lower = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] 
    upper = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] 
    for item in string: 
        if item in lower: 
            string = string.replace(item, "x") 
        elif item in upper: 
            string = string.replace(item, "y") 
        elif item.isnumeric(): 
            string = string.replace(item, "n")       
    for item in string:         
        if len( string ) < 8 or is_english_word( string ) : 
            return 'WEAK' 
        elif len( string ) >= 11 and string.count("x") >= 1 and string.count("y") >= 1 and string.count("n") >= 1:  
            return 'STRONG' 
        else: 
            return 'MEDIUM' 
 
print( password_strength( 'Unimaginatively' ) ) 

这个密码应该是“WEAK”,但输出是“MEDIUM”,我不知道我的代码有什么问题。非常感谢。

请您参考如下方法:

你的代码有很多问题;值得注意的是,您要用 x 替换小写字符,用 y 替换大写字符,用 n 替换数字,在调用 is_english_word - 这意味着 is_english_word() 将使用 'Xyyyyyyyyyyyyyy' 调用,这不是英文单词。这使您的密码不是 'WEAK'。

因为它也不是'STRONG',所以它最终是'MEDIUM'。

作为记录,这里是一个正确的代码示例,可以执行您想要的操作:

import string 
def password_strength(string): 
    if len(string) < 8 or is_english_word(string): 
        return 'WEAK' 
    elif (len(string) > 11 and  
            any(ch in string.ascii_lowercase for ch in string) and 
            any(ch in string.ascii_uppercase for ch in string) and 
            any(ch.isdigit() for ch in string)): 
        return 'STRONG' 
    else: 
        return 'MEDIUM'