python實現密碼強度校驗
阿新 • • 發佈:2020-03-20
本文例項為大家分享了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("日期:{} 密碼:{} 強度:{}{}\n".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()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。