Python 中的密碼驗證
一般來說,密碼需要適當複雜。在本文中,我們將討論如何驗證給定密碼是否滿足一定複雜性級別。我們將為此使用名為 re 的正則表示式模組。
示例 -1
首先,我們建立一個正則表示式,可以滿足將其稱為有效密碼所需的條件。然後,我們使用 re 的 search 函式將給定密碼與所需條件進行匹配。在以下示例中,複雜性要求是需要至少一個大寫字母、一個數字和一個特殊字元。我們還需要密碼長度在 8 到 18 之間。
示例
import re pswd = 'XdsE83&!' reg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!#%*?&]{8,18}$" # compiling regex match_re = re.compile(reg) # searching regex res = re.search(match_re, pswd) # validating conditions if res: print("Valid Password") else: print("Invalid Password")
輸出
執行上述程式碼,得到以下結果 −
Valid Password
示例 -2
在此示例中,我們使用不滿足所有所需條件的密碼。例如,密碼中沒有數字。在這種情況下,程式會將其指示為無效密碼。
示例
import re pswd = 'XdsEfg&!' reg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?& ])[A-Za-z\d@$!#%*?&]{8,18}$" # compiling regex match_re = re.compile(reg) # searching regex res = re.search(match_re, pswd) # validating conditions if res: print("Valid Password") else: print("Invalid Password")
輸出
執行上述程式碼,得到以下結果 −
Invalid Password
廣告