Python中的密码验证
让我们将密码作为字母数字字符和特殊字符的组合,并在几个条件的帮助下检查密码是否有效。
有效密码的条件是:
- 应该至少有一个数字。
- 应该至少有一个大写和一个小写字符。
- 应该至少有一个特殊符号。
- 长度应在 6 到 20 个字符之间。
Input : Geek12#
Output : Password is valid.
Input : asd123
Output : Invalid Password !!
我们可以使用多种方式检查给定字符串是否有资格成为密码。
方法#1:朴素方法(不使用正则表达式)。
# Password validation in Python
# using naive method
# Function to validate the password
def password_check(passwd):
SpecialSym =['$', '@', '#', '%']
val = True
if len(passwd) < 6:
print('length should be at least 6')
val = False
if len(passwd) > 20:
print('length should be not be greater than 8')
val = False
if not any(char.isdigit() for char in passwd):
print('Password should have at least one numeral')
val = False
if not any(char.isupper() for char in passwd):
print('Password should have at least one uppercase letter')
val = False
if not any(char.islower() for char in passwd):
print('Password should have at least one lowercase letter')
val = False
if not any(char in SpecialSym for char in passwd):
print('Password should have at least one of the symbols $@#')
val = False
if val:
return val
# Main method
def main():
passwd = 'Geek12@'
if (password_check(passwd)):
print("Password is valid")
else:
print("Invalid Password !!")
# Driver Code
if __name__ == '__main__':
main()
输出:
Password is valid
此代码使用布尔函数来检查是否满足所有条件。我们看到虽然代码的复杂性是基本的,但长度是相当大的。方法#2:使用正则表达式
Regex 模块的compile()
方法生成一个 Regex 对象,从而可以在pat变量上执行 regex 函数。然后我们检查pat定义的模式是否后跟输入字符串passwd 。如果是这样,则搜索方法返回true ,这将允许密码有效。
# importing re library
import re
def main():
passwd = 'Geek12@'
reg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!#%*?&]{6,20}$"
# compiling regex
pat = re.compile(reg)
# searching regex
mat = re.search(pat, passwd)
# validating conditions
if mat:
print("Password is valid.")
else:
print("Password invalid !!")
# Driver Code
if __name__ == '__main__':
main()
输出:
Password is valid.