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))
secrets
module (recommended over random
for security applications)password_generator.py
)python password_generator.py
generate_password()
with your own parametersThe 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.