Python проблема с генератором паролей в соответствии с требованиями пользователя - PullRequest
0 голосов
/ 11 апреля 2020

Я пытаюсь написать генератор паролей, который генерирует пароли в соответствии с требованиями пользователя. Если пользователь вводит более двух раз, то да. Это не всегда работает. Не все требования будут в пароле, который создает функция. Я хотел бы знать, как решить эту проблему и получить объяснение.

from random import randint
from secrets import choice
    def PasswordGenerator():
        print("Welcome to Password Generator\nYou can create a password with capital letters, lowercase letters, numbers, and special characters.\nDuring the password creation process, we will ask you which password you want.\n")
        while True:
            try:
                length = int(input("Please enter the length of the password you want to create:\nNote: The minimum length is 8 characters And enter Only integers\n"))
                while length < 8:
                    print("The minimum password length is 8 characters, please enter a valid integer number ")
                    length = int(input("Enter the length of the password you want to create:\n"))
                password_uppercase = input("Answer only with yes or no.\nDo you want upper case? \n")
                while password_uppercase != "yes" and password_uppercase != "YES" and password_uppercase != "no" and password_uppercase != "NO":
                    password_uppercase = input("Answer only with yes or no.\nDo you want upper case? \n")
                password_lowercase = input("Answer only with yes or no.\nDo you want lower case?\n")
                while password_lowercase != "yes" and password_lowercase != "YES" and password_lowercase != "no" and password_lowercase != "NO":
                    password_lowercase = input("Answer only with yes or no.\nDo you want lower case?\n")
                password_numbers = input("Answer only with yes or no.\nDo you want numbers?\n")
                while password_numbers != "yes" and password_numbers != "YES" and password_numbers != "no" and password_numbers != "NO":
                    password_numbers = input("Answer only with yes or no.\nDo you want numbers?\n")
                password_special = input("Answer only with yes or no.\nDo you want Special symbols?\n")
                while password_special != "yes" and password_special != "YES" and password_special != "no" and password_special != "NO":
                    password_special = input("Answer only with yes or no.\nDo you want Special symbols?\n")
            except ValueError:
                print("Enter Only integers")
            except:
                print("Oops you got an error! Please enter a VALID value")
            else:
                alphabet = ''
                if password_numbers == "yes":
                    alphabet += "0123456789"
                elif password_numbers == "YES":
                    alphabet += "0123456789"
                if password_uppercase == "yes":
                    alphabet += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                elif password_uppercase == "YES":
                    alphabet += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                if password_lowercase == "yes":
                    alphabet += "abcdefghijklmnopqrstuvwxyz"
                elif password_lowercase == "YES":
                    alphabet += "abcdefghijklmnopqrstuvwxyz"
                if password_special == "yes":
                    alphabet += "!#$%&'()*+,-./:;<=>?@[\]^_`{|}~"
                elif password_special == "YES":
                    alphabet += "!#$%&'()*+,-./:;<=>?@[\]^_`{|}~"
                password = "".join(choice(alphabet) for x in range(randint(length, length)))
                return password
                break

1 Ответ

1 голос
/ 11 апреля 2020

Поскольку вы создаете полный алфавит и случайным образом выбираете из него символы, это не гарантирует, что будет выбран хотя бы один из каждой группы (число, заглавные буквы и т. Д. c.).

Вы можете исправить это, разделив группы по алфавиту. Затем выбирайте хотя бы по одному из каждого. В конце вы должны перемешать символы один раз, чтобы убедиться, что порядок в алфавитном списке потерян в генерируемом пароле.

import random

def PasswordGenerator():
    print("Welcome to Password Generator\nYou can create a password with capital letters, lowercase letters, numbers, and special characters.\nDuring the password creation process, we will ask you which password you want.\n")
    try:
        length = int(input("Please enter the length of the password you want to create:\nNote: The minimum length is 8 characters And enter Only integers\n"))
        while length < 8:
            print("The minimum password length is 8 characters, please enter a valid integer number ")
            length = int(input("Enter the length of the password you want to create:\n"))
        password_uppercase = input("Answer only with yes or no.\nDo you want upper case? \n")
        while password_uppercase != "yes" and password_uppercase != "YES" and password_uppercase != "no" and password_uppercase != "NO":
            password_uppercase = input("Answer only with yes or no.\nDo you want upper case? \n")
        password_lowercase = input("Answer only with yes or no.\nDo you want lower case?\n")
        while password_lowercase != "yes" and password_lowercase != "YES" and password_lowercase != "no" and password_lowercase != "NO":
            password_lowercase = input("Answer only with yes or no.\nDo you want lower case?\n")
        password_numbers = input("Answer only with yes or no.\nDo you want numbers?\n")
        while password_numbers != "yes" and password_numbers != "YES" and password_numbers != "no" and password_numbers != "NO":
            password_numbers = input("Answer only with yes or no.\nDo you want numbers?\n")
        password_special = input("Answer only with yes or no.\nDo you want Special symbols?\n")
        while password_special != "yes" and password_special != "YES" and password_special != "no" and password_special != "NO":
            password_special = input("Answer only with yes or no.\nDo you want Special symbols?\n")
    except ValueError:
        print("Enter Only integers")
    except:
        print("Oops you got an error! Please enter a VALID value")
    else:
        alphabets = []   # keep a list of alphabet groups 
        if password_numbers in ("yes", "YES"):
            alphabets.append("0123456789")  # include group
        if password_uppercase in ("yes", "YES"):
            alphabets.append("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
        if password_lowercase in ("yes", "YES"):
            alphabets.append("abcdefghijklmnopqrstuvwxyz")
        if password_special in ("yes", "YES"):
            alphabets.append("!#$%&'()*+,-./:;<=>?@[\\]^_`{|}~")
        password_chars = []  # construct the password as a list
        while len(password_chars) < length:  # keep choosing until length requirement is met
            for alphabet in alphabets:  # for each group
                password_chars.append(random.choice(alphabet)) # choose a character from the group
                if len(password_chars) > length:
                    break
        random.shuffle(password_chars) # shuffle to lose the order of groups from the generated list
        return "".join(password_chars)

print(PasswordGenerator())

Выход:

Welcome to Password Generator
You can create a password with capital letters, lowercase letters, numbers, and special characters.
During the password creation process, we will ask you which password you want.

Please enter the length of the password you want to create:
Note: The minimum length is 8 characters And enter Only integers
8
Answer only with yes or no.
Do you want upper case? 
yes
Answer only with yes or no.
Do you want lower case?
yes
Answer only with yes or no.
Do you want numbers?
yes
Answer only with yes or no.
Do you want Special symbols?
yes

OnWw0=]7
...