Skip to contentSkip to navigation

Module 18 · Lesson 03

Project: Secure Password Generator

Build a password tool: generate passwords and passphrases with the secrets module, guarantee every required character type, measure strength in bits of entropy and check passwords against clear rules.

  • About 9 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Pools, picks, guarantee, measure
  • Strength in one line
  • Build the generator in five steps
  • Watch a password get checked

The generator in four parts

Pick from clear pools, pick securely, make sure every type is there, then measure the result.

  • Pools

    The string module has letters, digits and symbols ready. Drop look-alikes such as O and 0.

  • Pick securely

    secrets.choice draws from the system's secure random source, not a guessable formula.

  • Guarantee

    One character from each pool first, the rest from all of them, then shuffle.

  • Measure

    Strength in bits: the length times log2 of the pool size.

Secure randomness everywhere

The same tools protect accounts every day.

  • Password managersThey generate a long random password for every site.
  • Reset linksThe random part of a reset link is a token like secrets.token_urlsafe().
  • Sign-in codesSix-digit codes sent to your phone must be impossible to predict.
  • API keysServices hand out long random keys so programs can prove who they are.

Strength in one line

This line measures how hard a password is to guess. Tap each part to see its job.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

strength:How many yes-or-no guesses an attacker needs in the worst case. More is stronger.

Build the generator in five steps

Build the project one step at a time. Each example runs on its own: change it, then press Run.

Example 1 of 61. Pools

Ready-made character sets, with the easy-to-misread ones removed.

Your turn: Add string.punctuation as a fourth pool and print its size.

Python
import string

LOOK_ALIKE = set("O0Il1")
lower = "".join(c for c in string.ascii_lowercase if c not in LOOK_ALIKE)
upper = "".join(c for c in string.ascii_uppercase if c not in LOOK_ALIKE)
digits = "".join(c for c in string.digits if c not in LOOK_ALIKE)
print(len(lower), len(upper), len(digits))
print(digits)
Output
Press Run to see what it prints.

Watch a password get checked

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. pw = "Rain7"
  2. checks = []
  3. checks.append(len(pw) >= 8)
  4. checks.append(any(c.isdigit() for c in pw))
  5. checks.append(any(c.isupper() for c in pw))
  6. score = sum(checks)
  7. print(score, "of", len(checks))

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Same seed, same numbers:

import random
random.seed(1)
a = random.random()
random.seed(1)
print(a == random.random())

0 of 6 answered

Common password misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Building the generator

The brief

The tool creates a password of a chosen length that contains at least one lowercase letter, one capital, one digit and one symbol, with no characters that are easy to misread. It also creates passphrases of several random words, reports how strong each kind is in bits, and checks a password a person typed against a few rules. It never prints or stores a real password it did not have to.

random is not for secrets

The random module produces numbers from a formula. Given the same starting value, called a seed, it produces exactly the same sequence every time, which is perfect for games, simulations and repeatable tests, and terrible for passwords. An attacker who learns or guesses the state can predict every value that follows.

The secrets module draws from the operating system's secure random source, which is designed so that past values reveal nothing about future ones:

Try it 1: edit me, then Run
import secrets

print(secrets.choice("abc"))       # one secure pick
print(secrets.randbelow(10))       # a secure int from 0 to 9
print(secrets.token_urlsafe(16))   # a random string for links and keys
Output
Press Run to see what it prints.

The rule is simple: if a value protects something, it comes from secrets.

Character pools

The string module has the building blocks ready made: ascii_lowercase, ascii_uppercase, digits and punctuation. Some characters cause trouble when a person has to read a password aloud or type it from a letter: O and 0, l, 1 and I. Removing them costs a tiny amount of strength and saves a lot of support calls:

Try it 2: edit me, then Run
import string

LOOK_ALIKE = set("O0Il1")
LOWER = "".join(c for c in string.ascii_lowercase if c not in LOOK_ALIKE)
UPPER = "".join(c for c in string.ascii_uppercase if c not in LOOK_ALIKE)
DIGITS = "".join(c for c in string.digits if c not in LOOK_ALIKE)
SYMBOLS = "!#$%&*+-=?@"
Output
Press Run to see what it prints.

