Back
+15 XP
Concept

Cryptographically Secure Randomness with secrets

Never use the `random` module for security or tokens because its PRNG is predictable. The `secrets` module uses OS entropy (`/dev/urandom`) 🎲.

python
import secrets

api_key = secrets.token_hex(16)
print(f"Secure Token (32 chars): {api_key} 🎲")

reset_token = secrets.token_urlsafe(16)
print(f"URL Token: {reset_token} 🌐")

# 113. Cryptographically Secure Randomness with secrets Never use the `random` module for security or tokens because its PRNG is predictable. The `secrets` module uses OS entropy (`/dev/urandom`) 🎲. ```python import secrets api_key = secrets.token_hex(16) print(f"Secure Token (32 chars): {api_key} 🎲") reset_token = secrets.token_urlsafe(16) print(f"URL Token: {reset_token} 🌐") ``` Use `secrets.choice(['admin', 'user'])` when picking security roles or generating random passphrases from wordlists! 🎲 --- ### Question Why must the `random` module never be used to generate authentication tokens or session IDs? 🧠 - [ ] a. Its internal Mersenne Twister state can be reverse-engineered from previous outputs 🎲 - [ ] b. It can only generate numbers up to 100 - [ ] c. It requires root privileges on Linux - [ ] d. It prints tokens to the terminal by default --- ### Challenge Import `secrets`. Generate a 16-byte hex token with `secrets.token_hex(16)`. Print whether its string length is `32`. 🎯 <details> <summary>Solution</summary> ```python import secrets token = secrets.token_hex(16) print(len(token) == 32) ``` </details>

Checkpoint

Why must the `random` module never be used to generate authentication tokens or session IDs? 🧠

Practice

Import `secrets`. Generate a 16-byte hex token with `secrets.token_hex(16)`. Print whether its string length is `32`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks