Skip to main content

Password Strength Checker

Mejbah Ahammad

Use Case Scenario:

In the digital age, the strength of a user's password is a cornerstone of securing personal and corporate data. A password strength checker is crucial in systems for user registration or security settings updates, ensuring users craft robust passwords that are tough to crack.

Python Function: check_password_strength

import re

def check_password_strength(password):
    if len(password) < 8:
        return "Weak: Password too short."
    if not re.search("[a-z]", password):
        return "Weak: No lowercase letter."
    if not re.search("[A-Z]", password):
        return "Weak: No uppercase letter."
    if not re.search("[0-9]", password):
        return "Weak: No digit."
    if not re.search("[!@#$%^&*(),.?\":{}|<>]", password):
        return "Weak: No special character."
    return "Strong: Password is strong."

Code Explanation:

  • import re: This line brings Python's regular expressions module into our script, a powerful tool for matching sequences of characters within strings, crucial for pattern checks.
  • def check_password_strength(password):: We define a function check_password_strength that takes a single argument: the password string to be evaluated.
  • if len(password) < 8:: First, the function checks if the password length is below 8 characters, returning a message about the password being too short if true.
  • if not re.search("[a-z]", password):: It then verifies the presence of at least one lowercase letter. Absence results in a corresponding message.
  • if not re.search("[A-Z]", password):: Similarly, it checks for uppercase letters, returning a message if none are found.
  • if not re.search("[0-9]", password):: The function ensures that there is at least one digit in the password, informing the user if this criterion isn't met.
  • if not re.search("[!@#$%^&*(),.?\":{}|<>]", password):: Lastly, it checks for special characters, crucial for strong passwords, and alerts if absent.
  • return "Strong: Password is strong.": If all checks are passed, the function concludes the password is strong.

Input:

# Test passwords
passwords = ["weak", "StrongPassword123", "VeryStrong!123", "Weak123", "Robust$1234"]

# Check each password and print the result
for pwd in passwords:
    result = check_password_strength(pwd)
    print(f"Password: {pwd} - {result}")

Expected Output:

Password: weak - Weak: Password too short.
Password: StrongPassword123 - Weak: No special character.
Password: VeryStrong!123 - Strong: Password is strong.
Password: Weak123 - Weak: No special character.
Password: Robust$1234 - Strong: Password is strong.

Resources for Further Learning:

This password strength checker function provides a straightforward way to enforce security best practices, ensuring users create passwords that protect their accounts effectively.