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
stringmodule has letters, digits and symbols ready. Drop look-alikes such as O and 0.Pick securely
secrets.choicedraws 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
log2of 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
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.
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)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.
- pw = "Rain7"
- checks = []
- checks.append(len(pw) >= 8)
- checks.append(any(c.isdigit() for c in pw))
- checks.append(any(c.isupper() for c in pw))
- score = sum(checks)
- 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 notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
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
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
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.
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)Press Run to see what it prints.Predict first
How it works(open after your guess)
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.
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)))Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- IT administration
First-day passwords for new staff
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
handoverdictionary would be sent to a secure channel and then discarded.Pythonimport 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))OutputPress 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?
Why not keep generating until a password passes the rules?
How long should a generated password be?
Can I seed secrets to make my tests repeatable?
Your notes
Sign in to keep private notes alongside this lesson.
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.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
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.