Lab 14: Security Hardening

Time: 60 minutes | Level: Architect | Docker: docker run -it --rm python:3.11-slim bash

Overview

Production Python services must handle secrets safely, use constant-time comparisons, implement proper cryptography, and protect against deserialization attacks. This lab covers the full security hardening spectrum.

Prerequisites

pip install cryptography

Step 1: secrets Module — Cryptographically Secure Randomness

import secrets
import string

# Never use random module for security-sensitive values!
# import random  # WRONG for secrets

# Token generation
print("=== Secure Token Generation ===")
print(f"token_bytes(16): {secrets.token_bytes(16).hex()}")
print(f"token_hex(16):   {secrets.token_hex(16)}")      # 32 hex chars
print(f"token_urlsafe(16): {secrets.token_urlsafe(16)}")  # URL-safe base64

# API key generation
def generate_api_key(prefix: str = "sk") -> str:
    """Generate a Stripe-style API key."""
    token = secrets.token_urlsafe(32)
    return f"{prefix}_{token}"

print(f"\nAPI key: {generate_api_key('sk')}")
print(f"API key: {generate_api_key('pk')}")

# Secure random password
def generate_password(length: int = 16) -> str:
    alphabet = string.ascii_letters + string.digits + "!@#$%^&*"
    while True:
        pwd = ''.join(secrets.choice(alphabet) for _ in range(length))
        # Ensure complexity requirements
        has_upper = any(c.isupper() for c in pwd)
        has_digit = any(c.isdigit() for c in pwd)
        has_special = any(c in "!@#$%^&*" for c in pwd)
        if has_upper and has_digit and has_special:
            return pwd

print(f"Password: {generate_password(20)}")

# Secure comparison token (for URL-safe tokens)
def generate_csrf_token() -> str:
    return secrets.token_urlsafe(32)

token = generate_csrf_token()
print(f"CSRF token (length={len(token)}): {token[:20]}...")

💡 secrets.token_urlsafe(n) generates n bytes of randomness encoded as URL-safe base64. The resulting string is approximately n * 4/3 characters long.

Step 2: hmac.compare_digest — Timing-Safe Comparison

Step 3: hashlib — sha3_256 and blake2b

Step 4: Fernet Symmetric Encryption

📸 Verified Output:

Step 5: RSA Asymmetric Encryption

Step 6: X25519 ECDH Key Exchange

Step 7: Safe Deserialization — Restricting Unpickler

Step 8: Capstone — Encrypted Configuration Manager

📸 Verified Output:

Summary

Concept
API
Use Case

Secure randomness

secrets.token_bytes/hex/urlsafe

API keys, tokens, passwords

Timing-safe compare

hmac.compare_digest

Token/signature verification

Modern hashing

hashlib.sha3_256, blake2b

File integrity, fingerprints

Symmetric encryption

cryptography.fernet.Fernet

Encrypt config, data at rest

Key rotation

MultiFernet

Zero-downtime key rotation

RSA signing

private_key.sign/verify

Message authentication

ECDH key exchange

X25519PrivateKey.exchange

End-to-end encryption

Safe unpickling

RestrictedUnpickler

Protect against pickle exploits

Encrypted config

Custom SecureConfigManager

Production secrets management

Last updated