Build a Secure Password Generator in Python

Welcome to the first post in my new series, Learning Python by Building Real-World Algorithms. One mistake I often see beginners make when they build a password generator in Python is reaching straight for the random module. It works fine for a classroom demo, but in production systems, predictable randomness is a serious security flaw. In this tutorial, you will learn how to build a secure password generator in Python using cryptographic randomness, unbiased shuffling, and entropy measurement.

By the end, you will have a clean, standard-library script you can adapt for real authentication workflows.

The Core Concepts Behind Secure Password Generation

Before writing code, it helps to understand three algorithmic concepts that separate a script from a reliable security utility.

1. PRNG vs. CSPRNG (random vs. secrets)

Python’s random module uses the Mersenne Twister, a deterministic pseudorandom number generator (PRNG). It is fast and ideal for simulations or data sampling, but its internal state can be reconstructed after observing enough outputs. Once an attacker recovers that state, every future “random” password becomes predictable.

For security-sensitive tasks, Python provides the secrets module—a cryptographically secure pseudorandom number generator (CSPRNG). Instead of relying on an algorithmic seed, secrets pulls entropy directly from your operating system (such as /dev/urandom on Linux/macOS or BCryptGenRandom on Windows).

🎯 Turn Python Practice Into Interview Preparation
Writing working code is step one, yet technical rounds test how you spot edge cases and justify every choice. Master that structured thinking in Cracking Your First AI/ML Interview.

2. Eliminating Modulo and Positional Bias

When selecting characters from a pool, naive implementations often compute rand_int % pool_size. Unless the random integer range divides evenly by the pool size, some characters appear slightly more often than others—a flaw known as modulo bias. Calling secrets.choice() avoids this automatically through rejection sampling.

Similarly, if you guarantee password complexity by picking one lowercase letter, one uppercase letter, one digit, and one symbol first, those characters sit at fixed indices (0 through 3). Running an unbiased Fisher-Yates shuffle via secrets.SystemRandom().shuffle() removes that positional predictability.

3. Measuring Strength with Bit Entropy

Rather than guessing whether a password looks strong, engineers measure information entropy in bits:

H = L × log₂(N)

Here, L is the password length, and N is the number of unique characters in your pool. Each additional bit doubles the number of guesses an attacker needs in a brute-force search.

Secure Password Generator in Python

Because both secrets and string ship with Python 3.6+, you do not need to install any third-party packages. Save the following code as password_generator.py and run it directly:

import math
import secrets
import string


def calculate_entropy(length: int, pool_size: int) -> float:
    """Calculate password strength in bits using H = L * log2(N)."""
    return length * math.log2(pool_size)


def generate_secure_password(length: int = 16) -> tuple[str, float]:
    """Generate a cryptographically secure password and its bit entropy."""
    if length < 4:
        raise ValueError("Password length must be at least 4 characters.")

    # Define four distinct character pools (88 characters total)
    lowercase = string.ascii_lowercase
    uppercase = string.ascii_uppercase
    digits = string.digits
    symbols = "!@#$%^&*()-_=+[]{}|;:,.<>?"
    all_chars = lowercase + uppercase + digits + symbols

    # Step 1: Guarantee at least one character from each category
    password_chars = [
        secrets.choice(lowercase),
        secrets.choice(uppercase),
        secrets.choice(digits),
        secrets.choice(symbols),
    ]

    # Step 2: Fill the remaining length from the combined pool
    password_chars.extend(
        secrets.choice(all_chars) for _ in range(length - 4)
    )

    # Step 3: Shuffle in place using a cryptographic Fisher-Yates shuffle
    secrets.SystemRandom().shuffle(password_chars)

    password = "".join(password_chars)
    entropy = calculate_entropy(length, len(all_chars))
    return password, entropy


if __name__ == "__main__":
    for idx in range(1, 4):
        pwd, bits = generate_secure_password(length=16)
        print(f"Password {idx}: {pwd} | Entropy: {bits:.1f} bits")
Password 1: {T+p9?m{VxvcWb%] | Entropy: 103.4 bits
Password 2: gg$F#{91],?@T:Vs | Entropy: 103.4 bits
Password 3: 2)x2j=^RI::?#{EN | Entropy: 103.4 bits

Breaking Down How the Algorithm Works

  1. Input Guardrail: Raising a ValueError when length < 4 prevents silent logic bugs when the function tries to enforce four mandatory character categories.
  2. Curated Symbol Set: Instead of string.punctuation, which includes quotes and backslashes that often break shell scripts or legacy forms, we define 26 clean special characters alongside 26 lowercase letters, 26 uppercase letters, and 10 digits (N = 88).
  3. Guaranteed Coverage Without Retries: Many beginner scripts generate random strings in a while loop until all rules pass. Picking one character per pool upfront guarantees compliance in O(L) linear time.
  4. Unbiased Randomization: Calling secrets.SystemRandom().shuffle() randomizes the list in place so guaranteed character types appear at unpredictable positions, yielding 103.4 bits of entropy for a 16-character string.

What to Build Next

When I mentor learners moving from basic Python scripting into software and AI engineering, small utilities like this always reveal an important habit: never treat security primitives as boilerplate. Understanding why secrets replaces random prepares you to handle API keys, token generation, and session secrets safely in real applications.

As a next exercise, try extending this script with a flag to exclude visually ambiguous characters (0, O, 1, l) or adding a Diceware-style passphrase mode.

I hope you enjoyed this article on building a secure password generator in Python. For more tips on Python, AI and machine learning, follow me on Instagram.

Aman Kharwal
Aman Kharwal

AI/ML Engineer | Published Author. My aim is to decode data science for the real world in the most simple words.

Articles: 2280

Leave a Reply