RSA Encryption
RSA (Rivest–Shamir–Adleman) is the algorithmic backbone of modern digital security. It relies on the practical difficulty of factoring the product of two large prime numbers.
1. The Key Generation Process
The security of RSA rests on three main steps:
- Choose two large primes and .
- Compute . This is used as the modulus for both public and private keys.
- Compute Euler’s totient function .
- Choose an integer such that and .
- Determine as .
python
1def gcd(a, b):
2 while b:
3 a, b = b, a % b
4 return a
5
6def extended_gcd(a, b):
7 if a == 0: return b, 0, 1
8 d, x1, y1 = extended_gcd(b % a, a)
9 x = y1 - (b // a) * x1
10 y = x1
11 return d, x, y
12
13def mod_inverse(e, phi):
14 d, x, y = extended_gcd(e, phi)
15 return x % phi
16
17p, q = 61, 53
18n = p * q
19phi = (p-1) * (q-1)
20e = 65537 # Common choice for e
21d = mod_inverse(e, phi)
22
23print(f"Public Key (e, n): ({e}, {n})")
24print(f"Private Key (d, n): ({d}, {n})")
2. Encryption and Decryption
A message is encrypted into ciphertext using the public key :
The original message is recovered using the private key :
python
1# Use the keys from the previous step
2p, q = 61, 53
3n, e = p*q, 65537
4d = 2753 # Computed in step 1
5
6def encrypt(m, e, n):
7 return pow(m, e, n)
8
9def decrypt(c, d, n):
10 return pow(c, d, n)
11
12message = 42
13ciphertext = encrypt(message, e, n)
14decrypted = decrypt(ciphertext, d, n)
15
16print(f"Original: {message}")
17print(f"Encrypted: {ciphertext}")
18print(f"Decrypted: {decrypted}")
3. Why it Works (Euler’s Theorem)
RSA works because . According to Euler’s Totient Theorem, if , then .
What happens if an attacker finds out p and q?
4. Key Takeaways
- One-way function: Multiplication of primes is easy, but factoring their product is hard.
- Asymmetric: You share the public key with everyone but keep the private key secret.