Three lines, all standard library:
import secrets
import string
alphabet = string.ascii_letters + string.digits + string.punctuation
password = "".join(secrets.choice(alphabet) for _ in range(20))
print(password)
That picks 20 characters, each one independently, from the 94 printable ASCII characters that aren't a space. Run it a few times and you get things like %?Y@FoJ~%,p-;lvL6w$K. Each character can repeat, and that's on purpose. Removing a character once it has been used would make the password easier to guess, not harder.
Why secrets and not random
Half the examples on the internet use random.choice. Don't. The random module is a Mersenne Twister, which is a fine generator for simulations and shuffling a playlist, and it was never meant to keep anything private. Its whole internal state can be rebuilt from 624 outputs in a row, and after that every "random" value it will ever produce is known. The Python docs put a warning box about this at the top of the random page.
The secrets module, in the standard library since Python 3.6, asks the operating system for its randomness instead. That's the same source your TLS keys come from. It costs you nothing to use the right one.
I've been on the wrong side of this myself. The password generators on this site once ran on a generator seeded with about 53 bits. I wrote up what was wrong and how I fixed it.
How strong is it?
Strength is the number of equally likely passwords, measured in bits: length times log2 of the alphabet size. With all 94 characters, each one is worth about 6.55 bits.
- 12 characters: 79 bits
- 16 characters: 105 bits
- 20 characters: 131 bits
- 32 characters: 210 bits
Anything past 100 bits is out of reach of guessing, and going longer costs nothing when a machine is the one typing it. Use 20 for things a person might have to read and 32 for things only software will see. The math only holds because every character is picked uniformly and independently. A password you "improved" by hand has less entropy than the one you started with.
When a password policy wants one of everything
Some systems insist on a lowercase letter, an uppercase letter and a few digits. The tempting fix is to generate a password and then force a digit into position three. That makes position three predictable. Generate, check, and throw the whole thing away if it fails:
import secrets
import string
alphabet = string.ascii_letters + string.digits + string.punctuation
while True:
password = "".join(secrets.choice(alphabet) for _ in range(20))
if (any(c.islower() for c in password)
and any(c.isupper() for c in password)
and sum(c.isdigit() for c in password) >= 3):
break
print(password)
Every password that passes the policy is still equally likely, which is the property you're paying for. With these rules the loop usually goes around two or three times.
Passwords that survive config files and URLs
Punctuation is where generated passwords go to die. An @ or a / breaks a database URL, a $ vanishes inside a double-quoted shell string, and a # starts a comment in half the config formats ever invented. For anything headed into a connection string or a .env file, skip the punctuation and add length:
import secrets
print(secrets.token_urlsafe(24))
token_urlsafe(24) turns 24 random bytes into 32 characters of letters, digits, - and _. That's 192 bits, and nothing in it needs escaping anywhere. It's a good fit for database roles. My Postgres password generator and MySQL password generator do the same job in the browser and write the SQL for you.
From a shell, with nothing to save to a file:
python3 -c "import secrets; print(secrets.token_urlsafe(24))"
For application keys rather than passwords, secrets.token_hex(32) gives you 64 hex characters, which is what a Flask SECRET_KEY wants.
A passphrase instead
If a person has to type the thing, pick words. Same module, same idea, with a word list in place of an alphabet:
import secrets
from pathlib import Path
lines = Path("eff_large_wordlist.txt").read_text(encoding="utf-8").splitlines()
words = [line.split()[-1] for line in lines if line.strip()]
passphrase = " ".join(secrets.choice(words) for _ in range(6))
print(passphrase)
The EFF's long list has 7,776 words, so each word is worth about 12.9 bits. Five words is 65 bits and six is 78, which is plenty for something you memorize. Each line of that file is a dice roll followed by a word, which is why the code keeps only the last thing on the line. If you'd rather not download anything, there's a passphrase generator on this site too.
If your code is the one storing passwords
Generating a strong password is the easy half. If you're building the system that keeps them, a few things are not optional:
- Do not ever store users' passwords as plain text. Ever. I will find your code if you do this, and I will revert your pull request.
- Hash them with something built for passwords: Argon2, scrypt or bcrypt, each with its own random salt. A bare SHA-256 is not a password hash. Python ships
hashlib.scrypt, andargon2-cffiis onepip installaway. - Compare hashes and tokens with
secrets.compare_digest, not==, so the comparison takes the same time whether the first character matches or the last. - Never generate a user's password for them and send it by email. Send a link that expires and let them choose.
- Log failed logins, slow down repeated ones, and tell users when something looks off.
- If any of this is confusing, ask. Go find a more senior developer and ask how they'd do it. Nobody good will think less of you for it.
Good luck and happy passwording!
-Sethers