Password Generator — Developer Code Samples
Generate cryptographically secure random passwords using the secrets module in Python (preferred over random) or crypto.getRandomValues() in the browser. These patterns are appropriate for generating API keys, temporary passwords, and secure tokens.
Try the interactive version online:
Open Password Generator Tool →
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| length | int | No | Password length in characters (default: 16) |
| use_uppercase | bool | No | Include uppercase letters A-Z (default: True) |
| use_lowercase | bool | No | Include lowercase letters a-z (default: True) |
| use_digits | bool | No | Include digits 0-9 (default: True) |
| use_symbols | bool | No | Include symbols !@#$%^&* (default: True) |
Returns: Cryptographically secure random password string
Code Examples
import secrets
import string
# Generate a secure random password
def generate_password(
length=16,
use_uppercase=True,
use_lowercase=True,
use_digits=True,
use_symbols=True,
exclude_ambiguous=False
):
"""Generate a cryptographically secure password."""
charset = ''
required_chars = []
if use_lowercase:
chars = string.ascii_lowercase
if exclude_ambiguous:
chars = chars.replace('l', '').replace('o', '')
charset += chars
required_chars.append(secrets.choice(chars))
if use_uppercase:
chars = string.ascii_uppercase
if exclude_ambiguous:
chars = chars.replace('I', '').replace('O', '')
charset += chars
required_chars.append(secrets.choice(chars))
if use_digits:
chars = string.digits
if exclude_ambiguous:
chars = chars.replace('0', '').replace('1', '')
charset += chars
required_chars.append(secrets.choice(chars))
if use_symbols:
chars = '!@#$%^&*()-_=+[]{}|;:,.<>?'
charset += chars
required_chars.append(secrets.choice(chars))
# Fill remaining length with random chars from full charset
remaining = length - len(required_chars)
password = required_chars + [secrets.choice(charset) for _ in range(remaining)]
# Shuffle to avoid predictable positions
secrets.SystemRandom().shuffle(password)
return ''.join(password)
# Examples
print(generate_password(16)) # Full charset
print(generate_password(32, use_symbols=False)) # Alphanumeric only
print(generate_password(12, exclude_ambiguous=True))
# Generate a passphrase (easier to remember)
WORDS = ['correct', 'horse', 'battery', 'staple', 'purple', 'dragon', 'thunder']
passphrase = '-'.join(secrets.choice(WORDS) for _ in range(4))
print(passphrase) # e.g., correct-dragon-battery-horse
# Generate API key (hex format)
api_key = secrets.token_hex(32) # 64-char hex string
print(api_key)
# URL-safe token
token = secrets.token_urlsafe(32) # 43-char base64url string
print(token)