Auth & security at scale
OAuth2, JWT, IAM patterns, secrets rotation, and least-privilege service auth.
AES GCM encryption and decryption in Python
Encrypt and decrypt data with AES-256-GCM using the cryptography library, including nonce generation and authenticated roundtrip verification.
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
def aes_gcm_demo():
plaintext = b"confidential message"
key = AESGCM.generate_key(bit_length=256)
aesgcm = AESGCM(key)
nonce = os.urandom(12)
ciphertext = aesgcm.encrypt(nonce, plaintext, None)
decrypted = aesgcm.dec…
ChaCha20-Poly1305 mock in Python
Simulates ChaCha20-Poly1305 AEAD encryption and authentication using SHA-256 as a deterministic keystream and tag generator.
from hashlib import sha256
import struct
def chacha20_block(key, counter, nonce):
"""Mock ChaCha20 block: deterministic pseudo-random keystream from key+counter+nonce."""
state_input = key + struct.pack("<I", counter) + nonce + b"ChaCha20"
return sha256(state_input).digest()[:64] # 64-byte keystream bloc…
How to Mock KMS Envelope Encryption in Python
Demonstrates a minimal mock of AWS KMS envelope encryption flow with AES-GCM data key wrapping and unwrapping.
import base64
import json
import os
import hashlib
class MockKMS:
"""Minimal mock of AWS KMS envelope encryption flow."""
def generate_data_key(self):
# Simulate KMS returning a plaintext and encrypted data key
plaintext_key = os.urandom(32)
encrypted_key = hashlib.sha256(plaintext_k…
Implement RSA OAEP Padding in Python
Implements OAEP-style padding with MGF1 using SHA-256 from the Python standard library for RSA encryption prep.
import os
import hashlib
def mgf1(seed, length, hash_func=hashlib.sha256):
"""MGF1 mask generation function."""
output = b""
counter = 0
while len(output) < length:
c = counter.to_bytes(4, "big")
output += hash_func(seed + c).digest()
counter += 1
return output[:length]
…
Browse by section
Each section groups closely related Python snippets.
Auth & security at scale — Python code examples
What you will find here
This page collects auth & security at scale snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.