โมดูล secrets สร้าง Random Numbers แบบ Cryptographically Secure สำหรับ Password, Token, API Key, Session ID ใช้ Entropy จาก OS (os.urandom)
import secrets (Python 3.6+)
Random Numbers
| Function | คำอธิบาย |
secrets.SystemRandom | Class ใช้ OS Random Source (เหมือน random.SystemRandom) |
secrets.choice(seq) | สุ่ม 1 Element จาก Sequence |
secrets.randbelow(n) | สุ่ม Integer [0, n) |
secrets.randbits(k) | สุ่ม Integer k Bits |
Token Generation (ใช้งานบ่อยที่สุด)
| Function | Output | Use Case |
token_bytes([nbytes]) | Bytes (Default 32) | Encryption Keys |
token_hex([nbytes]) | Hex String (2*n chars) | API Keys, CSRF Tokens |
token_urlsafe([nbytes]) | Base64 URL-Safe (~1.3*n chars) | Password Reset URLs, Session IDs |
> **Default nbytes = 32** (256 bits Entropy) ปรับได้ตามความต้องการ
โค้ดตัวอย่าง
import secrets
# 1. Random Password จาก Character Set
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*'
password = ''.join(secrets.choice(chars) for _ in range(16))
print(f"Password: {password}")
# 2. Tokens
print(f"Hex Token (16 bytes): {secrets.token_hex(16)}")
print(f"URL-Safe Token (32 bytes): {secrets.token_urlsafe(32)}")
print(f"Bytes Token (16 bytes): {secrets.token_bytes(16).hex()}")
# 3. Random Integer
print(f"Random [0, 1000): {secrets.randbelow(1000)}")
print(f"Random 128-bit: {secrets.randbits(128)}")
ผลลัพธ์ตัวอย่าง
Password: K9#mP2$vL5@xR7!q
Hex Token (16 bytes): a1b2c3d4e5f678901234567890abcdef
URL-Safe Token (32 bytes): a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6
Bytes Token (16 bytes): a1b2c3d4e5f678901234567890abcdef
Random [0, 1000): 742
Random 128-bit: 12345678901234567890123456789012
Best Practices
- อย่าใช้ random module สำหรับ Security (Predictable)
- Token Length: อย่างน้อย 32 bytes (256 bits) สำหรับ Long-lived Secrets
- Password Reset Token: ใช้
token_urlsafe(32) + Expire ใน 1 ชม.
- API Keys: ใช้
token_hex(32) หรือ token_urlsafe(32)
- Session IDs: ใช้
token_urlsafe(32)
เปรียบเทียบ random vs secrets
| ด้าน | random | secrets |
| Purpose | General Purpose, Simulation | Cryptography, Security |
| Predictability | Predictable (Mersenne Twister) | Unpredictable (OS Entropy) |
| Speed | Fast | Slower (System Calls) |
| Thread Safety | Yes | Yes |