Build a Python Password Generator That Creates Truly Random Passwords (Full Code Included)
Every security guide tells you to use long, unique, random passwords. But how do you actually generate one — and how do you know the generator itself is trustworthy? Today we’ll build a proper password generator in Python, and learn the one mistake that makes most homemade generators insecure.
The Mistake: random vs secrets
Python has two random-number modules, and mixing them up is a real security bug. The random module is designed for games and simulations — its output is predictable if an attacker learns enough of it. The secrets module is designed for security: it draws from your operating system’s cryptographic random source, the same source that generates your encryption keys. For passwords, tokens and anything security-related, always use secrets.
The Code
Paste this as one Code block:
import secrets
import string
def generate_password(length=20, use_symbols=True):
"""Generate a cryptographically random password."""
alphabet = string.ascii_letters + string.digits
if use_symbols:
alphabet += "!@#$%^&*()-_=+"
# Guarantee at least one of each required type
password = [
secrets.choice(string.ascii_lowercase),
secrets.choice(string.ascii_uppercase),
secrets.choice(string.digits),
]
if use_symbols:
password.append(secrets.choice("!@#$%^&*()-_=+"))
# Fill the rest randomly
password += [secrets.choice(alphabet)
for _ in range(length - len(password))]
# Shuffle so the guaranteed characters aren't first
secrets.SystemRandom().shuffle(password)
return "".join(password)
def generate_passphrase(words=5):
"""Generate a memorable passphrase from random words."""
wordlist = ["ocean", "rocket", "purple", "guitar", "forest",
"silver", "tiger", "planet", "bridge", "candle",
"hammer", "velvet", "comet", "anchor", "marble"]
return "-".join(secrets.choice(wordlist) for _ in range(words))
if __name__ == "__main__":
print("Password: ", generate_password(20))
print("Passphrase: ", generate_passphrase(5))
How It Works
- secrets.choice() picks each character from a cryptographically secure random source — unpredictable even to an attacker who watches your output.
- Guaranteed character types ensure the password always contains lowercase, uppercase, digits and symbols, so it passes every site’s complexity rules.
- The shuffle step matters. Without it, the first four characters would always follow the same pattern (lower, upper, digit, symbol) — a pattern attackers can exploit. Shuffling removes that leak.
- The passphrase option trades raw randomness for memorability: five random words are easy to remember and still carry around 65 bits of entropy — far stronger than a typical human password.
Try It
Save as genpass.py and run python3 genpass.py. Generate a few passwords and notice how different they look from anything a human would invent — that’s the point. Humans are predictable; secrets isn’t.
Level Up
- Add a strength estimate using the entropy formula from our earlier password checker post.
- Load the wordlist from the EFF’s large wordlist (7,776 words) for real passphrases.
- Store generated passwords in a password manager, never in a text file.
- Never use random for passwords, tokens, OTPs or anything an attacker could profit from guessing.
You just built a tool that does one small thing correctly — and in security, doing the small things correctly is the whole game.



Comments
Post a Comment