Python Security Scripts

0_AIO_Python_Security

How to Program Your Own Password Generator With Python

Let´s find out how easy is to create a strong password generator with Python in a few lines

We are gonna take the original code from Zsecurity and we´ll optimize it a bit to handle user input.

I highly recommend Zsecurity if you want to deep into Ethical hacking, Security, Python programming and more.

Ok, back to the code, is something like this

"""
strong password generator
"""
#we import RANDINT to generate a random number between 2 given values
from random import randint

#we add some variables that will store our "dictionary"
#from which we´ll create the password
lowerCase = "abcdefghijklmnopqrstuvwxyz"
upperCase = lowerCase.upper()
numbers = "1234567890"
special = "!#$%&/()=?¡@[]_<>,."

#we add the variables to get a very strong password
password_creation = lowerCase + upperCase + numbers + special

#we ask the user to enter the password lenght
password_lenght = int(input("How many characters do you wish the password? Minimum 8 maximum 1024: "))
password = ""
lenght = 0

if password_lenght < 8 or password_lenght > 1024:
    print("Minimun 8 characters - maximum 1024, try again")
    
#here the magic happens to create the final password    
else:
    while lenght < password_lenght:#while password lenght does not reach the value entered by the user
        
#the password is created selecting a random (randint) value from password_creation
        password = password + password_creation[randint(0, len(password_creation) -1)]
        lenght +=1
    print("Generated password: ", password)#we show the result

If we run it we´ll be asked to enter the lenght we want the password to have (I entered 24)

How many characters do you wish the password? Minimum 8 maximum 1024: 24

Generated password: %5VcsbRU!B.k949h#w/kUZXG

Ok, it seems a secure password, maybe we can check how secure is

Kaspersky Password Checker

or here My1login

or you can choose anyone, it seems that it works.

Now we have a problem here

Just for having some boundaries, I asked the user to enter a number between 8 and 1024 (no need to limit, but a password less than 8 characters is no password and more than 1024 is maybe…a bit long, you can set your own limits editing the code)

But the problem is that there is NO user-input check…yet

Let´s run the code again an enter a value OUT of the input request, let´s say five characters

>>> %Run z_strong_password_gen.py
How many characters do you wish the password? Minimum 8 maximum 1024: 5

Minimun 8 characters - maximum 1024, try again

What happened here? Well, the program stopped because we just coded a message telling that the input was not valid, BUT we did nothing after that. So let´s fix it

There are SEVERAL ways to do it, from non-good practices (like “repeating yourself”) to a bit more advanced like creating a function to check user input.

Let´s pick up a medium-level one to make things easy

Goal: Request User Input Until Valid

What are we gonna use: try/except statements and If/break

If you don´t know what is this, you can read a nice intro to try-except (w3school)

Well, here the code again with some comments to understand it better

"""
strong password generator
"""
#we import RANDINT to generate a random number between 2 given values
from random import randint

#we add some variables that will store our "dictionary"
#from which we´ll create the password
lowerCase = "abcdefghijklmnopqrstuvwxyz"
upperCase = lowerCase.upper()
numbers = "1234567890"
special = "!#$%&/()=?¡@[]_<>,."

#we add the variables to get a very strong password
password_creation = lowerCase + upperCase + numbers + special

password = ""
lenght = 0
while True:
    try:
        password_lenght = int(input("How many characters do you wish the password? Minimum 8 maximum 100: "))
        if password_lenght < 8 or password_lenght > 100:
            print("Minimun 8 characters - maximum 100, try again")
    except ValueError:
        print ("Please enter a valid NUMBER...")
        continue
    else:
        while lenght < password_lenght:#while password lenght do not reach the value entered by user
        

            password = password + password_creation[randint(0, len(password_creation) -1)]
            lenght +=1
            
"""
the password is created by selecting a random (randint) value
from password_creation and iterating a number of times through
the password_creation. This times is the number entered by the user
so every time the loop runs, it picks a random character from
password_creation and add it to the string it is creating until it reaches the value entered by the user
"""
            
        print("Generated password: ", password)#we show the result   
   

Now let´s add some input validation to avoid “bad” input like non-digit values or numbers out of range

from random import randint

lowerCase = "abcdefghijklmnopqrstuvwxyz"
upperCase = lowerCase.upper()
numbers = "1234567890"
special = "!#$%&/()=?¡@[]_<>,."

password_creation = lowerCase + upperCase + numbers + special

while True:
    # pulled password and length in here to reset on each loop
    password = ""
    length = 0

    try:
        password_length = int(input("How many characters do you wish the password? Minimum 8 maximum 1024: "))
        if password_length < 8 or password_length > 1024:
            print("Minimun 8 characters - maximum 1024, try again")
            # add continue, to not try to create password, if validation fails
            continue
    except ValueError:
#this prevents user to enter non-numerical values
        print("Please enter a valid NUMBER...")
        continue
    else:
        while length < password_length:
            password = password + password_creation[randint(0, len(password_creation) - 1)]
            length += 1
        print("Generated password: ", password)

that was ok, but what about optimizing the code to make it smaller and more legible?

Let´s try it

from random import randint

lowerCase = "abcdefghijklmnopqrstuvwxyz"
upperCase = lowerCase.upper()
numbers = "1234567890"
special = "!#$%&/()=?¡@[]_<>,."

mega_pass = lowerCase+ upperCase + numbers + special

lenght = 0
password_lenght = 0
password = ""


while True:
    try:
        password_lenght = int(input("How many characters long do you want the password? (min 8 - max 100; \n"))
    
    except ValueError:#if user enters a non-numerical value it will ask again
        print("\nNumbers please...")
    
    if  password_lenght not in range (8, 101):#if the user enters a numerical value OUT of range it asks again

        print("\nEnter a digit between 8 and 100...")
        
    
    else:
        while lenght < password_lenght:
            password = password + mega_pass[randint(0, len(mega_pass) -1)]
            lenght +=1
        
        print("\nYou choose" , password_lenght , "characters long\n")
        print("Here is your PASSWORD:\n ", password)
        break#it just ends the program after one password deliver

Let´s test it

Enter a digit between 8 and 100…
How many characters long do you want the password? (min 8 – max 100;
0 -> it must be 8 or more

Enter a digit between 8 and 100…-> so it asks again
How many characters long do you want the password? (min 8 – max 100;
5000 -> is greater than 100, so it asks again

Enter a digit between 8 and 100…
How many characters long do you want the password? (min 8 – max 100;
74747gggg -> we enter digits AND characters

Numbers please…-> it detects them and ask again for just numbers

Enter a digit between 8 and 100…
How many characters long do you want the password? (min 8 – max 100;
80 -> is between 8 and 100

You choose 80 characters long

Here is your PASSWORD:-> so it calculates our password and shows it below
Q$lK=TjJ8lCSx=9_mqkcEXzuVt[W#.p9DrB.FtAexuAXE)z]5_GdhI)G[tV!$YI_NZIz<fRe!T(Fvlnv

That was nice! we could ask the user to enter some value between a given range, NON alphanumerical BUT only digits, check the input, ask again if the user failed to enter the right characters, and calculate the strong password

Resources to keep learning

Data Structures AWESOME Cheat Sheet here

Github Repositories to Learn Python

Leave a Reply

Your email address will not be published. Required fields are marked *