Sample Hack - Password Validator

The goal of this homework hack is to create a password validator. A couple examples are given below (Simple and Advanced)

Simple Password Validator

def password_validator(password):
    if len(password) < 8:
        return "Password too short. Must be at least 8 characters."

    if password == password.lower() or password == password.upper():
        return "Password must contain both uppercase and lowercase letters."

    if not any(char.isdigit() for char in password):
        return "Password must contain at least one number."

    # Optional
    password = password.replace("123", "abc")

    words = password.split(" ")
    customized_password = "-".join(words)

    return f"Password is valid! Here’s a fun version: {customized_password}"

# Example usage
password = "HelloWorld123"
print(password_validator(password))

Password is valid! Here’s a fun version: HelloWorldabc
print(password_validator("HELLO123"))
Password must contain both uppercase and lowercase letters.
print(password_validator("Hello123"))

Advanced Password Validator

import re

def password_validator(password):
    if len(password) < 8:
        return "Password too short. Must be at least 8 characters."
    
    if password == password.lower() or password == password.upper():
        return "Password must contain both uppercase and lowercase letters."
    
    if not any(char.isdigit() for char in password):
        return "Password must contain at least one number."
    
    if not re.search(r"[!@#$%^&*()_+]", password):
        return "Password must contain at least one special character (e.g. !, @, #, etc.)"
    
    common_passwords = ["password", "123456", "letmein", "qwerty"]
    if password.lower() in common_passwords:
        return "Password is too common. Choose something less predictable."
    
    sequential_patterns = ["123", "abc", "xyz"]
    for pattern in sequential_patterns:
        if pattern in password.lower():
            return "Password should not contain sequential characters like '123' or 'abc'."
    
    score = 0
    if len(password) >= 10:
        score += 1
    if re.search(r"[A-Z]", password) and re.search(r"[a-z]", password):
        score += 1
    if re.search(r"\d", password):
        score += 1
    if re.search(r"[!@#$%^&*()_+]", password):
        score += 1

    strength = "Weak"
    if score == 2:
        strength = "Medium"
    elif score >= 3:
        strength = "Strong"

    password = password.replace("Hello", "Hi")
    words = password.split(" ")
    customized_password = "-".join(words)

    return f"Password is valid and {strength}! Here’s a fun version: {customized_password}"

# Example usage
password = "HelloWorld13475!"
print(password_validator(password))


Password is valid and Strong! Here’s a fun version: HiWorld13475!