python判断密码强度_python实现密码强度校验
本文實例為大家分享了python實現密碼強度校驗的具體代碼,供大家參考,具體內容如下
一 校驗規則
規則1 密碼長度8位以上
規則2 密碼需包含數字
規則3 密碼需包含大小寫字母
規則4 密碼需包含特殊字符["+", "-", "*", "/", "_", "&", "%", ","]
規則5 校驗5次不通過則強制退出
二 文件操作
每次輸入的密碼都會保存到文本文件中
以下是python的代碼實現:
"""
作者:zhengzhihui
版本:7.0
日期:2019/7/13
功能:判斷密碼強度
2.0功能:循環和終止
3.0功能:將密碼保存到文本中
4.0功能:讀取文件,遍歷文件
5.0功能:定義PasswordTool類
6.0功能:定義FileTool類
7.0功能:密碼中增加大小寫字母和特殊字符["+", "-", "*", "/", "_", "&", "%", ","]
"""
import time as tm
class FileTool():
"""
文件工具類
"""
def __init__(self, filepath):
self.filepath = filepath
def write_to_file(self, content):
with open(self.filepath, "a") as f:
f.write(content)
def read_from_file(self):
with open(self.filepath, "r") as f:
content = f.readlines()
return content
class PasswordTool():
"""
密碼工具類
"""
def __init__(self, password):
self.password = password
self.strength_level = 0
def check_number_exist(self):
"""
判斷是否含數字
"""
has_number = False
for c in self.password:
if c.isnumeric():
has_number = True
break
return has_number
def check_letter_exist(self):
"""
判斷是否含字母
"""
has_upper_letter = False
has_lower_letter = False
for c in self.password:
if c.isupper():
has_upper_letter = True
elif c.islower():
has_lower_letter = True
has_both_letter = has_upper_letter and has_lower_letter
if has_both_letter:
break
return has_both_letter
def check_specialchar_exist(self):
"""
判斷是否包含特殊字符
"""
has_specialchar = False
specialchar_list = ["+", "-", "*", "/", "_", "&", "%", ","]
for c in self.password:
if c in specialchar_list:
has_specialchar = True
break
return has_specialchar
def process_password(self):
"""
判斷是否符合規則
"""
# 規則1:長度至少8位
if len(self.password) >= 8:
self.strength_level += 1
else:
print("密碼長度至少8位")
# 規則2:必須包含數字
if self.check_number_exist():
self.strength_level += 1
else:
print("密碼需要包含數字")
# 規則3:必須包含大小寫字母
if self.check_letter_exist():
self.strength_level += 1
else:
print("密碼需要包含大小寫字母")
# 規則4:需要包含特殊字符
if self.check_specialchar_exist():
self.strength_level += 1
else:
print("密碼需要包含至少一個特殊字符("+,-,*,/,_")")
def main():
"""
主函數
"""
try_times = 5
pwd_strength_dict = {0: "弱", 1: "較弱", 2: "中", 3: "強", 4: "超強"}
myfile = FileTool("password_7.0.txt")
while try_times > 0:
password = input("請輸入密碼: ")
mypwdtool = PasswordTool(password)
mypwdtool.process_password()
now_time = tm.strftime("%Y-%m-%d %H:%M:%S", tm.localtime())
myfile.write_to_file("日期:{} 密碼:{} 強度:{}{}
".format(now_time, password,
mypwdtool.strength_level, pwd_strength_dict[mypwdtool.strength_level]))
if mypwdtool.strength_level >= 4:
print("恭喜!密碼合格")
break
else:
print("密碼不合格")
try_times -= 1
print()
if try_times <= 0:
print("嘗試次數過多,密碼設置失敗!")
content = myfile.read_from_file()
print(content)
if __name__ == "__main__":
main()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持云海天教程。
總結
以上是生活随笔為你收集整理的python判断密码强度_python实现密码强度校验的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【学习笔记】网络层——网络层设备、移动I
- 下一篇: 【LeetCode笔记】剑指 Offer