密码验证 - Python

7

我需要创建一个代码来验证密码是否符合以下条件:

  • 至少有8个字符
  • 至少包含1个数字
  • 至少包含1个大写字母

下面是代码:

def validate():
    while True:
        password = input("Enter a password: ")
        if len(password) < 8:
            print("Make sure your password is at lest 8 letters")
        elif not password.isdigit():
            print("Make sure your password has a number in it")
        elif not password.isupper(): 
            print("Make sure your password has a capital letter in it")
        else:
            print("Your password seems fine")
            break

validate()

我不确定问题出在哪里,但当我输入一个包含数字的密码时,它一直告诉我需要一个带有数字的密码。有什么解决方案吗?


可能是重复的问题,参考检查字符串是否包含数字 - Sayse
可能是重复的问题:检查密码强度(如何检查条件) - iFlo
14个回答

16
你可以使用 re 模块处理正则表达式。
使用它,你的代码会像这样:
import re

def validate():
    while True:
        password = raw_input("Enter a password: ")
        if len(password) < 8:
            print("Make sure your password is at lest 8 letters")
        elif re.search('[0-9]',password) is None:
            print("Make sure your password has a number in it")
        elif re.search('[A-Z]',password) is None: 
            print("Make sure your password has a capital letter in it")
        else:
            print("Your password seems fine")
            break

validate()

对于特殊字符,您可以添加以下代码:elif re.search('[^a-zA-Z0-9]',password) is None: print("请确保您的密码中包含特殊字符") - Albert

6
r_p = re.compile('^(?=\S{6,20}$)(?=.*?\d)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^A-Za-z\s0-9])')

这段代码将验证您的密码是否符合以下要求:

  1. 最小长度为6,最大长度为20
  2. 至少包含一个数字
  3. 至少包含一个大写字母和一个小写字母
  4. 至少包含一个特殊字符

5

password.isdigit() 不是检查密码中是否包含数字,而是根据以下内容检查所有字符:

str.isdigit():如果字符串中的所有字符都是数字且至少有一个字符,则返回True,否则返回False。

password.isupper() 不是检查密码中是否有大写字母,而是根据以下内容检查所有字符:

str.isupper():如果字符串中所有大小写字符都是大写字母且至少有一个大小写字符,则返回True,否则返回False。

解决方案,请查看检查字符串是否包含数字的问题和被接受的答案。

您可以自己构建hasNumbers()函数(从链接的问题复制):

def hasNumbers(inputString):
    return any(char.isdigit() for char in inputString)

还有一个hasUpper()函数:

def hasUpper(inputString):
    return any(char.isupper() for char in inputString)

“isupper”检查密码中的所有字符是否都是大写字母。例如:“HELLO WORLD !!”.isupper()返回True。它检查至少有一个大写字母,并且没有小写字母。 - Jean-François Fabre

2

例子:

class Password:
    def __init__(self, password):
        self.password = password

    def validate(self):        
        vals = {
        'Password must contain an uppercase letter.': lambda s: any(x.isupper() for x in s),
        'Password must contain a lowercase letter.': lambda s: any(x.islower() for x in s),
        'Password must contain a digit.': lambda s: any(x.isdigit() for x in s),
        'Password must be at least 8 characters.': lambda s: len(s) >= 8,
        'Password cannot contain white spaces.': lambda s: not any(x.isspace() for x in s)            
        } 
        valid = True  
        for n, val in vals.items():                         
           if not val(self.password):                   
               valid = False
               return n
        return valid                

    def compare(self, password2):
        if self.password == password2:
            return True


if __name__ == '__main__':
    input_password = input('Insert Password: ')
    input_password2 = input('Repeat Password: ')
    p = Password(input_password)
    if p.validate() is True:
        if p.compare(input_password2) is True:
            print('OK')
    else:
       print(p.validate())

1

使用常规方法进行最简单的Python验证

password = '-'

while True:
    password = input(' enter the passwword : ')
    lenght = len(password)

    while lenght < 6:
        password = input('invalid , so type again : ')

        if len(password)>6:
            break

    while not any(ele.isnumeric() for ele in password):
        password = input('invalid , so type again : ')
    while not any(ele.isupper() for ele in password):
        password = input('invalid , so type again : ')
    while not any(ele not in "[@_!#$%^&*()<>?/|}{~:]" for ele in password):
        password = input('invalid , so type again : ')
    break

