9.3 Asymmetric Key Cryptography: Diffie-Hellman & RSA Algorithm
๐ก Core Intuition: The Open Padlock and the Private Keyโ
๐ณ The Everyday Analogy: Padlocks vs Master Keysโ
Imagine Alice wants anyone in the world to be able to send her confidential letters, but she has never met her correspondents:
- The Public Key (The Open Padlock): Alice purchases 10,000 identical open padlocks. She places them in an open crate on her front porch. Anyone can take a padlock, place a confidential message in a metal box, snap Alice's padlock shut, and ship the box to her.
- The Private Key (The Secret Physical Key): Snapping the padlock shut requires no key. But once clicked shut, only Alice holds the unique physical key that can unlock it. Even the person who snapped the lock shut cannot reopen the box!
- The Key Scaling Advantage: In a symmetric system of users, every pair needs a unique secret key, requiring nearly shared keys. In an asymmetric system, each user requires only one key pair, requiring just total keys.
๐ป Bridging to Computer Scienceโ
In network security:
- Asymmetric Key Cryptography (Public Key Cryptography) uses mathematically linked key pairs:
- Public Key (): Distributed openly to the entire world. Used by senders to encrypt data or verify signatures.
- Private Key (): Kept strictly secret by the owner. Used to decrypt ciphertext or generate digital signatures.
- Asymmetric algorithms rely on one-way trapdoor functions: mathematical operations that are trivial to compute in the forward direction, but computationally impossible to reverse unless you possess a secret piece of information (the "trapdoor").
๐Table of Contents
- ๐๏ธ Symmetric vs Asymmetric Cryptography
- ๐ค Diffie-Hellman Key Exchange (1976)
- ๐ The RSA Algorithm (Rivest, Shamir, Adleman - 1977)
- ๐งฎ Complete Numerical Walkthrough: RSA Step-by-Step
- ๐ญ Real-World Production Context: Hybrid Cryptosystems, Forward Secrecy & Post-Quantum Cryptography
- ๐ Numerical Applications & Worked Examples
- ๐ฏ Exam & Interview Pitfall Check
๐๏ธ Symmetric vs Asymmetric Cryptographyโ
Symmetric Key vs Asymmetric Key Cryptography
The fundamental architectural trade-off between algorithmic throughput and key distribution scalability
Symmetric Cryptography (Shared Key)
- โขSingle shared secret key K used for both encryption and decryption.
- โขKey scaling problem: N users require N(N - 1) / 2 shared keys.
- โขBlazing fast: 1,000x to 10,000x faster than asymmetric ciphers.
- โขCannot provide non-repudiation because both parties share the exact same key.
Asymmetric Cryptography (Key Pair)
- โขPublic Key (PK) encrypts; Private Key (SK) decrypts.
- โขScales linearly: N users require exactly 2N keys.
- โขComputationally heavy: based on modular exponentiation and elliptic curves.
- โขProvides non-repudiation and digital identity verification.
๐ค Diffie-Hellman Key Exchange (1976)โ
Published by Whitfield Diffie and Martin Hellman in 1976, Diffie-Hellman (DH) solved the greatest paradox in security history: How can two parties establish a shared secret key over an insecure, publicly monitored channel without transmitting the secret itself?
The Mathematical Foundation: Discrete Logarithm Problem (DLP)โ
Diffie-Hellman relies on modular arithmetic over a large prime with primitive root :
- Computing is computationally easy (via repeated squaring).
- Given and , finding is the Discrete Logarithm Problem, which is computationally intractable for large primes ().
The 4-Step Diffie-Hellman Protocolโ
The Diffie-Hellman Key Exchange Protocol
Space-time protocol exchange establishing a shared symmetric key over an insecure channel
Alice and Bob publicly agree on a large prime p and primitive root generator g.
Step-by-Step Mathematical Walkthroughโ
- Public Agreement: Alice and Bob agree on public parameters: a prime and primitive root .
- Alice's Key Pair: Alice picks a secret random integer () and computes: Alice sends publicly to Bob.
- Bob's Key Pair: Bob picks a secret random integer () and computes: Bob sends publicly to Alice.
- Shared Secret Derivation:
- Alice takes Bob's public value and raises it to her private key :
- Bob takes Alice's public value and raises it to his private key :
An eavesdropper (Eve) watching the wire sees only and . To compute , Eve must solve the Discrete Logarithm Problem to find or , which is mathematically intractable!
The Man-in-the-Middle (MitM) Flaw of Unauthenticated DHโ
Diffie-Hellman provides forward secrecy and secrecy, but zero authentication:
- An active attacker (Eve) sits between Alice and Bob.
- When Alice sends , Eve intercepts it and sends her own public key to Bob.
- When Bob sends , Eve intercepts it and sends her own public key to Alice.
- Alice establishes key with Eve. Bob establishes key with Eve.
- Eve transparently decrypts, reads, alters, and re-encrypts every message between Alice and Bob!
- Remedy: Authenticated Diffie-Hellman (e.g. Ephemeral Elliptic Curve Diffie-Hellman - ECDHE signed with an RSA or ECDSA digital certificate in TLS).
๐ The RSA Algorithm (Rivest, Shamir, Adleman - 1977)โ
RSA was the first practical public-key cryptosystem capable of both encryption and digital signatures.
The Mathematical Foundation: Euler's Totient Theoremโ
Let be the product of two large prime numbers. Euler's Totient Function counts integers up to relatively prime to :
Euler's Theorem states that for any integer relatively prime to :
Therefore, for any integer :
If we choose exponents and such that , then:
The 5-Step RSA Key Generation Algorithmโ
| Step Number | Mathematical Operation | Rule / Formula |
|---|---|---|
| Step 1 | Choose two large distinct primes | and (typically 1024 or 2048 bits each). |
| Step 2 | Compute the modulus | . ( is made public). |
| Step 3 | Compute Euler's Totient | . (Kept strictly secret). |
| Step 4 | Choose public exponent | Select such that and . (Industry standard: ). |
| Step 5 | Compute private exponent | Compute modular multiplicative inverse using Extended Euclidean Algorithm: . |
- Public Key: (Shared with everyone).
- Private Key: (Kept secret; and are discarded or destroyed).
Encryption and Decryption Formulasโ
๐งฎ Complete Numerical Walkthrough: RSA Step-by-Stepโ
Let us execute the complete RSA algorithm using small prime numbers:
Step 1: Key Generationโ
- Choose primes: .
- Compute modulus:
- Compute Totient:
- Choose public exponent :
- Must satisfy . Let us pick (since ).
- Compute private exponent :
- .
- We need an integer such that :
- If
- If
- If
- If
- If !
- Therefore, .
Step 2: Encryptionโ
Alice wishes to send the plaintext message to Bob using Bob's public key :
Step 3: Decryptionโ
Bob receives ciphertext and decrypts it using his private key :
Using modular exponentiation:
- Repeating squaring across the binary decomposition of :
- The final result evaluates to:
The decrypted plaintext matches the original message identically!
Security Basis: The Integer Factorization Problemโ
Why can an attacker not calculate from the public key ?
- To find , the attacker must compute .
- To compute , the attacker must know and .
- To find and , the attacker must factor .
- For a modulus , the best known classical factoring algorithm (the General Number Field Sieve) would require billions of years of supercomputer computation!
๐ญ Real-World Production Context: Hybrid Cryptosystems, Forward Secrecy & Post-Quantum Cryptographyโ
1. Hybrid Cryptography in Production (TLS & SSH)โ
Why does HTTPS never encrypt full web pages directly using RSA?
- Computational Overhead: Asymmetric modular exponentiation () requires heavy multi-precision arithmetic. RSA is roughly than symmetric AES in software and slower than hardware AES-NI.
- Message Size Limit: Standard RSA can only encrypt messages strictly smaller than its modulus size (). Encrypting a video would require thousands of individual RSA blocks.
- The Production Solution (Hybrid Cryptography):
- The client and server execute an asymmetric handshake (ECDHE / RSA) to mutually authenticate and agree upon a single temporary, high-entropy 256-bit symmetric key.
- All bulk application data (HTML, video, images) is encrypted using high-speed symmetric AES-256-GCM or ChaCha20-Poly1305.
2. Perfect Forward Secrecy (PFS) via Ephemeral Diffie-Hellman (ECDHE)โ
In legacy TLS 1.2, clients encrypted the symmetric pre-master secret using the server's static RSA public key.
- The Retrospective Wiretap Threat: Intelligence agencies or attackers record and store millions of encrypted HTTPS sessions across fiber taps. If the server's private RSA key is compromised, leaked, or subpoenaed 5 years later, the adversary can decrypt every historical recording retroactively!
- TLS 1.3 Mandate: TLS 1.3 completely banned static RSA key exchanges. It mandates Ephemeral Diffie-Hellman (ECDHE):
- For every new connection, both endpoints generate fresh, temporary private keys that are erased from RAM immediately after the session key is derived.
- Even if the server's long-term certificate private key is stolen later, historical recorded sessions remain mathematically unbreakable.
3. The Quantum Threat & NIST Post-Quantum Cryptography (PQC)โ
In 1994, Peter Shor formulated Shor's Algorithm:
- On a sufficiently large, fault-tolerant quantum computer, Shor's algorithm factors integers and calculates discrete logarithms in polynomial time , instantaneously breaking RSA, Diffie-Hellman, and Elliptic Curve Cryptography (ECDSA/ECDH)!
- In 2024, NIST officially standardized the first Post-Quantum Cryptography (PQC) standards based on high-dimensional lattice mathematics:
- ML-KEM (Kyber / FIPS 203): Key Encapsulation Mechanism replacing Diffie-Hellman/RSA key exchange.
- ML-DSA (Dilithium / FIPS 204): Digital signature algorithm replacing RSA/ECDSA signatures.
- Cloudflare, Google Chrome, and Apple iMessage already deploy hybrid Post-Quantum TLS (X25519 + Kyber768) to protect current communications against "Harvest Now, Decrypt Later" adversaries.
๐ Numerical Applications & Worked Examplesโ
Example 1: Full RSA Cryptosystem Mathematical Traceโ
Problem Statement: In an RSA cryptosystem, the prime numbers are chosen as and . The public exponent is selected as .
- Compute the modulus , totient , and derive the private key exponent using the Extended Euclidean Algorithm.
- Encrypt the plaintext message .
- Show the complete decryption calculation confirming recovery of the plaintext.
Step-by-Step Solution:
- Key Generation:
- Modulus:
- Euler's Totient:
- Public exponent . Check (valid).
- Derive private exponent :
- Public Key:
- Private Key:
- Encryption ():
- Break down exponent via repeated squaring:
- Decryption (): The decrypted plaintext matches the original message identically!
Example 2: Diffie-Hellman Key Exchange with Man-in-the-Middle Interceptionโ
Problem Statement: Alice and Bob agree on public parameters (prime modulus) and (primitive root).
- Alice picks private secret .
- Bob picks private secret .
- Calculate Alice's public value and Bob's public value .
- Compute the shared secret key derived by Alice and Bob.
- Suppose an active adversary (Mallory) intercepts the transmission and substitutes her own private secret . Trace how Mallory creates two independent shared keys.
Step-by-Step Solution:
- Public Values:
- Alice computes:
- Bob computes:
- Shared Secret Key Derivation:
- Alice computes with Bob's public :
- Bob computes with Alice's public :
- Man-in-the-Middle Attack:
- Mallory intercepts and . She computes her public value:
- Mallory sends to both Alice and Bob.
- Key with Alice: .
- Key with Bob: .
- Mallory decrypts Alice's traffic with Key 2, reads the plaintext, re-encrypts it with Key 9, and forwards it to Bob undetected, proving why Diffie-Hellman requires digital signatures (PKI) for authentication!
Example 3: High-Speed Modular Exponentiation via Square-and-Multiplyโ
Problem Statement: In RSA and Diffie-Hellman operations, computing modular exponentiations naively by multiplying by itself times requires astronomical CPU time and produces gigabyte-sized intermediate products that overflow hardware registers.
- Compute using the formal Square-and-Multiply (Binary Exponentiation) algorithm.
- Formulate the binary representation of exponent .
- Trace each intermediate squaring and multiplication step modulo 100.
- Calculate the total number of modular operations required versus naive multiplication, and analyze the asymptotic complexity for a 2048-bit RSA key.
Step-by-Step Solution:
- Binary Representation of Exponent : The binary string has length bits: .
- Step-by-Step Algorithm Trace (Left-to-Right Scan):
We initialize accumulator and process bits from most significant bit () to least significant ():
- Bit (MSB):
- Square:
- Multiply:
- Bit :
- Square:
- Multiply:
- Bit :
- Square:
- Multiply:
- Bit :
- Square:
- Multiply: Bit is 0 Skip multiplication ()
- Bit (LSB):
- Square:
- Multiply:
- Final Output:
- Bit (MSB):
- Complexity & Efficiency Analysis:
- Naive Multiplication: Requires .
- Square-and-Multiply: Requires .
- Scaling to 2048-Bit RSA:
- For a 2048-bit exponent, naive multiplication requires operations (impossible in the lifetime of the universe).
- Square-and-multiply requires at most , completing on modern CPUs in under 1 millisecond!
๐ฏ Exam & Interview Pitfall Checkโ
Question 1: Explain Euler's Totient function and why the security of the RSA cryptosystem relies fundamentally on the computational hardness of integer prime factorization.
Answer:
- Euler's Totient Function :
- counts the number of positive integers less than that are coprime to .
- When is the product of two distinct prime numbers, any multiple of (there are such multiples) or (there are such multiples) shares a factor with .
- By the inclusion-exclusion principle:
- Why Security Relies on Integer Factorization:
- To compute the private key exponent , an adversary must solve , which requires knowing .
- However, calculating requires knowledge of the individual prime factors and .
- The public key announces only the product .
- While multiplying two 1024-bit primes and takes microseconds, factoring a 2048-bit composite number back into and has no known polynomial-time classical algorithm (the General Number Field Sieve takes sub-exponential time , requiring billions of CPU-years).
- Consequently, the private key remains computationally impossible to derive from public information.
Question 2: Explain the Man-in-the-Middle (MitM) attack on the classic Diffie-Hellman Key Exchange protocol. How is this vulnerability mitigated in modern protocols like TLS 1.3?
Answer:
- Diffie-Hellman MitM Attack:
- Classic Diffie-Hellman establishes a shared key based on the mathematical properties of , but it does not authenticate the identities of the participants.
- An active adversary (Eve) intercepts Alice's public value and generates her own private exponent , sending to Bob pretending to be Alice.
- When Bob replies with , Eve intercepts it and generates another private exponent , sending to Alice pretending to be Bob.
- Alice computes shared key . Eve computes the identical key .
- Bob computes shared key . Eve computes the identical key .
- Alice and Bob believe they share a secure connection, but they are actually communicating through Eve, who decrypts Alice's messages with , inspects or alters them, and re-encrypts them with for Bob.
- Mitigation:
- Diffie-Hellman must be paired with Digital Signatures and Public Key Certificates.
- In TLS 1.3, the server sends an ephemeral Diffie-Hellman key share (ECDHE) which it cryptographically signs using its certified private signing key (RSA or ECDSA). The client verifies the signature against the server's trusted X.509 certificate, guaranteeing that the public DH parameter genuinely originated from the authentic server.
- Why can't we use RSA to encrypt a 1 GB movie file directly?:
- Size Constraint: Plaintext must be strictly smaller than the modulus (). For a 2048-bit key, the maximum plaintext block is 256 bytes.
- Performance: Modular exponentiation on multi-thousand-bit numbers requires massive CPU cycles. Encrypting a gigabyte file via RSA would take minutes and burn battery life.
- Hybrid Cryptography: Real-world protocols (TLS, SSH, PGP) use Hybrid Encryption: asymmetric cryptography (RSA/ECDHE) negotiates a lightweight 256-bit symmetric key, and fast symmetric cryptography (AES-GCM) encrypts the bulk payload.
- Why is textbook RSA insecure without padding?: In textbook RSA (), encrypting the same message twice produces the exact same ciphertext. Furthermore, if and is small (), , so and an attacker can recover simply by taking the integer cube root! Production RSA strictly mandates OAEP (Optimal Asymmetric Encryption Padding) to inject randomness.
- Trap: Confusing Private Exponent with Totient : is the modular inverse of modulo . It is calculated via , NOT .
- Trap: Believing Diffie-Hellman Encrypts Data: Diffie-Hellman is strictly a Key Exchange / Key Agreement protocol. It cannot encrypt or decrypt messages directly; it merely establishes a shared symmetric secret key.