首页 > 解决方案 > 如何编写 python 密码验证器

问题描述

我无法让程序检查具有“强密码”的所有因素,而不必制作十亿个 if 语句。

我正在尝试制作一个密码强度程序,其中密码必须具有:

  1. 至少 10 个字符
  2. 是混合大小写
  3. 至少一个数字
  4. 来自 "!@#$%^&*" 的有效特殊字符

代码:

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)

虽然它有效,但我需要找出一个更好的系统,它更……健壮,我猜?使用正则表达式不是必须的,这只是我最终这样做的方式。

标签: regexpython-3.xloopsif-statementpasswords

解决方案


(?=.{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")

演示在这里!


推荐阅读