Primeiro gerador de senha em Python

Sep 10 2020

Este é meu primeiro projeto usando Python. Fiz um gerador de senha simples que verifica a entrada do usuário. Como posso melhorar?

import random
def password_generator():
    password = []
    letters = ["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"]
    password_length = 0
    password_numbers = []
    password_letters = []
    # Input the length of the password
    while True:
        password_length_input = input("Choose the length of your password with numbers between 6 and 15:\n")
        if not password_length_input.isnumeric():
            print(f"{password_length_input} is not a number, try again:")
            continue
        else:
            password_length = int(password_length_input)
            print(f"Password length: {password_length}")
        if 6 <= password_length <= 15:
            break
        else:
            print("The password must be between 6 and 15 characters, try again:")
            continue
    # Input the amount of numbers in password
    while True:
        password_numbers_input = \
            input(f"Choose the amount of numbers you want in your password, max {password_length}\n")
        if not password_numbers_input.isnumeric():
            print(f"{password_numbers_input} is not a number try again")
            continue
        elif int(password_numbers_input) > password_length:
            password_numbers = 0
            print(f"The value is too high, choose maximum {password_length} numbers")
            continue
        else:
            password_numbers = int(password_numbers_input)
            print(f"Password numbers: {password_numbers}")
            for number in range(0,password_numbers):
                password.append(random.randrange(0,9))
            break
    # Check for numbers and letters in password
    while True:
        if password_numbers == password_length:
            print(f"The password will be only {password_numbers} numbers, no letters.")
            break
        else:
            password_letters = password_length - password_numbers
            print(f"""Your password will be {password_length} characters with {password_numbers} numbers and {password_letters} letters.""")
            for letter in range(0,password_letters):
                password.append(random.choice(letters))
            break
    random.shuffle(password)
    password_string = ''.join([str(item) for item in password])
    print(f"Your password is:\n{password_string}")

password_generator()

Exemplo de uso:

Choose the length of your password with numbers between 6 and 15:
Password length: 8
Choose the amount of numbers you want in your password, max 8
Password numbers: 2
Your password will be 8 characters with 2 numbers and 6 letters.
Your password is:
pzc11bmf

Respostas

9 benrg Sep 10 2020 at 22:06
letters = ["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"]

Este método de escrever o alfabeto é muito sujeito a erros. Gostaria de importar stringe usar string.ascii_lowercaseno lugar de letters. Se você quiser gerar sua própria gama de letras por qualquer motivo, eu escreveria

letters = [chr(n) for n in range(ord('a'), ord('z') + 1)]

uma vez que não há perigo de omitir ou duplicar uma carta.


password_length = 0
password_numbers = []
password_letters = []

Esses valores padrão nunca são usados. Os padrões para password_numberse password_lettersnão fazem sentido, pois essas variáveis ​​contêm números. Gostaria de deletar todas as três linhas.


if not password_length_input.isnumeric():
    print(f"{password_length_input} is not a number, try again:")
    continue
else:
    password_length = int(password_length_input)
    print(f"Password length: {password_length}")

Eu preferiria escrever

try:
    password_length = int(password_length_input)
except ValueError:
    print(f"{password_length_input} is not a number, try again:")
    continue
print(f"Password length: {password_length}")

while True:
    if password_numbers == password_length:
        ...
        break
    else:
        ...
        break

Não há sentido em ter um whileloop aqui, já que você sempre sai dele na primeira iteração.


range(0,password_numbers)

Você pode apenas escrever range(password_numbers).


password.append(random.randrange(0,9))

Isso acrescentará um dígito de 0 a 8 inclusive, nunca 9. Se você quiser todos os dez dígitos, deverá escrever random.randrange(10). Ou, talvez melhor, use random.choice(string.digits).


password_string = ''.join([str(item) for item in password])

Se você usar string.digits, cada elemento de passwordserá um caractere, portanto, você pode simplificar isso para password_string = ''.join(password).

6 Anonymous Sep 10 2020 at 20:31

Uma maneira mais direta de gerar uma string aleatória:

import random
import string

    def get_random_string(length):
        letters = string.ascii_lowercase
        result_str = ''.join(random.choice(letters) for i in range(length))
        print("Random string of length", length, "is:", result_str)
    
    get_random_string(8)
    get_random_string(8)
    get_random_string(6)

emprestado a partir daqui , e há mais exemplos.

Agora, se você tiver requisitos específicos, como um número mínimo de dígitos, pode ajustar a fórmula ou gerar duas listas e mesclá-las enquanto embaralha os valores.

Há um exemplo no link que citei acima: "Gerar uma string alfanumérica aleatória com uma contagem fixa de letras e dígitos" => mesclando duas compreensões de lista.

A maneira como você está fazendo isso é processual, mas não Pythônica. É meio que reinventar a roda.

No mínimo, sua lista de caracteres permitidos deve ser semelhante a esta:

letters = "abcdefghijklmnopqrstuvwxyz"

Em seguida, você escolhe uma letra aleatória, por exemplo letters[3], retornará 'd', pois a lista é baseada em 0 e o Python trata strings como sequências de caracteres. Usando o shuffle como você já está fazendo, você pode escrever um código mais conciso.

3 K.Oleksy Sep 10 2020 at 19:19

Primeiro

Eu sugiro criar métodos separados para cada loop while.

Segundo

O loop "while True" não é uma boa prática, eu acho. Em vez disso, use a condição.

Terceiro

Eu sugiro criar a classe PasswordGenerator que conterá seu código. Isso o ajudará a expandir seu código no futuro.

Estrutura básica para seu projeto

 class PasswordGenerator():
     
    check_declared_password_length():
        ...
        
    check_amount_of_password_numbers():
        ...
    *
    *
    *

Para o fim, lembre-se de criar funções com uma responsabilidade. Depois disso, você pode escrever testes de unidade para cada um deles e será mais fácil.