Want to create a robust Python password strength checker to analyze password security? This project will guide you through building a command-line tool that evaluates the strength of a password based on entropy, length, and character diversity.
What You Will Learn:
- Understanding password strength evaluation
- Using entropy for password security analysis
- Implementing getpass for secure password input
- Validating user input and character diversity
- Creating a loop for multiple checks
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_checker.py
.
Great, now, let's dive head first into our Python editor to get this build started.
Step 2: Understanding How the Password Strength Checker Works
Our program will:
- Prompt the user to enter a password securely using
getpass
. - Evaluate the password’s strength based on length, character variety, and entropy.
- Provide feedback on password quality and improvements.
- Allow the user to check multiple passwords in a loop until they decide to exit.
Step 3: Importing Required Modules
We need three Python modules:
import random # For generating random numbers
import os # To clear the screen
Why Do We Use These Modules?
-
string → Provides predefined character sets (lowercase, uppercase, digits, special characters).
-
getpass → Allows secure password entry without displaying it on the screen.
-
math → Used to calculate password entropy for strength evaluation.
Now that we have our required modules, let's move on to defining our functions.
Step 4: Implementing Password Entropy Calculation
Let's start by writing the core password evaluation functions.
MIN_LENGTH = 8 # Minimum recommended password length
def calculate_entropy(password):
"""Calculates entropy based on character diversity and length."""
charset_size = 0
if any(c in string.ascii_lowercase for c in password):
charset_size += 26
if any(c in string.ascii_uppercase for c in password):
charset_size += 26
if any(c in string.digits for c in password):
charset_size += 10
if any(c in string.punctuation for c in password):
charset_size += len(string.punctuation)
if any(c.isspace() for c in password):
charset_size += 1
return len(password) * math.log2(charset_size) if charset_size else 0
How It Works:
-
Identifies character diversity by checking if the password contains lowercase, uppercase, digits, special characters, or spaces.
-
Uses entropy calculation to determine password strength using the formula
entropy = length * log2(character_set_size)
. -
Higher entropy = stronger password, making it harder for attackers to guess.
Why Do We Use Entropy?
Entropy is a scientific measure of password strength. Instead of just checking if a password contains numbers or symbols, entropy estimates how unpredictable a password is:
-
Higher entropy → More combinations → Harder to crack.
-
Lower entropy → Easier to guess → Weaker security.
By using entropy-based evaluation, we provide a better security analysis rather than just counting characters.
Now that we have password entropy in place, let’s proceed to evaluating password strength and user feedback.
Step 5: Checking Password Strength
Now, let's implement the function that analyzes password strength and provides feedback:
def check_password_strength():
"""Evaluates password strength based on entropy and diversity."""
password = getpass.getpass('Enter your password: ')
if len(password) < MIN_LENGTH:
print(f"⚠️ Your password is too short! It must be at least {MIN_LENGTH} characters.")
return
lower_count = sum(1 for c in password if c in string.ascii_lowercase)
upper_count = sum(1 for c in password if c in string.ascii_uppercase)
num_count = sum(1 for c in password if c in string.digits)
special_count = sum(1 for c in password if c in string.punctuation)
wspace_count = sum(1 for c in password if c.isspace())
entropy = calculate_entropy(password)
# Classifying password strength
if entropy < 28:
remarks = "⚠️ Very Weak: Easily guessable! Change it immediately."
elif entropy < 36:
remarks = "⚠️ Weak: Can be cracked quickly. Use a stronger password."
elif entropy < 60:
remarks = "✅ Moderate: Decent password, but can still be improved."
elif entropy < 80:
remarks = "✅ Strong: Hard to guess, but consider making it longer."
else:
remarks = "✅ Very Strong: Excellent password! Highly secure."
# Display password analysis
print("\n🔎 Password Analysis:")
print(f"🔹 {lower_count} lowercase letters")
print(f"🔹 {upper_count} uppercase letters")
print(f"🔹 {num_count} digits")
print(f"🔹 {special_count} special characters")
print(f"🔹 {wspace_count} whitespace characters")
print(f"🔹 Entropy Score: {entropy:.2f} bits")
print(f"🔹 Remarks: {remarks}\n")
How It Works:
-
Analyzes password diversity by counting lowercase, uppercase, digits, special characters, and whitespace.
-
Uses entropy score to classify the strength of the password.
-
Provides clear feedback on how secure the password is via various Python f-strings.
By implementing this analysis, users get a comprehensive breakdown of their password’s security level.
Now that we can evaluate password strength, let’s move on to looping the process for multiple checks.
Step 6: Looping for Multiple Checks
To allow users to check multiple passwords, we add a while loop:
def check_another_password():
"""Asks the user if they want to check another password."""
while True:
choice = input("🔄 Do you want to check another password? (y/n): ").strip().lower()
if choice == 'y':
return True
elif choice == 'n':
print("👋 Exiting... Stay secure!")
return False
else:
print("⚠️ Invalid input. Please enter 'y' or 'n'.")
How It Works:
-
Continuously prompts users to check another password.
-
Ensures only valid responses (
y
for yes,n
for no) are accepted. -
Provides a smooth user experience by keeping the program interactive.
By implementing this, users can evaluate multiple passwords in a single session.
Now that we have an interactive password checker, let’s move on to finalizing the program execution.
Step 7: Running the Program
Finally, we ensure the script runs correctly when executed:
if __name__ == '__main__':
print("===== 🔑 Welcome to Password Strength Checker 🔑 =====")
while check_another_password():
check_password_strength()
Why Is This Needed?
-
Ensures the script runs only when executed directly.
-
Prevents unintended execution when imported as a module.
-
Creates a structured workflow that loops through password checks.
By using this structure, we keep the program organized, user-friendly, and maintainable. Now, your password strength checker is fully functional and ready to use.
Final Code: Password Strength Checker
import string # For checking character diversity
import getpass # For secure password input
import math # For entropy calculation
# Minimum recommended password length
MIN_LENGTH = 8
def calculate_entropy(password):
"""Calculates entropy based on character diversity and length."""
charset_size = 0
if any(c in string.ascii_lowercase for c in password):
charset_size += 26
if any(c in string.ascii_uppercase for c in password):
charset_size += 26
if any(c in string.digits for c in password):
charset_size += 10
if any(c in string.punctuation for c in password):
charset_size += len(string.punctuation)
if any(c.isspace() for c in password):
charset_size += 1
return len(password) * math.log2(charset_size) if charset_size else 0
def check_password_strength():
"""Evaluates password strength based on entropy and diversity."""
password = getpass.getpass('Enter your password: ')
if len(password) < MIN_LENGTH:
print(f"⚠️ Your password is too short! It must be at least {MIN_LENGTH} characters.")
return
lower_count = sum(1 for c in password if c in string.ascii_lowercase)
upper_count = sum(1 for c in password if c in string.ascii_uppercase)
num_count = sum(1 for c in password if c in string.digits)
special_count = sum(1 for c in password if c in string.punctuation)
wspace_count = sum(1 for c in password if c.isspace())
entropy = calculate_entropy(password)
# Classifying password strength
if entropy < 28:
remarks = "⚠️ Very Weak: Easily guessable! Change it immediately."
elif entropy < 36:
remarks = "⚠️ Weak: Can be cracked quickly. Use a stronger password."
elif entropy < 60:
remarks = "✅ Moderate: Decent password, but can still be improved."
elif entropy < 80:
remarks = "✅ Strong: Hard to guess, but consider making it longer."
else:
remarks = "✅ Very Strong: Excellent password! Highly secure."
# Display password analysis
print("\n🔎 Password Analysis:")
print(f"🔹 {lower_count} lowercase letters")
print(f"🔹 {upper_count} uppercase letters")
print(f"🔹 {num_count} digits")
print(f"🔹 {special_count} special characters")
print(f"🔹 {wspace_count} whitespace characters")
print(f"🔹 Entropy Score: {entropy:.2f} bits")
print(f"🔹 Remarks: {remarks}\n")
def check_another_password():
"""Asks the user if they want to check another password."""
while True:
choice = input("🔄 Do you want to check another password? (y/n): ").strip().lower()
if choice == 'y':
return True
elif choice == 'n':
print("👋 Exiting... Stay secure!")
return False
else:
print("⚠️ Invalid input. Please enter 'y' or 'n'.")
if __name__ == '__main__':
print("===== 🔑 Welcome to Password Strength Checker 🔑 =====")
while check_another_password():
check_password_strength()
Wrapping Up
Congratulations! You’ve built a fully functional Password Strength Checker in Python.
What You Learned:
- Password entropy calculation
- Validating password length and diversity
- Secure password input using getpass
- Continuous password checks with a loop
Next Steps:
- Add a password breach check using HaveIBeenPwned API.
- Suggest stronger passphrase alternatives if a password is weak.
- Build a GUI version using Tkinter or PyQt.
The best way to learn is by building projects, so keep coding!