Python Snippets

Password Strength Validator with Feedback

import re
import string
from typing import Tuple, List

def validate_password_strength(password: str) -> Tuple[bool, List[str]]:
    """
    Validates password strength and provides feedback for improvement.
    
    Criteria:
    - Minimum 8 characters
    - At least one uppercase letter
    - At least one lowercase letter
    - At least one digit
    - At least one special character
    - Not common password patterns (e.g., 'password123')
    
    Args:
        password (str): The password to validate
        
    Returns:
        Tuple[bool, List[str]]: (is_valid, feedback_messages)
    """
    feedback = []
    score = 0
    
    # Check length
    if len(password) < 8:
        feedback.append("Password must be at least 8 characters long")
    else:
        score += 1
    
    # Check for uppercase letters
    if not re.search(r"[A-Z]", password):
        feedback.append("Add at least one uppercase letter")
    else:
        score += 1
    
    # Check for lowercase letters
    if not re.search(r"[a-z]", password):
        feedback.append("Add at least one lowercase letter")
    else:
        score += 1
    
    # Check for digits
    if not re.search(r"\d", password):
        feedback.append("Add at least one number")
    else:
        score += 1
    
    # Check for special characters
    if not re.search(rf"[{re.escape(string.punctuation)}]", password):
        feedback.append("Add at least one special character (!@#$%^&* etc.)")
    else:
        score += 1
    
    # Check for common weak patterns
    common_patterns = [
        r"password",
        r"123456",
        r"qwerty",
        r"abc123",
        r"admin",
        r"letmein"
    ]
    
    password_lower = password.lower()
    has_common_pattern = any(re.search(pattern, password_lower) for pattern in common_patterns)
    
    if has_common_pattern:
        feedback.append("Avoid common password patterns")
    else:
        score += 1
    
    # Additional checks for stronger passwords
    if len(password) >= 12:
        score += 1
    
    # Check for character diversity
    unique_chars = len(set(password))
    if unique_chars < len(password) * 0.7:
        feedback.append("Use more diverse characters")
    else:
        score += 1
    
    # Determine strength based on score
    is_valid = score >= 6
    strength_levels = {
        0: "Very Weak",
        1: "Very Weak",
        2: "Weak",
        3: "Weak",
        4: "Fair",
        5: "Fair",
        6: "Good",
        7: "Strong",
        8: "Very Strong"
    }
    
    strength = strength_levels.get(score, "Very Strong")
    feedback.insert(0, f"Password Strength: {strength}")
    
    return is_valid, feedback

def main():
    """Main function to demonstrate password validation"""
    print("Password Strength Validator")
    print("=" * 30)
    
    # Example passwords to test
    test_passwords = [
        "password",
        "Password123!",
        "MyStr0ng!Passw0rd",
        "p4ssw0rd",
        "Tr0ub4dor&3"
    ]
    
    for pwd in test_passwords:
        is_valid, feedback = validate_password_strength(pwd)
        print(f"\nPassword: '{pwd}'")
        print(f"Valid: {is_valid}")
        for msg in feedback:
            print(f"  - {msg}")
    
    # Interactive mode
    print("\n" + "=" * 30)
    print("Enter your own password to test (or 'quit' to exit):")
    
    while True:
        user_password = input("\nPassword: ")
        if user_password.lower() == 'quit':
            break
            
        is_valid, feedback = validate_password_strength(user_password)
        print(f"Valid: {is_valid}")
        for msg in feedback:
            print(f"  - {msg}")

if __name__ == "__main__":
    main()

What This Code Does

This password strength validator is a practical security tool that evaluates the robustness of passwords based on modern security criteria. The function analyzes several key factors:

  1. Length Requirements: Ensures passwords are at least 8 characters (12+ is better)
  2. Character Diversity: Checks for uppercase, lowercase, digits, and special characters
  3. Pattern Recognition: Identifies common weak passwords like “password123”
  4. Uniqueness: Analyzes character diversity to prevent repetitive patterns
  5. Scoring System: Provides a quantitative measure of password strength

Why This is Useful

Weak passwords are one of the most common security vulnerabilities. This tool helps users:

The validator goes beyond simple checks by providing specific, constructive feedback rather than just a pass/fail result.

How to Run It

  1. Save the code to a file named password_validator.py
  2. Run from terminal: python password_validator.py
  3. The script will first run examples, then allow you to test your own passwords

For integration into other projects, simply import the validate_password_strength function:

from password_validator import validate_password_strength

is_valid, feedback = validate_password_strength("YourPassword123!")
if not is_valid:
    for message in feedback:
        print(message)

Note: This validator does not store or transmit passwords. It’s designed for client-side validation to provide immediate feedback to users.