1. Introduction to Cryptographically Secure Generation
In modern web applications, generating user reset passwords, API authorization tokens, and encryption keys requires true unpredictability. Standard pseudo-random number generators like Python's random module are deterministic (based on the Mersenne Twister algorithm) and vulnerable to state prediction attacks. For security-sensitive data, production applications must utilize the CSPRNG (Cryptographically Secure Pseudo-Random Number Generator) provided by Python's secrets module, which draws entropy directly from the underlying operating system kernel (/dev/urandom on Linux/macOS or CryptGenRandom on Windows).
2. System Architecture & Generation Workflow
┌────────────────────────────────────────────────────────┐
│ CLI Prompt: What do you want to generate? │
│ Options: [pass] for Password | [keys] for Secret Key │
└──────────────────────────┬─────────────────────────────┘
│
┌────────────────┴────────────────┐
▼ ▼
[Mode: pass (Password)] [Mode: keys (Secret Key)]
Length: 16 to 24 characters Length: 64 up to 256 characters
│ │
▼ ▼
┌───────────────────────────┐ ┌───────────────────────────┐
│ Guarantee Multi-Set Mix: │ │ High-Entropy Keyboard Mix:│
│ • 1+ Lowercase (a-z) │ │ • Lowercase Letters (a-z) │
│ • 1+ Uppercase (A-Z) │ │ • Uppercase Letters (A-Z) │
│ • 1+ Numeric Digit (0-9) │ │ • Numeric Digits (0-9) │
│ • 1+ Special Symbol │ │ • English Keyboard Symbols│
│ CSPRNG Shuffle (secrets) │ │ CSPRNG Shuffle (secrets) │
└─────────────┬─────────────┘ └─────────────┬─────────────┘
│ │
└────────────────┬────────────────┘
▼
┌──────────────────────────────────────────┐
│ 100% Unpredictable High-Entropy Output │
└──────────────────────────────────────────┘
3. Key Differences Between Password and Secret Key Modes
- Password Mode (
pass, 16–24 chars): Ideal for user accounts and credential resets. It balances human readability and password manager compliance while guaranteeing that every character class (uppercase, lowercase, numbers, symbols) is present. - Secret Key Mode (
keys, 64–256 chars): Ideal for FlaskSECRET_KEY, JWT signing secrets, HMAC tokens, and API credentials. It draws from the complete standard English keyboard character set (94 printable ASCII characters) using cryptographically secure CSPRNG selection to achieve maximum entropy.
4. Production Python Implementation (generate_pass.py)
Below is the complete, self-contained Python script implementing both generation modes with input validation:
#!/usr/bin/env python3
import sys
import string
import secrets
# Character Pools (English Keyboard Only)
LOWERCASE = string.ascii_lowercase
UPPERCASE = string.ascii_uppercase
DIGITS = string.digits
KEYBOARD_SYMBOLS = "!@#$%^&*()-_=+[{]}\|;:'\",<.>/?`~"
SYMBOLS = KEYBOARD_SYMBOLS
EXTENDED_SYMBOLS = KEYBOARD_SYMBOLS
ALL_KEYBOARD_CHARS = LOWERCASE + UPPERCASE + DIGITS + KEYBOARD_SYMBOLS
def generate_password(length: int) -> str:
"""Generate a high-strength password between 16 and 24 characters."""
if length < 16 or length > 24:
raise ValueError("Password length must be between 16 and 24 characters.")
all_chars = ALL_KEYBOARD_CHARS
password_chars = [
secrets.choice(LOWERCASE),
secrets.choice(UPPERCASE),
secrets.choice(DIGITS),
secrets.choice(KEYBOARD_SYMBOLS),
]
for _ in range(length - 4):
password_chars.append(secrets.choice(all_chars))
rng = secrets.SystemRandom()
rng.shuffle(password_chars)
return "".join(password_chars)
def generate_secret_key(length: int) -> str:
"""Generate a high-entropy secret key between 64 and 256 characters."""
if length < 64 or length > 256:
raise ValueError("Key length must be between 64 and 256 characters.")
all_chars = ALL_KEYBOARD_CHARS
key_chars = [
secrets.choice(LOWERCASE),
secrets.choice(UPPERCASE),
secrets.choice(DIGITS),
secrets.choice(KEYBOARD_SYMBOLS),
]
for _ in range(length - 4):
key_chars.append(secrets.choice(all_chars))
rng = secrets.SystemRandom()
rng.shuffle(key_chars)
return "".join(key_chars)
if __name__ == "__main__":
mode = input("What do you want to generate? (pass / keys): ").strip().lower()
if mode in ("pass", "password", "p"):
val = input("Enter password length (16-24) [default: 16]: ").strip()
length = int(val) if val else 16
print(f"Generated Password: {generate_password(length)}")
elif mode in ("keys", "key", "k"):
val = input("Enter key length (64-256) [default: 64]: ").strip()
length = int(val) if val else 64
print(f"Generated Secret Key: {generate_secret_key(length)}")
5. Command-Line Execution Examples
Example 1: Generating a 16-Character Secure User Password:
$ python3 password_utils/generate_pass.py
What do you want to generate? (pass / keys): pass
Enter password length (16-24) [default: 16]: 16
✅ Generated Secure Password (16 chars):
👉 Pf27Etm:0p33Tq|H
Example 2: Generating a 64-Character Cryptographic Secret Key:
$ python3 password_utils/generate_pass.py
What do you want to generate? (pass / keys): keys
Enter key length (64-256) [default: 64]: 64
✅ Generated Secret Key (64 chars):
👉 k9#mP$2vL@8xQ!zW^5yR*1tB&7uK~4sJ%0aZ(3cD)6fG_8hN+2jM-5pT=9wY{1bV}4
6. Key Takeaways for Production Security
- Always use
secrets.SystemRandomrather than standardrandom.shuffleorrandom.choicefor cryptographic artifacts. - Never hardcode generated secrets into public repositories — store them in environment variables or cloud secrets vaults.
- Enforce password complexity rules on user registration while offering instant one-click strong generation.