在Python中测试密码的强度



字符串是WEAK密码,如果:或者长度小于8个字符,或者,它是一个英语单词,即函数is_English_word((为True。

字符串是STRONG密码,如果:它至少包含11个字符AND至少包含1个小写字母且至少包含1个大写字母AND至少包含一个数字。

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

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",我不知道我的代码有什么问题。非常感谢。

您的代码存在许多问题;值得注意的是,在调用is_english_word之前,您将用x替换小写字符,用y替换大写字符,并用n替换数字,这意味着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'   

如果你考虑到使用字符串方法执行的相同操作(检查至少一个字符是否为真(对字母类型的3个限制,你可以显著简化你的代码:

def is_weak(word):
return len(word < 8 or is_english_word(word)
def is_strong(word):
return len(word) >= 11 and all(any(method(c) for c in word) 
for method in (str.islower, str.isupper, str.isdigit))
def password_strength(password):
if is_weak(password):
return 'WEAK'
elif is_strong(password):
return 'STRONG'
else:
return 'MEDIUM'

最新更新