密码验证 - Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41117733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:27:47  来源:igfitidea点击:

Validation of a Password - Python

pythonvalidationpasswords

提问by HaViK

So I have to create code that validate whether a password:

所以我必须创建验证密码的代码:

  • Is at least 8 characters long
  • Contains at least 1 number
  • Contains at least 1 capital letter
  • 长度至少为 8 个字符
  • 包含至少 1 个数字
  • 包含至少 1 个大写字母

Here is the code:

这是代码:

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()

I'm not sure what is wrong, but when I enter a password that has a number - it keeps telling me that I need a password with a number in it. Any solutions?

我不确定出了什么问题,但是当我输入一个带有数字的密码时 - 它一直告诉我我需要一个带有数字的密码。任何解决方案?

回答by zipa

You can use remodule for regular expressions.

您可以将re模块用于正则表达式。

With it your code would look like this:

有了它,您的代码将如下所示:

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()

回答by MikeZhang

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

this code will validate your password with :

此代码将验证您的密码:

  1. min length is 6 and max length is 20
  2. at least include a digit number,
  3. at least a upcase and a lowcase letter
  4. at least a special characters
  1. 最小长度为 6,最大长度为 20
  2. 至少包括一个数字,
  3. 至少一个大写字母和一个小写字母
  4. 至少一个特殊字符

回答by Cleared

password.isdigit()does not check if the password contains a digit, it checks all the characters according to:

password.isdigit()不检查密码是否包含数字,它根据以下条件检查所有字符:

str.isdigit(): Return true if all characters in the string are digits and there is at least one character, false otherwise.

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

password.isupper()does not check if the password has a capital in it, it checks all the characters according to:

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

str.isupper(): Return true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise.

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

For a solution, please check the question and accepted answer atcheck if a string contains a number.

如需解决方案,请在检查字符串是否包含数字检查问题和接受的答案

You can build your own hasNumbers()-function (Copied from linked question):

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

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

and a hasUpper()-function:

hasUpper()- 功能:

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

回答by srinivasu u

You are checking isdigit and isupper methods on the entire password string object not on each character of the string. The following is a function which checks if the password meets your specific requirements. It does not use any regex stuff. It also prints all the defects of the entered password.

您正在检查整个密码字符串对象上的 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))

回答by user2557522

Python 2.7 The for loop will assign a condition number for each character. i.e. Pa$$w0rd in a list would = 1,2,4,4,2,3,2,2,5. Since sets only contains unique values, the set would = 1,2,3,4,5; therefore since all conditions are met the len of the set would = 5. if it was pa$$w the set would = 2,4 and len would = 2 therefore invalid

Python 2.7 for 循环将为每个字符分配一个条件编号。即列表中的 Pa$$w0rd = 1,2,4,4,2,3,2,2,5。由于集合仅包含唯一值,因此集合将 = 1,2,3,4,5;因此,由于满足所有条件,集合的 len 将 = 5。如果是 pa$$w,则集合将 = 2,4,len 将 = 2 因此无效

name = raw_input("Enter a Password: ")
list_pass=set()
special_char=['#','$','@']
for i in name:
    if(i.isupper()):
      list_pass.add('1')
  elif (i.islower()):
      list_pass.add('2')
  elif(i.isdigit()) :
      list_pass.add('3')
  elif(i in special_char):
      list_pass.add('4')
if len(name) >=6 and len(name) <=12:
    list_pass.add('5')
if len(list_pass) is 5:
    print ("Password valid")
else: print("Password invalid")

回答by Nons

''' 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()))

With Regex

使用正则表达式

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))

Module import

模块导入

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='')

回答by Xavi Martínez

Example:

例子:

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())

回答by ehsanb159

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)

回答by Maxime Lorant

What you need is using the anybuilt-in function:

您需要的是使用any内置函数

  • any([x.isdigit() for x in password])will return True if at least one digit is present in password
  • any([x.isupper() for x in password])will return True if at least one character is considered as uppercase.
  • any([x.isdigit() for x in password])如果至少存在一位数字,则返回 True password
  • any([x.isupper() for x in password])如果至少一个字符被视为大写,则返回 True。

回答by Marcin ?wierczyna

Maybe you can use regex expression:

也许你可以使用正则表达式:

re.search(r"[A-Z]", password)

Check uppercase letters.

检查大写字母。

re.search(r"[0-9]", password)

Check digits in password.

检查密码中的数字。