Lesson 10 of 10
Practice & Quiz - Cryptography & PKI
Test your cryptography knowledge: symmetric vs asymmetric encryption, hashing, digital signatures, TLS handshake, and PKI with a practical Python cryptography exercise and 5 quiz questions.
Practical Exercise - Applied Cryptography in Python
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.asymmetric import rsa, padding as asym_padding
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.backends import default_backend
from cryptography.x509 import (
CertificateBuilder, NameAttribute, random_serial_number,
BasicConstraints,
)
from cryptography.x509.oid import NameOID
from cryptography import x509
import os, base64, hashlib, datetime, bcrypt, hmac
# ─── 1. AES-256-GCM: Authenticated Encryption ────────────────
# GCM (Galois/Counter Mode): provides both confidentiality AND integrity
# If ciphertext is tampered → decryption raises InvalidTag exception
def encrypt_aes_gcm(plaintext: bytes, associated_data: bytes = b'') -> dict:
"""Encrypt with AES-256-GCM. Returns key, nonce, ciphertext+tag."""
key = AESGCM.generate_key(bit_length=256) # 32 random bytes
nonce = os.urandom(12) # 96-bit nonce (GCM standard)
aesgcm = AESGCM(key)
# associated_data: authenticated but NOT encrypted (e.g., user_id, version)
ciphertext = aesgcm.encrypt(nonce, plaintext, associated_data)
return {'key': key, 'nonce': nonce, 'ciphertext': ciphertext}
def decrypt_aes_gcm(key, nonce, ciphertext, associated_data=b'') -> bytes:
return AESGCM(key).decrypt(nonce, ciphertext, associated_data)
msg = b'Sensitive customer data: SSN 123-45-6789'
enc = encrypt_aes_gcm(msg, associated_data=b'user_id:42')
print(f'Encrypted: {base64.b64encode(enc["ciphertext"]).decode()[:50]}...')
decrypted = decrypt_aes_gcm(enc['key'], enc['nonce'], enc['ciphertext'], b'user_id:42')
print(f'Decrypted: {decrypted.decode()}')
# ─── 2. RSA-4096: Asymmetric Encryption for Key Exchange ─────
# Rule: only use asymmetric encryption to encrypt symmetric keys (never large data)
private_key = rsa.generate_private_key(public_exponent=65537, key_size=4096)
public_key = private_key.public_key()
# Hybrid encryption: encrypt AES key with RSA public key
aes_key = enc['key']
encrypted_key = public_key.encrypt(
aes_key,
asym_padding.OAEP(
mgf=asym_padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None,
)
)
decrypted_key = private_key.decrypt(
encrypted_key,
asym_padding.OAEP(mgf=asym_padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(), label=None)
)
print(f'\nRSA key exchange: keys match = {aes_key == decrypted_key}')
# ─── 3. ECDSA Digital Signatures ─────────────────────────────
# Elliptic Curve: smaller keys, faster than RSA, same security
ec_private = ec.generate_private_key(ec.SECP256R1()) # P-256 curve
ec_public = ec_private.public_key()
message = b'Transfer $10,000 from account A to B | timestamp=2024-01-01T10:00:00Z'
signature = ec_private.sign(message, ec.ECDSA(hashes.SHA256()))
# Verify - raises exception if invalid
try:
ec_public.verify(signature, message, ec.ECDSA(hashes.SHA256()))
print(f'Signature VALID for: {message[:50].decode()}...')
except Exception as e:
print(f'Signature INVALID: {e}')
# Tamper detection
tampered = message + b' | extra=malicious'
try:
ec_public.verify(signature, tampered, ec.ECDSA(hashes.SHA256()))
except Exception:
print('Tampered message: signature REJECTED')
# ─── 4. Password Hashing with bcrypt ─────────────────────────
password = b'user_password_123'
salt = bcrypt.gensalt(rounds=12) # cost factor: 2^12 = 4096 iterations
hashed = bcrypt.hashpw(password, salt)
print(f'\nbcrypt hash: {hashed.decode()}')
print(f'Verify: {bcrypt.checkpw(password, hashed)}')
print(f'Wrong pw: {bcrypt.checkpw(b"wrong", hashed)}')
# ─── 5. HMAC for API request signing ─────────────────────────
api_secret = os.urandom(32)
payload = b'GET /api/users?page=1 timestamp=1704067200'
mac = hmac.new(api_secret, payload, hashlib.sha256).hexdigest()
print(f'\nHMAC-SHA256: {mac}')
# Constant-time comparison prevents timing attacks
def verify_hmac(secret, payload, received_mac):
expected = hmac.new(secret, payload, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, received_mac) # constant-time!
print(f'HMAC valid: {verify_hmac(api_secret, payload, mac)}')Module Quiz
Why is AES-GCM preferred over AES-CBC for modern encryption?
Tip
Tip
Practice Practice Quiz Cryptography PKI in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).
Practice Task
Note
Practice Task - (1) Write a working example of Practice Quiz Cryptography PKI from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Practice Quiz Cryptography PKI is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.
Finished this lesson?