1
您正在对整个密码字符串对象进行isdigit和isupper方法的检查,而不是对字符串的每个字符进行检查。以下是一个函数,用于检查密码是否符合您的特定要求。它不使用任何正则表达式。它还打印出输入密码的所有缺陷。
#!/usr/bin/python3
def passwd_check(passwd):
    """Check if the password is valid.

    This function checks the following conditions
    if its length is greater than 6 and less than 8
    if it has at least one uppercase letter
    if it has at least one lowercase letter
    if it has at least one numeral
    if it has any of the required special symbols
    """
    SpecialSym=['$','@','#']
    return_val=True
    if len(passwd) < 6:
        print('the length of password should be at least 6 char long')
        return_val=False
    if len(passwd) > 8:
        print('the length of password should be not be greater than 8')
        return_val=False
    if not any(char.isdigit() for char in passwd):
        print('the password should have at least one numeral')
        return_val=False
    if not any(char.isupper() for char in passwd):
        print('the password should have at least one uppercase letter')
        return_val=False
    if not any(char.islower() for char in passwd):
        print('the password should have at least one lowercase letter')
        return_val=False
    if not any(char in SpecialSym for char in passwd):
        print('the password should have at least one of the symbols $@#')
        return_val=False
    if return_val:
        print('Ok')
    return return_val

print(passwd_check.__doc__)
passwd = input('enter the password : ')
print(passwd_check(passwd))

1
使用 return_val 不符合 Python 的风格。如果不合法,只需返回 False;如果合法,则返回 True。 - woodpav

1

当然,使用正则表达式可能有更简单的答案,但这是其中最简单的方法之一。

from string import punctuation as p
s = 'Vishwasrocks@23' #or user input is welcome
lis = [0, 0, 0, 0]
for i in s:
    if i.isupper():
        lis[0] = 1
    elif i.islower():
        lis[1] = 1
    elif i in p:
        lis[2] = 1
    elif i.isdigit():
        lis[3] = 1
print('Valid') if 0 not in lis and len(s) > 8 else print('Invalid')

1
''' Minimum length is 5;
 - Maximum length is 10;
 - Should contain at least one number;
 - Should contain at least one special character (such as &, +, @, $, #, %, etc.);
 - Should not contain spaces.
'''

import string

def checkPassword(inputStr):
    if not len(inputStr):
        print("Empty string was entered!")
        exit(0)

    else:
        print("Input:","\"",inputStr,"\"")

    if len(inputStr) < 5 or len(inputStr) > 10:
        return False

    countLetters = 0
    countDigits = 0
    countSpec = 0
    countWS = 0

    for i in inputStr:
        if i in string.ascii_uppercase or i in string.ascii_lowercase:
             countLetters += 1
        if i in string.digits:
            countDigits += 1
        if i in string.punctuation:
            countSpec += 1
        if i in string.whitespace:
            countWS += 1

    if not countLetters:
        return False
    elif not countDigits:
        return False
    elif not countSpec:
        return False
    elif countWS:
        return False
    else:
        return True


print("Output: ",checkPassword(input()))

使用正则表达式
s = input("INPUT: ")
print("{}\n{}".format(s, 5 <= len(s) <= 10 and any(l in "0123456789" for l in s) and any(l in "!\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~" for l in s) and not " " in s))

模块导入
from string import digits, punctuation

def validate_password(p):
    if not 5 <= len(p) <= 10:
        return False

    if not any(c in digits for c in p):
        return False

    if not any(c in punctuation for c in p):
        return False

    if ' ' in p:
        return False

    return True

for p in ('DJjkdklkl', 'John Doe'
, '$kldfjfd9'):
    print(p, ': ', ('invalid', 'valid')[validate_password(p)], sep='')

0

你需要使用any内置函数

  • any([x.isdigit() for x in password]) 如果password中至少有一个数字,将返回True。
  • any([x.isupper() for x in password]) 如果password中至少有一个字符被视为大写,则返回True。

0
uppercase_letter = ['A', 'B','C', 'D','E','F','G','H','I','J','K','L','M','N','O',
            'P','Q','R','S','T','U','V','W','X','Y','Z']

number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

import re

info ={}

while True:

    user_name = input('write your username: ')

    if len(user_name) > 15:
        print('username is too long(must be less than 16 character)')
    elif len(user_name) < 3 :
        print('username is short(must be more than 2 character)')
    else:
        print('your username is', user_name)
        break


while True:   

    password= input('write your password: ')

    if len(password) < 8 :
        print('password is short(must be more than 7 character)')

    elif len(password) > 20:
        print('password is too long(must be less than 21 character)') 

    elif re.search(str(uppercase_letter), password ) is None :
        print('Make sure your password has at least one uppercase letter in it')

    elif re.search(str(number), password) is None :
        print('Make sure your password has at least number in it')

    else:
        print('your password is', password)
        break

info['user name'] = user_name

info['password'] = password

print(info)

你能解释一下你的代码如何回答这个问题以及为什么吗? - Michael Heil
@mike 首先,如果你认为我的代码有用,请点击向上箭头: ),而且我的代码易读性很高,如果你有问题,请告诉我 :) - ehsanb159

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接