RSA & ECDSA Key Pairs in Python
Generate, serialize, and use RSA and EC keys for signing and encryption.
RSA & ECDSA Key Pairs in Python is a free Cryptology Academy lesson on CoddyKit — lesson 3 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.
Key Pair Operations Overview
Python's cryptography library supports RSA and ECDSA for generating keys, signing, verifying, serialising, and loading. These are the building blocks for TLS certificates, code signing, and JWTs.
Generating an RSA Key Pair
Minimum recommended: 2048-bit for compatibility, 4096-bit for long-lived keys:
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
public_key = private_key.public_key()
print("RSA key generated, size:", private_key.key_size, "bits")RSA Signing with PSS
Always use PSS padding for signatures (not PKCS#1 v1.5):
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
message = b"document to sign"
signature = private_key.sign(
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
print("RSA-PSS signature:", signature.hex()[:32], "...")RSA Signature Verification
Verification raises InvalidSignature on failure:
from cryptography.exceptions import InvalidSignature
try:
public_key.verify(
signature,
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
print("Signature valid!")
except InvalidSignature:
print("Signature INVALID")Generating an ECDSA Key Pair
ECDSA with NIST P-256 (secp256r1) gives 128-bit security with much smaller keys than RSA-3072:
from cryptography.hazmat.primitives.asymmetric import ec
private_key = ec.generate_private_key(ec.SECP256R1())
public_key = private_key.public_key()
print("EC private key generated on curve:", private_key.curve.name)ECDSA Signing and Verification
ECDSA uses DER-encoded signatures by default:
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import hashes
from cryptography.exceptions import InvalidSignature
# Sign
sig = private_key.sign(b"my data", ec.ECDSA(hashes.SHA256()))
print("ECDSA signature bytes:", len(sig))
# Verify
try:
public_key.verify(sig, b"my data", ec.ECDSA(hashes.SHA256()))
print("ECDSA signature valid")
except InvalidSignature:
print("Invalid")Serialising Keys to PEM
Save keys to PEM files for storage or distribution:
from cryptography.hazmat.primitives import serialization
# Private key — encrypted with passphrase
private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.BestAvailableEncryption(b"strong-passphrase")
)
# Public key — no encryption
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
print(public_pem.decode()[:64])Loading Keys from PEM
Load persisted keys back into objects:
from cryptography.hazmat.primitives.serialization import (
load_pem_private_key, load_pem_public_key
)
with open("ec_private.pem", "rb") as f:
priv = load_pem_private_key(f.read(), password=b"strong-passphrase")
with open("ec_public.pem", "rb") as f:
pub = load_pem_public_key(f.read())
print("Loaded EC key curve:", priv.curve.name)ECDH Key Agreement
Use ECDH to derive a shared secret for symmetric encryption:
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
alice_priv = ec.generate_private_key(ec.SECP256R1())
bob_priv = ec.generate_private_key(ec.SECP256R1())
# Alice computes shared secret
shared = alice_priv.exchange(ec.ECDH(), bob_priv.public_key())
aes_key = HKDF(hashes.SHA256(), 32, None, b"app-context").derive(shared)
print("Derived AES key:", aes_key.hex())RSA Encryption with OAEP
For encrypting small payloads (e.g., a DEK) with RSA — always use OAEP:
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
# Encrypt with public key
ciphertext = public_key.encrypt(
b"small secret",
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# Decrypt with private key
plaintext = private_key.decrypt(ciphertext, padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(), label=None
))
print("Decrypted:", plaintext)Choosing RSA vs ECDSA
ECDSA: smaller signatures (~71 bytes for P-256 vs ~256 bytes for RSA-2048), faster signing, same security level. RSA: broader legacy support, simpler mental model. Use ECDSA P-256 or Ed25519 for new systems.
Knowledge Check
Why should RSA-PSS be preferred over PKCS#1 v1.5 for digital signatures?
Lesson Recap
Use rsa.generate_private_key for RSA, ec.generate_private_key for ECDSA. Sign with PSS (RSA) or ECDSA + SHA-256. Serialise to PEM with PKCS8 format and passphrase encryption. Use ECDH for key agreement. Prefer ECDSA P-256 or Ed25519 for new systems.
Frequently asked questions
Is the “RSA & ECDSA Key Pairs in Python” lesson free?
Yes — the full text of “RSA & ECDSA Key Pairs in Python” 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 “RSA & ECDSA Key Pairs in Python”?
Generate, serialize, and use RSA and EC keys for signing and encryption. 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 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “RSA & ECDSA Key Pairs in Python” 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