Python

Generate Strong Random Password

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Build a password using the `secrets` module (CSPRNG) with rejection sampling for unbiased distribution. Use this — NOT random.choice, which is seeded predictably.
Python
Raw
import secrets

def generate_password(length: int = 20, *, lower=True, upper=True, digits=True, symbols=True) -> str:
    pools: list[str] = []
    if lower:   pools.append("abcdefghijklmnopqrstuvwxyz")
    if upper:   pools.append("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    if digits:  pools.append("0123456789")
    if symbols: pools.append("!@#$%^&*()-_=+[]{};:,.<>?/~")
    if not pools or length < 1:
        raise ValueError("Pick at least one character set and length >= 1")

    alphabet = "".join(pools)
    # Guarantee at least one of each chosen set
    out = [secrets.choice(p) for p in pools]
    out += [secrets.choice(alphabet) for _ in range(length - len(out))]
    secrets.SystemRandom().shuffle(out)
    return "".join(out)[:length]

print(generate_password(20))                                    # 'X9k!nQ2pR&7vL@bWtN3z'
print(generate_password(16, symbols=False))                     # alnum only
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.