A short, chosen symbol list avoids quotes, backslashes and spaces, which often break forms and command lines.

Generating a password

Joining secure choices from the combined pool gives a strong random password:

Try it 3: edit me, then Run
POOL = LOWER + UPPER + DIGITS + SYMBOLS

def simple_password(length: int) -> str:
    return "".join(secrets.choice(POOL) for _ in range(length))
Output
Press Run to see what it prints.

But a purely random password sometimes has no digit at all, and many sites reject it. Generating again until one passes works, but the cleaner approach is to build the guarantee in.

Guaranteeing every type

Pick one character from each required pool first, fill the rest from the full pool, then shuffle so the guaranteed characters are not always at the front:

Try it 4: edit me, then Run
def password(length: int = 14) -> str:
    pools = [LOWER, UPPER, DIGITS, SYMBOLS]
    if length < len(pools):
        raise ValueError(f"length must be at least {len(pools)}")
    chars = [secrets.choice(pool) for pool in pools]
    chars += [secrets.choice(POOL) for _ in range(length - len(pools))]
    secrets.SystemRandom().shuffle(chars)
    return "".join(chars)
Output
Press Run to see what it prints.

secrets.SystemRandom() gives the familiar shuffle method backed by the secure source. Using random.shuffle here would undo part of the care taken above.

Measuring strength: entropy

Strength is measured in bits of entropy: how many yes-or-no guesses an attacker needs, on average, to cover all possibilities. For characters picked independently and evenly, the formula is length * log2(pool_size):

Try it 5: edit me, then Run
import math
print(round(12 * math.log2(62), 1))   # 71.5 bits
Output
Press Run to see what it prints.

Each extra bit doubles the work for an attacker. Around 60 bits resists casual attacks; 80 or more is a comfortable margin for important accounts. Note that this measures the generator, not a particular string: Password1! meets every rule, yet it is one of the first things an attacker tries.

Passphrases

Several random words, such as orbit-lantern-pepper-velvet, are easier to remember and type. Their strength is words * log2(list_size). Four words from a list of 7,776 give about 51.7 bits, and six give about 77.5. The words must still be picked with secrets.choice, never chosen by a person, because people pick predictable words.

Checking a typed password

A checker returns a list of problems rather than just True or False, so the person learns what to change. Typical rules: at least 12 characters, at least one digit and one capital, and not in a list of very common passwords. Compare against that list in lower case, so PASSWORD is caught too. Real services also check against lists of passwords exposed in past breaches.

Testing random output

A test cannot compare a generated password with a fixed string. Instead, test properties: generate a few hundred passwords and check that every one has the right length, contains each required type, and uses only allowed characters, and that they are not all the same. That kind of test also catches subtle bugs, such as an off-by-one length.

Handling secrets carefully

Do not print generated passwords in logs, error messages or debugging output, and do not save them in plain text. Show a password once, to the person who needs it, and store only a salted hash, as the authentication lessons on any web framework will explain.

Syntax

The general shape of the statements in this lesson.

syntax.py
secrets.choice(pool)                        # one secure character
secrets.randbelow(n), secrets.token_urlsafe(16)
secrets.SystemRandom().shuffle(chars)       # secure shuffle
string.ascii_lowercase, string.digits       # ready-made pools
"".join(c for c in pool if c not in LOOK_ALIKE)
[secrets.choice(p) for p in pools]          # one of each type
length * math.log2(pool_size)               # bits of entropy
any(c.isdigit() for c in pw)                # rule checks
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A generator that guarantees every type

Intermediate

Build pools without look-alike characters, write a generator that guarantees one character of each type, and check its properties over many runs without printing any password.

Python
import math
import secrets
import string

