Want to generate strong, random passwords in Python? This beginner-friendly tutorial will guide you through building a terminal-based password generator that creates secure passwords based on user-defined length and evaluates their entropy.
What You Will Learn:
- How to generate secure, random passwords
- Using Python's secrets
module for cryptographic security
- Calculating password entropy to measure strength
- Structuring an efficient and user-friendly program
- Best practices for password security
Step 1: Setting Up the Project
Before we start coding, let’s set up our Python project:
1. Make sure Python is installed on your computer. If not, download it from the official Python website.
2. Open your favorite code editor or IDE.
3. Create a new Python file, for example, password_generator.py
.
Great, now, let's dive head first into our Python editor to get this build started to produce something like I've shown below:
Step 2: Understanding Secure Password Generation
A secure password should be:
- Randomly generated → Prevents easy guessing.
- Sufficiently long → Longer passwords are harder to crack.
- Contain a mix of characters → Uppercase, lowercase, digits, and special symbols.
- Unique → Avoids using common words or patterns.
To ensure strong security, we will generate passwords using Python’s secrets
module, which is designed for cryptographic applications.
Step 3: What is Entropy in Passwords?
Entropy measures the randomness and unpredictability of a password, which determines its resistance to brute-force attacks.
How is Entropy Calculated?
The formula for entropy (in bits) is:
Entropy = log₂(N^L)
where:
N
= Number of possible characters in the set (e.g., 26 for lowercase, 62 for letters + digits, etc.)L
= Password length
Higher entropy values mean stronger passwords.
Step 4: Importing Required Modules
We need the following modules:
import secrets # For cryptographic random password generation
import string # For character sets (uppercase, lowercase, digits, symbols)
import math # For entropy calculation
Why These Modules?
secrets
→ Generates cryptographically secure random values.string
→ Provides predefined character sets for password generation.math
→ Used to compute log₂ for entropy calculation.
Step 5: Writing the Password Generator Function
Now, let's define a function to generate a secure password:
def generate_password(length=12):
"""Generates a secure password of a given length."""
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(characters) for _ in range(length))
return password
How It Works:
-
Defines a set of possible characters: The
characters
variable includes uppercase letters, lowercase letters, digits, and special symbols, ensuring a wide variety of possible passwords. -
Uses
secrets.choice()
for randomness: Unlike Python'srandom
module, which is not cryptographically secure,secrets.choice()
ensures that the password is generated using a method resistant to prediction or bias. -
Builds the password dynamically:
-
The function iterates
length
times. -
In each iteration, a random character is selected from
characters
. -
These characters are concatenated using
''.join()
to form the final password string.
-
-
Default password length is 12: If the user does not specify a length, the function generates a password with 12 characters, a commonly recommended minimum for security.
This approach ensures that the generated passwords are both random and secure, making them resistant to brute-force attacks and dictionary-based guessing.
Step 6: Calculating Password Entropy
Let's create a function that determines the secure password's entropy:
def calculate_entropy(password):
"""Calculates entropy (bits of security) for a given password."""
char_pool = 0
if any(c.islower() for c in password):
char_pool += 26 # Lowercase letters
if any(c.isupper() for c in password):
char_pool += 26 # Uppercase letters
if any(c.isdigit() for c in password):
char_pool += 10 # Digits
if any(c in string.punctuation for c in password):
char_pool += len(string.punctuation) # Special characters
entropy = math.log2(char_pool ** len(password))
return entropy
How It Works:
-
Determines the variety of characters used in the password:
-
If the password contains lowercase letters, the function adds
26
to the character pool. -
If it contains uppercase letters, another
26
is added. -
If it includes digits (
0-9
), the function increases the pool by10
. -
If special characters are used, it includes their total count (
len(string.punctuation)
).
-
-
Computes entropy using
log₂(N^L)
, where:-
N
is the total number of possible characters (character pool size). -
L
is the length of the password. -
The
math.log2()
function is used to calculate entropy in bits.
-
-
Higher entropy values indicate stronger passwords:
-
Weak passwords (< 50 bits) are easy to crack.
-
Moderate passwords (50-80 bits) are better but could be stronger.
-
Strong passwords (> 80 bits) provide high security.
-
By structuring the function this way, we ensure an accurate estimation of password strength, allowing users to make informed security choices.
Step 7: Running the Password Generator
Now, it's time to run the password generator function within a while loop, to allow users the option to generate a new password:
if __name__ == "__main__":
print("===== Secure Password Generator =====")
while True:
length = int(input("Enter desired password length: "))
password = generate_password(length)
entropy = calculate_entropy(password)
print(f"\nGenerated Password: {password}")
print(f"Password Entropy: {entropy:.2f} bits")
if entropy < 50:
print("⚠️ Weak password! Consider using more characters.")
elif entropy < 80:
print("✅ Moderate password. Could be stronger.")
else:
print("🔒 Strong password! Very secure.")
user_choice = input("Are you happy with this password? (yes/no): ").strip().lower()
if user_choice == 'yes':
print("✅ Password finalized.")
break
else:
print("🔄 Generating a new password...\n")
How This Works:
-
-
Prompts the user for their desired password length, ensuring flexibility.
-
Generates a strong, random password using the
generate_password()
function. -
Calculates entropy using the
calculate_entropy()
function to measure the strength of the generated password. -
Displays the password and entropy value in a clear format within a Python f-string.
-
Provides security feedback based on entropy:
-
If entropy is less than 50, the password is weak and should be improved.
-
If entropy is between 50 and 80, the password is moderate but could be stronger.
-
If entropy is greater than 80, the password is strong and highly secure.
-
-
Introduces a
while
loop to keep generating passwords until the user is satisfied. -
Allows the user to confirm if they are happy with the generated password or want a new one.
-
Breaks the loop once the user accepts the password, ensuring flexibility without restarting the program.
This structure ensures usability while also educating users about password strength, helping them create more secure passwords for their online accounts.
-
Final Code: Password Generator
import secrets # For cryptographic random password generation
import string # For character sets (uppercase, lowercase, digits, symbols)
import math # For entropy calculation
def generate_password(length=12):
"""Generates a secure password of a given length."""
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(characters) for _ in range(length))
return password
def calculate_entropy(password):
"""Calculates entropy (bits of security) for a given password."""
char_pool = 0
if any(c.islower() for c in password):
char_pool += 26 # Lowercase letters
if any(c.isupper() for c in password):
char_pool += 26 # Uppercase letters
if any(c.isdigit() for c in password):
char_pool += 10 # Digits
if any(c in string.punctuation for c in password):
char_pool += len(string.punctuation) # Special characters
entropy = math.log2(char_pool ** len(password))
return entropy
if __name__ == "__main__":
print("===== Secure Password Generator =====")
while True:
length = int(input("Enter desired password length: "))
password = generate_password(length)
entropy = calculate_entropy(password)
print(f"\nGenerated Password: {password}")
print(f"Password Entropy: {entropy:.2f} bits")
if entropy < 50:
print("⚠️ Weak password! Consider using more characters.")
elif entropy < 80:
print("✅ Moderate password. Could be stronger.")
else:
print("🔒 Strong password! Very secure.")
user_choice = input("Are you happy with this password? (yes/no): ").strip().lower()
if user_choice == 'yes':
print("✅ Password finalized.")
break
else:
print("🔄 Generating a new password...\n")
Wrapping Up
Congratulations! You’ve built a fully functional secure password generator in Python.
What You Learned:
- Generating secure passwords using secrets.choice()
- Calculating entropy to measure password strength
- Structuring a Python program efficiently
- Providing user-friendly feedback for security awareness
Next Steps:
- Modify the generator to support passphrases (multi-word passwords).
- Encrypt generated passwords before storing them in a file.
- Build a GUI version using Tkinter for easier user interaction.
The best way to learn Python is by building real projects—so keep experimenting!