English English French French Spanish Spanish German German
Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
Share on:

How to Create a Random Password Generator in Python

How-to-Create-a-Random-Password-Generator-in-Python
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

Learn to code a password generator in Python—to generate secure passwords—using the Python secrets module.

Python is a versatile programming language that you can use across applications in automation, web development, data analysis, and more.

You can use Python to automate real-world tasks such as monitoring websites, sending emails, and generating passwords. In this tutorial, you’ll learn how to create a secure and random password generator in Python.

Let’s get started…

3 Reasons Why You Should Code a Password Generator in Python

Random-Password-Generator

Have you ever felt tired of generating secure passwords and keeping track of them? Here’s why you should consider coding a password generator in Python.

1. Automate the Password Generation Process

On a typical day in your life, you’ll visit numerous websites – from e-commerce websites to learning and coding platforms. Most of the websites require you to log in with credentials. This is a repetitive task that you can automate using a Python script.

2. Generate Secure Passwords

Coming up with strong passwords that meet security constraints can be challenging; trivial passwords that are not strong are susceptible to security attacks.

python-password-generator

You can use Python to programmatically generate secure passwords. This lets you run the script to generate passwords as needed—without worrying about the password being secure.

3. Add a Practical Project to Your Portfolio

If you’re a beginner Python programmer, you should build projects to hone your skills and showcase your programming expertise through a portfolio.

In addition to a simple Python script, you can customize it further, and publish it as a PyPI package. You can also add a graphical user interface using libraries such as Tkinter, and much more!

This way, you can code your own password generator—to securely generate and manage your passwords—across the various sites.

The Random Module in Python: Is It Secure Enough?

Python random module also provides functions that let you sample from an alphabet and construct seemingly random sequences. The random module generates pseudo-random sequences. Let us parse what pseudo-randomness means.

The term pseudo-random signifies that even though the sequence may appear random, it actually is deterministic.

Therefore, if you set a random seed, then the random module will yield the same sequence on your machine, and for anyone who runs the same script with the same seed.

This is why you should not use random for applications where security is important, such as passwords.

So when can you use the random module?

For all applications that are not sensitive, you can use the random module. For example, there are three sets of question papers, A, B, and C in a class of 40 students. You would like to assign a particular set to each student at random.

2

In this case, you can use random.choice() inside a list comprehension expression, as shown below:

import random

papers = ['A','B','C']

q_list = [random.choice(papers) for i in range(40)]
print(q_list)
Sample output:
['A', 'A', 'B', 'B', 'B', 'B', 'B', 'C', 'B', 'A', 'C', 'C', 'B', 
'C', 'A', 'B', 'A', 'A', 'C', 'C', 'A', 'A', 'A', 'C', 'A', 'C', 
'A', 'C', 'B', 'B', 'B', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B']

📑 Key takeaway: For statistical simulations, you can use the random module; for sensitive applications, use the secrets module.

Python Secrets Module: Your Key to Secure Passwords

The Python Enhancement Proposal, PEP 506, advises developers to use the secrets module whenever a sequence should be cryptographically secure, such as passwords and security tokens.

python-secrets-password-generator

The secrets the module has several built-in functions that let you do the following:

  • Generate sequences of random numbers that are secure for cryptographic applications.
  • Use functions like choice(), randbits(), and randbelow() to generate secure random numbers.
  • Generate tokens for a password reset, temporary URLs, and more.

How to Code a Password Generator in Python [in 4 Steps]

Prerequisites: You need to have Python 3.6 or a later version installed to code along with this tutorial. You can also run the example code in Geekflare’s Online Python Code Editor.

Step 1: Import necessary modules

As a first step, let’s import the secrets module. This module is built into the Python standard library, so you can import it as follows:

import secrets

Let’s also import Python’s built-in string module:

import string

Step 2: Define the alphabet

The next step is to define the alphabet. Alphabet denotes the set of all characters that we’ll consider for password generation. Here, we want it to contain the following: lowercase and uppercase letters and special characters.

alphabet

The string module provides string constants that we can use to define the alphabet. We’ll use the following string constants:

  • The ascii_letters is a concatenation of letters lowercase and uppercase letters.
  • The digits constant is the string containing the numbers 0 to 9: '0123456789'.
  • The punctuation constant is the string of all special characters.
letters = string.ascii_letters
digits = string.digits
special_chars = string.punctuation

Finally, let’s concatenate the above string constants to get the alphabet.

alphabet = letters + digits + special_chars

Step 3: Fix the length of the password; Generate a password

Let’s store the length of the password in the variable, pwd_length. In this example, the password string is of length 12.

pwd_length = 12

▶️ Now, run the following code cell to generate a password:

pwd = ''
for i in range(pwd_length):
  pwd += ''.join(secrets.choice(alphabet))

print(pwd)
# Sample output
}2:Lz,1!Gvo@

The above code does the following:

  • The password string pwd is an empty string initially.
  • We know that secrets.choice(alphabet) returns one character, sampled at random from the alphabet.
  • We use the join() method to add this character to the pwd string. Because we do not want any whitespace between the characters, we specify the separator to be ''.
  • To repeat the above steps to generate a password, we use a loop that runs for as many iterations as the length of the password.

Step 4: Customize Your Passwords Based on Constraints

You can customize the password generation by checking if it meets certain constraints.

For example, let’s check if the generated password string of length 12 satisfies the following constraints:

  • The string pwd should contain at least one special character.
  • It should contain at least two digits.

In the code snippet below, you may modify the condition that the if statement checks for according to the constraints you define.

while True:
  pwd = ''
  for i in range(pwd_length):
    pwd += ''.join(secrets.choice(alphabet))

  if (any(char in special_chars for char in pwd) and 
      sum(char in digits for char in pwd)>=2):
          break
print(pwd)
# Sample output
lX]{`y47pM4t

In the code cell above, we use an infinite while loop that runs so long as the password string pwd does not meet the constraints. When the generated password, pwd satisfies the constraints, we break out of the infinite loop.

Here’s the complete code for the Python password generator:

# necessary imports
import secrets
import string

# define the alphabet
letters = string.ascii_letters
digits = string.digits
special_chars = string.punctuation

alphabet = letters + digits + special_chars

# fix password length
pwd_length = 12

# generate a password string
pwd = ''
for i in range(pwd_length):
  pwd += ''.join(secrets.choice(alphabet))

print(pwd)

# generate password meeting constraints
while True:
  pwd = ''
  for i in range(pwd_length):
    pwd += ''.join(secrets.choice(alphabet))

  if (any(char in special_chars for char in pwd) and 
      sum(char in digits for char in pwd)>=2):
          break
print(pwd)

Conclusion

Congratulations on finishing this tutorial! 🎉You’ve now learned how to code a password generator in Python.

  • To generate cryptographically secure passwords, you should use the secrets module and not the random module.
  • A strong password should be sufficiently long and should be random in that it cannot be easily predicted or generated. It should be a combination of uppercase and lowercase letters, digits, and special characters.
  • Python ships with a built-in string module that provides all letters, digits, and special characters in the constants ascii_letters, digits, and punctuation, respectively. Use the syntax: string.constant to access these string constants.
  • You can use the above constants to define an alphabet (a set of all characters) for password generation.
  • Once you’ve defined an alphabet, you can use secrets.choice() to sample a random character from it. To repeat this for the length of the password, you can use a for loop.

▶️ Next, read the list of Python web servers to use.

Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Semrush is an all-in-one digital marketing solution with more than 50 tools in SEO, social media, and content marketing.
    Try Semrush
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder