3 line Python script for generating secure passwords
Sometimes I need a password and I don't have a good way to generate one. Maybe it's a website and Chrome isn't auto-suggesting a password. Maybe it's not a website. Whatever the situation, here's a simple Python script I use to generate a secure password.
#!/usr/bin/env python3
import secrets
# These characters are easily distinguishable, and they don't count as
# separators in iTerm, so you can double-click to copy/paste
alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz~_-+./'
assert len(alphabet) == 64
# log2(64) == 6, so we get 6 bits per char, so 11 chars gives us 66 bits of
# randomness
print(''.join(secrets.choice(alphabet) for i in range(11)))
This is basically just 3 lines of code (plus comments/assertions) so I think it's easy enough to analyze for correctness. It uses secrets as a source for secure randomness.
If you enjoyed this post, please let me know on Twitter or Bluesky.
Posted November 18, 2023.
Tags: #python