Python Snippets

Secure Password Generator with Customizable Complexity

This snippet generates strong, randomized passwords with customizable complexity options (length, character types). It’s useful for creating secure credentials for applications, user accounts, or API keys.

import secrets
import string

def generate_password(length=16, use_uppercase=True, use_digits=True, use_special=True):
    """Generate a secure random password with specified complexity."""
    characters = string.ascii_lowercase
    if use_uppercase:
        characters += string.ascii_uppercase
    if use_digits:
        characters += string.digits
    if use_special:
        characters += string.punctuation
    
    if not characters:
        raise ValueError("At least one character type must be selected")
    
    return ''.join(secrets.choice(characters) for _ in range(length))

# Example usage
print("Standard password:", generate_password())
print("Numeric PIN:", generate_password(6, use_uppercase=False, use_special=False))
print("Extra strong:", generate_password(24, use_uppercase=True, use_digits=True, use_special=True))

Why This Is Useful

  1. Security-First: Uses secrets module (cryptographically secure) instead of random
  2. Customizable: Control length and character sets via parameters
  3. Validation: Prevents empty character set scenarios
  4. Readable: Clear function signature with sensible defaults

How to Use

  1. Call generate_password() with no arguments for a 16-character password with all character types
  2. Customize via parameters:
    • length: Set password length (default 16)
    • use_uppercase: Include A-Z (default True)
    • use_digits: Include 0-9 (default True)
    • use_special: Include !@#$% etc. (default True)

Example Outputs

Standard password: gH7#kL9@mN2!pQ4%
Numeric PIN: 729384
Extra strong: Wb3$kP8#mN1@xZ6*qL9%vR4^cT7&yU2

For production use, consider adding these features: