Search Knowledge

© 2026 LIBREUNI PROJECT

RSA Encryption

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:

  1. Choose two large primes pp and qq.
  2. Compute n=pqn = pq. This nn is used as the modulus for both public and private keys.
  3. Compute Euler’s totient function ϕ(n)=(p1)(q1)\phi(n) = (p-1)(q-1).
  4. Choose an integer ee such that 1<e<ϕ(n)1 < e < \phi(n) and gcd(e,ϕ(n))=1\gcd(e, \phi(n)) = 1.
  5. Determine dd as de1(modϕ(n))d \equiv e^{-1} \pmod{\phi(n)}.
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 MM is encrypted into ciphertext CC using the public key (e,n)(e, n): CMe(modn)C \equiv M^e \pmod n

The original message is recovered using the private key (d,n)(d, n): MCd(modn)M \equiv C^d \pmod n

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 MedMkϕ(n)+1M(modn)M^{ed} \equiv M^{k\phi(n) + 1} \equiv M \pmod n. According to Euler’s Totient Theorem, if gcd(M,n)=1\gcd(M, n) = 1, then Mϕ(n)1(modn)M^{\phi(n)} \equiv 1 \pmod n.

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.

Which value is part of the public key?

Finish Course