2014-11-09 82 views
0

我的代碼正在運行,但定義什麼使得強密碼的第一行代碼會導致代碼的其餘部分無效返回。例如,當第一行代碼正在搜索一個數字字符時,其中的任何代碼都會導致代碼在滿足要求時不打印消息。如果我從尋找一個數字,以尋找一個資本或小寫字符改變它,那麼任何編碼以後也不會,如果代碼需要尋找資金或小寫等功能re.search密碼檢查錯誤

import re 
password = str(input("Please enter the password you wish to test the strength of.\n")) 
if re.search(r'[0-9]', password): 
    if re.search(r'[A-Z]', password): 
     if re.search(r'[a-z]', password): 
      print("Your password strength is STRONG.") 
elif re.search(r'[a-z]', password) and re.search(r'[A-Z]', password): 
    print("Your password strength is MEDIUM.") 
elif re.search(r'[0-9]', password) and re.search(r'[A-Z]', password): 
    print("Your password strength is MEDIUM.") 
elif re.search(r'[a-z]', password) and re.search(r'[0-9]', password): 
    print("Your password strength is MEDIUM.") 
elif re.search(r'[A-Z]', password) or re.search(r'[a-z]', password) or re.search(r'[0-9]', password): 
    print("Your password strength is WEAK.") 
+0

密碼的長度是否會影響您在此處提供的強度等級? – shuttle87 2014-11-09 00:54:53

+0

如果密碼在6到12個字符之間,那麼只會測試強度。然而,長度並不影響力量,它只是它具有的字符。 – user3292752 2014-11-09 00:57:08

回答

0

,你就能把重構的東西這樣

import re 
strength = 0 
password = str(input("Please enter the password you wish to test the strength of.\n")) 
if re.search(r'[0-9]', password): 
    strength += 1 
if re.search(r'[A-Z]', password): 
    strength += 1 
if re.search(r'[a-z]', password): 
    strength += 1 

if strength == 3 
    print("Your password strength is STRONG.") 

if strength == 2: 
    print("Your password strength is MEDIUM.") 

if strength == 1: 
    print("Your password strength is WEAK.") 

雖然,我相信有更好的做這件事的方式,嘗試思考開箱:d

+0

如果我使用password.isupper或password.islower或password.isdigit,該方法是否可行? – user3292752 2014-11-09 00:59:03

+0

很可能不是,例如jez所說的「9gag」,會爲所有這些方法返回False。太糟糕了沒有hasupper,haslower或hasdigit方法 – 2014-11-09 01:04:10

1

按照通過使用密碼「9GAG」的代碼你自己的邏輯。在那裏有[0-9]但是不是[A-Z]。口譯員輸入第一個if,因此被排除在隨後的elifs之外,但它不會輸入嵌套的if,並且處於陷阱狀態。

這種方法可能會更容易:

hits = [ re.search(r'[0-9]', password) != None, re.search(r'[A-Z]', password) != None, re.search(r'[a-z]', password) != None ] 
strength = sum(hits) 
+0

現在這就是我所說的開箱即用的思想,bool在python上被當作一個int來處理,儘管對於剛剛學習的人來說它可能有點複雜。 – 2014-11-09 01:01:28

+0

是的。爲了澄清,那麼:每個術語're.search(pattern,passord)!= None'產生'真'(匹配)或'假'(不匹配)。在許多其他數值運算中,'sum'被視爲1,'False'被視爲0,所以例如sum([True,True,False])爲2。 – jez 2014-11-09 01:05:50

0

我曾經試圖執行一個更先進的密碼強度算法(包括香農熵和的修改),但最終我看到了,這是一個難以解決的問題,並且當密碼良好時不能真正說出。

你可能很容易確定的唯一的事情是密碼非常糟糕。

所以,也許只是教育用戶明智地選擇密碼或者在恰當的時候創建隨機密碼是最好的。

對密碼施加任意規則通常是相當煩人的。例如。如果有人使用密碼管理器生成隨機密碼,他們可能會違反規則,但仍然是好密碼,因爲它們是隨機的。