top of page

Password Generator (Python)

Updated: Oct 15, 2023


Image showing woman thinking of password.

In this blog:

Why write a password generator?

*Automation*

Writing your own password generator script is like having a tool in your technological toolkit and allows you to be less dependant on those weak passwords you think up when creating an account on a new website.


Having a script lets you automate this repetitive task.

Random or secrets?

The random module in Python lets you compose a pseudo-random sequence from a set of strings or an alphabet that you set.

What's not so good about this is that a pseudo-random string is deterministic.


This means if you set a random seed on your machine, this module will give the same string on your machine and for anyone else who is using the same seed.

In other words, the random module is a very effective tool to generate random sequences and assign random values to strings for cases that are not sensitive.

Image showing two dice thrown.

On the other hand, Python's secrets module allows for production of data that is as close to true randomness as possible.


The secrets module is a great source of cryptographically sound data that cannot be found out by determining the seed that was used to secure the data.

Image showing Python script.

Advantages of the secrets module over the random module include:


  • Secrets is able to generate cryptographically sound data.

  • Generate password tokens for password resets and temporary URLS.

  • Use functions such as choice(), randbits() and more.

Example ➡️

import secrets
import string
password = ''
numbers_letters = string.digits+string.ascii_letters
for i in range(10):
    password +=str(''.join(secrets.choice(numbers_letters)))

print(password)

What it does ➡️

  • The script above imports the secrets string modules.

  • Password is defined as a string with no characters so that we can add to it later.

  • the variable numbers_letters is used to hold the valued contained within the digits and ascii characters in their respective modules.

  • The for loop allows us to use a range (in this case 10) of characters from which the secrets.choice function picks its random characters and concatenates it to the empty string that is the passwords variable.

  • the script runs as soon as we execute with the print instruction.

Randbits()

Randbits allows you to create a random integer in the specified size (i), in bits.


  • If i=4, then the resulting integer is from 0-15.

  • If i=8, then the resulting integer is from 0-255.

  • If i=16, then the resulting integer is from 0-65,535.

This just goes on and on.

Example ➡️

#getrandbits == returns integer in the specified size (bits)
import random
print (random.getrandbits(64))

Output ➡️

13970237700045628873

Dissecting the script


Step 1 ➡️ Importing modules

We must first import all necessary modules ➡️


The script below imports the string and secrets modules.

import string
import secrets

Step 2 ➡️ Choosing Length

We can ask the user (or ourselves) to pick the length of the password as an integer.


The secrets module will then randomise its character selection from the value provided.


The script below takes input from the user as an integer to indicate the desired length of the password and stores it in the length variable.


length = int(input("Enter password length: "))

Step 3 ➡️ Choosing characters


The alphabet includes what characters we want in our password.

The string module allows us to insert characters.

ascii_letters 
#lets us use lower and uppercase characters. 

digits 
#lets us use a string of numbers from 0 to 9.

punctuation 
#lets us use special characters.

We can also ask the user to pick what characters they want in their password.


The script below simply prints out a list that the user can choose from to customise their password.


print('''Choose your character set for the password:
         1. Numbers
         2. Special characters
         3. Letters (Uppercase)
         4. Letters (lowercase)
         5. Save''')

Step 4 ➡️ Defining the alphabet


We can define variables using the string functions so that it's easier to just call them later on in the script.

The script below saves the characters variable with speech marks so that we get no whitespace between characters.


The string functions are saved as variables that are easier to understand and type later.

characters = ""
upperLetters = string.ascii_uppercase
lowerLetters = string.ascii_lowercase
numbers = string.digits
specialChars = string.punctuation

Step 5 ➡️ Getting character set from user

We can use a while loop with nested if statements to loop through the script for as long as possible.

The script below shows the while loop which sets the Boolean for the nested if statements below.

The choice variable asks the user to pick a number. This is a number from the options given above to choose character types.

The if statements append whatever characters that were chosen by the user until number 5 (save) option is selected, which breaks the loop.

If a number outside of the options is selected, an error message is printed.

while True:
    choice = int(input("Pick a number "))

    if choice == 1:
        characters += numbers

    elif choice == 2:
        characters += specialChars

    elif choice == 3:
        characters += upperLetters

    elif choice == 4:
        characters += lowerLetters

    elif choice == 5:
        break

    else:
        print("Pick from the options given!")

Step 6 ➡️ Getting character set from user


The script below creates an empty list variable called password.


The for loop iterates through the value denoted by the user (and stored in the length variable above) and randomly picks characters up to that value stored in length.

This method uses the secrets module which is a more secure version of the random module.

The characters are stored in the result variable.

The password list is then appended with the results.

We can then print the password with the print statement below. The password is printed as a string using "".join as otherwise Python will throw an error saying there are numbers in the string.

password = []
for i in range(length):

    result = secrets.choice(characters)

    password.append(result)

print("Your password is " + "".join(password))

Full script ➡️

# Import required modules
import string
import secrets

# Getting password length
length = int(input("Enter password length: "))

# Choosing characters for password
print('''Choose your character set for the password:
         1. Numbers
         2. Special characters
         3. Letters (Uppercase)
         4. Letters (lowercase)
         5. Save''')


# Defining alphabet
characters = ""
upperLetters = string.ascii_uppercase
lowerLetters = string.ascii_lowercase
numbers = string.digits
specialChars = string.punctuation


# Getting character set for password
while True:
    choice = int(input("Pick a number "))

    if choice == 1:
        # Add numbers if choice is 1
        characters += numbers

    elif choice == 2:
        # Add special characters if choice is 2
        characters += specialChars

    elif choice == 3:
        # Add Upper case letters if choice is 3
        characters += upperLetters

    elif choice == 4:
        # Add Lower case letters if choice is 4
        characters += lowerLetters

    elif choice == 5:
        break
        # Break the loop if choice is 5

    else:
        # Print error message if choice not in options
        print("Pick from the options given!")


# Define empty list named password
password = []
for i in range(length):
    # Picking random character from our list
    # and storing it in the 'result' variable
    result = secrets.choice(characters)

    # Appending the random character to password
    password.append(result)

# Printing password as a string
print("Your password is " + "".join(password))

The end

This was a very simple password generator and will produce secure passwords quickly whenever you need one on the interwebs.


You can add much more to your script and make it as complex as you like, with more options.


If you want to add constraints that would end the generator prematurely on meeting, visit Geekflare's tutorial here.


Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
  • GitHub
  • Twitter
  • LinkedIn
bottom of page