Public-Key Cryptography
Key pairs, asymmetric encryption, and the key exchange problem
Skills taught: crypto.public-key
The Key Distribution Problem
Symmetric encryption is fast and secure, but requires sharing a secret key. How do you share that key securely? You can't send it over an insecure channel — that defeats the purpose. Public-key cryptography solves this by allowing parties to establish a shared secret without having communicated privately before.
- Public Key
- Can be freely distributed to anyone. Used to encrypt data for the owner, or to verify a signature the owner made.
- Private Key
- Must remain secret. Used to decrypt data encrypted with the matching public key, or to create a digital signature.
- Key Pair
- A mathematically linked pair of public and private keys. Data encrypted with one can only be decrypted with the other.
RSA Key Pair Generation and Encryption
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes, serialization
import os
# --- Generate key pair ---
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
public_key = private_key.public_key()
# --- Export public key (share this openly) ---
pem_pub = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
print(pem_pub.decode()) # -----BEGIN PUBLIC KEY-----
# --- Encrypt with public key (anyone can do this) ---
message = b"AES session key: " + os.urandom(32) # 32-byte session key
ciphertext = public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# --- Decrypt with private key (only you can do this) ---
plaintext = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print("Decrypted:", plaintext)
Warning: Never use RSA with PKCS1v15 padding for encryption — it is vulnerable to Bleichenbacher's attack. Always use OAEP padding (RSA-OAEP) for encryption, and PSS padding (RSA-PSS) for signing.
Hybrid Encryption: The Real-World Pattern
RSA can only encrypt small amounts of data (up to ~190 bytes for a 2048-bit key with OAEP). Real systems use hybrid encryption: use RSA to encrypt a random AES key, then use AES-GCM to encrypt the actual data.
from cryptography.hazmat.primitives.asymmetric import padding as asym_padding
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives import hashes
import os
def hybrid_encrypt(public_key, plaintext: bytes) -> dict:
# 1. Generate a random symmetric session key
session_key = AESGCM.generate_key(256)
nonce = os.urandom(12)
# 2. Encrypt the data with the session key (fast AES)
aesgcm = AESGCM(session_key)
ciphertext = aesgcm.encrypt(nonce, plaintext, None)
# 3. Encrypt the session key with RSA (slow, but only 32 bytes)
encrypted_key = public_key.encrypt(
session_key,
asym_padding.OAEP(
mgf=asym_padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return {"encrypted_key": encrypted_key, "nonce": nonce, "ciphertext": ciphertext}
# Recipient decrypts the session key with their private key, then decrypts data with AES
Symmetric vs Asymmetric Encryption
- Symmetric (AES-GCM): Same key for encryption and decryption
- Asymmetric (RSA, ECDH): Public key encrypts; private key decrypts
Tip: In practice, asymmetric cryptography is used only to establish a shared session key. Once both parties have the session key, all further communication uses fast symmetric encryption (AES-GCM).
Frequently Asked Questions
Can asymmetric encryption be used to encrypt large files?
No. RSA can encrypt at most ~190 bytes (2048-bit key with OAEP). For large files, use hybrid encryption: RSA encrypts a random AES-256 key, AES-GCM encrypts the file.
Is it safe to publish my public key?
Yes — that is the whole point. The public key is designed to be shared openly. Security depends entirely on keeping the private key secret.
What is key escrow?
Giving a copy of a private key to a third party (government, employer) for law enforcement or recovery purposes. It is controversial because it creates a target for attackers and undermines end-to-end encryption.