Python cryptography Library Overview
Set up hazmat and high-level primitives; understand the library structure.
Python cryptography Library Overview is a free Cryptology Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Cryptology Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Use the cryptography Library?
The Python cryptography library (by PyCA) provides both a high-level Fernet interface and low-level hazmat primitives. It wraps OpenSSL and is the community standard for production crypto in Python.
Installation and Structure
Install: pip install cryptography. Two layers: cryptography.fernet (safe, opinionated symmetric encryption) and cryptography.hazmat.primitives (AES, RSA, EC, hashes, HMAC — use with care).
Fernet: Safe Symmetric Encryption
Fernet uses AES-128-CBC + HMAC-SHA256 with a timestamp. It handles IV generation, padding, and MAC automatically. Perfect for encrypting config values, tokens, or small blobs.
from cryptography.fernet import Fernet
# Generate a URL-safe base64-encoded 32-byte key
key = Fernet.generate_key()
f = Fernet(key)
token = f.encrypt(b"my secret data")
print("Encrypted:", token[:40], "...")
plain = f.decrypt(token)
print("Decrypted:", plain)Hazmat Primitives: Hashes
The hazmat layer provides SHA-2, SHA-3, BLAKE2, and more:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
digest.update(b"Hello, ")
digest.update(b"world!")
result = digest.finalize()
print("SHA-256:", result.hex())Hazmat Primitives: HMAC
HMAC for message authentication:
from cryptography.hazmat.primitives import hmac, hashes
import os
key = os.urandom(32)
h = hmac.HMAC(key, hashes.SHA256())
h.update(b"authenticated message")
signature = h.finalize()
print("HMAC-SHA256:", signature.hex())
# Verify
h2 = hmac.HMAC(key, hashes.SHA256())
h2.update(b"authenticated message")
h2.verify(signature) # raises if invalidKey Serialisation
Serialise keys to PEM/DER for storage or transmission:
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.BestAvailableEncryption(b"passphrase")
)
print(pem[:60])Loading Keys from PEM
Load a PEM key from disk:
from cryptography.hazmat.primitives.serialization import load_pem_private_key
with open("private_key.pem", "rb") as f:
pem_data = f.read()
key = load_pem_private_key(pem_data, password=b"passphrase")
print("Key loaded, size:", key.key_size, "bits")X.509 Certificate Handling
Parse and inspect TLS certificates:
from cryptography import x509
import datetime
with open("cert.pem", "rb") as f:
cert = x509.load_pem_x509_certificate(f.read())
print("Subject:", cert.subject)
print("Issuer:", cert.issuer)
print("Not valid after:", cert.not_valid_after_utc)
print("Serial:", cert.serial_number)Random Byte Generation
Always use os.urandom or secrets for cryptographic randomness:
import os, secrets
# Cryptographically secure 32-byte key
key = os.urandom(32)
print("Random key:", key.hex())
# secrets module: URL-safe token
token = secrets.token_urlsafe(32)
print("URL-safe token:", token)Avoiding Hazmat Pitfalls
The hazmat API is called "Hazardous Materials" for a reason. Common mistakes: reusing nonces, using ECB mode, skipping authentication tags, comparing MACs with ==. Use high-level APIs when possible.
Knowledge Check
What does Fernet encryption provide that raw AES-CBC alone does not?
Lesson Recap
The cryptography library has two layers: safe Fernet and flexible hazmat. Use Fernet for symmetric encryption, hazmat for AES-GCM, RSA, ECDSA, and certificate handling. Always use os.urandom for keys. Avoid hazmat pitfalls — prefer authenticated modes.
Frequently asked questions
Is the “Python cryptography Library Overview” lesson free?
Yes — the full text of “Python cryptography Library Overview” is free to read here on the web, and the Cryptology Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Cryptology Academy course, upgrade to CoddyKit PRO.
What will I learn in “Python cryptography Library Overview”?
Set up hazmat and high-level primitives; understand the library structure. You practise Cryptology Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Cryptology Academy?
No prior experience is required. Cryptology Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Python cryptography Library Overview” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Cryptology Academy lesson?
Yes. Every Cryptology Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Python cryptography Library Overview
- AES-GCM Encrypt & Decrypt in Python
- RSA & ECDSA Key Pairs in Python
- Common Python Crypto Pitfalls & Secure Patterns