RSA (Rivest–Shamir–Adleman) is a widely used public-key cryptosystem that allows secure data transmission. It relies on the mathematical difficulty of factoring large integers, particularly the product of two large prime numbers.
Here’s a step-by-step explanation of how RSA encryption and decryption work:
🔐 1. Key Generation
RSA uses a pair of keys:
- Public Key: Used for encryption (shared openly)
- Private Key: Used for decryption (kept secret)
Step 1: Choose Two Large Prime Numbers
- Pick two distinct large prime numbers,
p and q.
Step 2: Compute the Modulus n
- Compute:
n=p×q
This value
n is used as the modulus for both the public and private keys.
Step 3: Compute Euler's Totient Function φ(n)
- Compute:
ϕ(n)=(p−1)(q−1)
Step 4: Choose Public Exponent e
Step 5: Compute Private Exponent d
- Find
d such that:
d⋅e≡1modϕ(n)
That means d is the modular multiplicative inverse of e modulo ϕ(n).
This can be done using the Extended Euclidean Algorithm.
Final Keys:
- Public Key: (n,e)
- Private Key: (n,d)
📤 2. Encryption
To encrypt a message M (which must be a number less than n), use the recipient’s public key (n,e):
C=Memodn
Where:
C is the encrypted ciphertext
M is the original plaintext message (as an integer)
📥 3. Decryption
To decrypt the ciphertext C, use the private key (n,d):
M=Cdmodn
This recovers the original message M.
✅ Why It Works
RSA works due to properties of modular exponentiation and Euler's theorem:
- The exponents
e and d are inverses modulo ϕ(n), so:
(Me)d≡
provided and are coprime, which is generally true unless is one of or .
Even if an attacker knows n, e, and C, computing d requires factoring n into its primes p and q, which is computationally infeasible for sufficiently large n.
🔒 Security Considerations
- Key Size: As of today, 2048-bit keys are considered secure; 1024-bit keys are no longer recommended.
- Padding Schemes: Raw RSA is vulnerable to several attacks. Real-world implementations use padding schemes like OAEP (for encryption) or PSS (for signatures).
- Side-channel Attacks: Timing, power consumption, etc., may leak information about the private key.
🧮 Example (Small Numbers for Illustration)
Let’s say Alice wants to generate RSA keys:
-
Choose primes:
p=61,q=53
-
Compute:
n=61×53=3233
-
Compute:
Now:
- Public Key: (3233, 17)
- Private Key: (3233, 2753)
If Bob wants to send message M = 123:
- Encrypt:
C=12317mod3233=855
Alice decrypts:
- Decrypt:
M=8552753mod3233=123
✅ Message recovered!
Summary
| Step | Description |
|---|
| Key Gen | Choose primes p, q; compute n, φ(n); choose e, find d |
| Encryption | C=Memodn |
| Decryption | |
Let me know if you'd like a Python implementation or deeper math!