LOOK_ALIKE = set("O0Il1")
POOLS = {
    "lower": "".join(c for c in string.ascii_lowercase if c not in LOOK_ALIKE),
    "upper": "".join(c for c in string.ascii_uppercase if c not in LOOK_ALIKE),
    "digit": "".join(c for c in string.digits if c not in LOOK_ALIKE),
    "symbol": "!#$%&*+-=?@",
}
ALL = "".join(POOLS.values())

def password(length: int = 14) -> str:
    if length < len(POOLS):
        raise ValueError(f"length must be at least {len(POOLS)}")
    chars = [secrets.choice(pool) for pool in POOLS.values()]
    chars += [secrets.choice(ALL) for _ in range(length - len(POOLS))]
    secrets.SystemRandom().shuffle(chars)
    return "".join(chars)

made = [password(14) for _ in range(500)]
print("pool sizes:", {name: len(pool) for name, pool in POOLS.items()})
print("all length 14:", all(len(p) == 14 for p in made))
print("every type in every password:", all(any(c in pool for c in p) for p in made for pool in POOLS.values()))
print("no look-alikes:", not any(c in LOOK_ALIKE for p in made for c in p))
print("all different:", len(set(made)) == len(made))
print(f"strength: about {14 * math.log2(len(ALL)):.0f} bits")
try:
    password(3)
except ValueError as error:
    print("error:", error)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The guaranteed characters come first and the shuffle mixes them in, so every password passes the rules without a retry loop. The test lines check properties across 500 passwords instead of comparing with a fixed value, which is the only way to test random output. Nothing in the output reveals a password, yet it proves the generator behaves.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Using random for passwords

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
import random
random.seed(42)
first = ''.join(random.choice('abcdef') for _ in range(8))
random.seed(42)
print(first == ''.join(random.choice('abcdef') for _ in range(8)))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints True: the same seed gives the same password, so it can be reproduced by anyone who knows the seed

Write this instead

import secrets
password = ''.join(secrets.choice('abcdef') for _ in range(8))
print(len(password))

Why it happens

random is a deterministic formula designed for simulations, not a source of unpredictable values.

In the real world

Where this shows up in software people use every day.

  1. First-day passwords for new staff

    IT administration

    An IT team creates accounts for new starters every Monday. A script makes a one-time password for each person, checks it against the company policy, and prints only a confirmation, while the passwords themselves go straight to a secure handover system.

    Why Python fits

    The policy lives in one dictionary that both the generator and the checker read, so they cannot drift apart. The script proves each password meets the policy without ever printing one; in a real system the handover dictionary would be sent to a secure channel and then discarded.

    Python
    import secrets
    import string
    
    POLICY = {"length": 16, "needs": [string.ascii_lowercase, string.ascii_uppercase, string.digits, "!#$%&*?@"]}
    POOL = "".join(POLICY["needs"])
    
    def one_time_password():
        chars = [secrets.choice(group) for group in POLICY["needs"]]
        chars += [secrets.choice(POOL) for _ in range(POLICY["length"] - len(chars))]
        secrets.SystemRandom().shuffle(chars)
        return "".join(chars)
    
    def meets_policy(pw):
        return len(pw) == POLICY["length"] and all(any(c in group for c in pw) for group in POLICY["needs"])
    
    handover = {}
    for user in ["a.khan", "b.lopez", "c.osei"]:
        handover[user] = one_time_password()
        print(f"{user:<8} created, meets policy: {meets_policy(handover[user])}")
    print("distinct passwords:", len(set(handover.values())) == len(handover))
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Does removing look-alike characters weaken passwords much?

Very little. Dropping five characters from a pool of about 70 costs well under one bit per character, which one extra character more than makes up for.

Why not keep generating until a password passes the rules?

It works, and the result is still secure. Building the guarantee in is simply more direct and always takes the same time, which makes it easier to reason about.

How long should a generated password be?

For accounts that matter, 14 to 16 random characters, or five or six random words, is a sensible default. Longer is better when a password manager does the typing.

Can I seed secrets to make my tests repeatable?

No, and that is the point: secrets cannot be seeded. Test properties instead, or pass a choice function into your code so a test can supply a predictable one.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 8 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.