Python Snippets

Secure Password Generator with Customizable Requirements

This snippet generates strong, secure passwords with customizable length and character set requirements. It’s useful for creating passwords that meet specific security policies or for generating multiple passwords for different services.

import secrets
import string

def generate_password(length=12, uppercase=True, digits=True, special_chars=True):
    """Generate a secure random password with customizable requirements.
    
    Args:
        length (int): Length of the password. Default 12.
        uppercase (bool): Include uppercase letters. Default True.
        digits (bool): Include digits. Default True.
        special_chars (bool): Include special characters. Default True.
    
    Returns:
        str: Generated password.
    """
    chars = string.ascii_lowercase
    if uppercase:
        chars += string.ascii_uppercase
    if digits:
        chars += string.digits
    if special_chars:
        chars += string.punctuation
    
    while True:
        password = ''.join(secrets.choice(chars) for _ in range(length))
        # Ensure all required character types are included if specified
        if (not uppercase or any(c in string.ascii_uppercase for c in password)) and \
           (not digits or any(c in string.digits for c in password)) and \
           (not special_chars or any(c in string.punctuation for c in password)):
            return password

# Example usage
print("Standard password:", generate_password())
print("Numeric PIN:", generate_password(4, uppercase=False, special_chars=False))
print("Complex password:", generate_password(16, True, True, True))

Explanation

Key Features

  1. Cryptographically Secure: Uses secrets module (recommended over random for security applications)
  2. Customizable Requirements:
    • Length (default 12 characters)
    • Uppercase letters (default enabled)
    • Digits (default enabled)
    • Special characters (default enabled)
  3. Validation: Guarantees the password contains at least one character from each enabled character set

Why This Is Useful

How to Run

  1. Simply copy the code into a Python file (e.g., password_generator.py)
  2. Run with python password_generator.py
  3. Customize the example usages at the bottom or call generate_password() with your own parameters

The function will continue generating passwords until it finds one that meets all specified requirements, then return it immediately. This avoids the security issue of potentially weak passwords that don’t include all required character types.