regex - 如何编写 python 密码验证器
问题描述
我无法让程序检查具有“强密码”的所有因素,而不必制作十亿个 if 语句。
我正在尝试制作一个密码强度程序,其中密码必须具有:
- 至少 10 个字符
- 是混合大小写
- 至少一个数字
- 来自 "!@#$%^&*" 的有效特殊字符
代码:
import re
def passwordChecker(password):
tooShort = "Your password is too short, it must be at least 10 characters"
noNum = "Your password does not have a number. Please add at least one number."
notMixed = "Your password is not mixed case. Please choose a password with mixed case."
noSpec = "Your password does not have a valid special character. Please add at least one valid special character."
if len(password) >= 10 and re.search(r'[0-9]', password) and re.search(r'[A-Z]', password) \
and re.search(r'[a-z]', password) and re.search(r'[$!@%^&*#]', password):
print("Your password is valid")
elif len(password) < 10:
print(tooShort, "\n" +str(noNum), "\n" + str(notMixed), "\n" + str(noSpec))
elif len(password) >= 10 and re.search(r'[A-Z]', password) and re.search(r'[a-z]', password):
print(noNum, "\n" + str(noSpec))
elif len(password) >= 10 and re.search(r'[$!@%^&*#]', password):
print(notMixed, "\n" + str(noNum))
password = str(input("Enter a password: "))
passwordChecker(password)
虽然它有效,但我需要找出一个更好的系统,它更……健壮,我猜?使用正则表达式不是必须的,这只是我最终这样做的方式。
解决方案
(?=.{10,})(?=.*[A-Z].*)(?=.*[a-z].*)(?=.*\d.*)(?=.*[\!\@\#\$\%\^\&\*].*)(?=^[\!\@\#\$\%\^\&\*a-zA-Z0-9]+$)^.*$
应该满足您的每一个需求,并且也很容易修改。
(?=.{10,})
确保至少 10 个字符。(?=.*[A-Z].*)
检查至少 1 个大写字母。(?=.*[a-z].*)
检查至少 1 个小写字母。(?=.*\d.*)
检查至少 1 位数字。(?=.*[\!\@\#\$\%\^\&\*].*)
从您的列表中查找至少 1 个符号。(?=^[\!\@\#\$\%\^\&\*a-zA-Z0-9]+$)
确保没有符号出现在您的列表中。^.*$
要匹配的实际密码。
如果您不想要这些规则中的一个或多个,只需删除包含它们的肯定前瞻。
编辑:这是一个实现密码检查器的示例 python 程序。
import re
#loop forever
while(1==1):
#get a password
pword = input("password to test: ")
#test it against the conditions
if(re.match(
"(?=.{10,})" +
"(?=.*[A-Z].*)" +
"(?=.*[a-z].*)" +
"(?=.*\d.*)" +
"(?=.*[\!\@\#\$\%\^\&\*].*)(?=^[\!\@\#\$\%\^\&\*a-zA-Z0-9]+$)" +
"^.*$", pword)
):
#match: good password
print("good")
else:
#failed one of the conditions: bad password
print("bad")
推荐阅读
- javascript - 加载多个启动画面/超时加载屏幕反应本机博览会
- web - www 和非 www 域有不同的 SOP 吗?
- string - 在字符串匹配条件下无法终止 Ansible playbook
- javascript - 无法在浏览器中加载 WASM
- javascript - 使用 Java Script 对角线来回移动元素
- javascript - 如何将服务器中每个用户的 id 放入数组中?(Discord.js v12)
- php - 无法找到 [Laravel\Passport\Client] 的工厂
- python - 基于另一个 numpy 数组的 argmax 切片一个 numpy 数组
- phpstorm - 如何在 PhpStorm 中快速使用 USE 上课?
- c - 如何在数组中添加json对象?