Lesson 8 of 15

RSA Cryptosystem

RSA Cryptosystem

RSA (Rivest–Shamir–Adleman, 1977) is the most widely deployed public-key cryptosystem. Its security rests on the integer factorization problem — factoring large numbers is believed to be computationally infeasible.

Key Generation

  1. Choose two distinct primes pp and qq
  2. Compute n=pqn = p \cdot q (the modulus)
  3. Compute φ(n)=(p1)(q1)\varphi(n) = (p-1)(q-1) (Euler's totient)
  4. Choose ee coprime to φ(n)\varphi(n) (the public exponent; common choice: e=65537e = 65537)
  5. Compute de1(modφ(n))d \equiv e^{-1} \pmod{\varphi(n)} (the private exponent)

Public key: (e,n)(e, n) · Private key: (d,n)(d, n)

Encryption and Decryption

encrypt(m)=memodn\text{encrypt}(m) = m^e \bmod n decrypt(c)=cdmodn\text{decrypt}(c) = c^d \bmod n

Why It Works

By Euler's theorem: mφ(n)1(modn)m^{\varphi(n)} \equiv 1 \pmod{n}, so:

cd=(me)d=med=m1+kφ(n)=m(mφ(n))km(modn)c^d = (m^e)^d = m^{ed} = m^{1 + k\varphi(n)} = m \cdot (m^{\varphi(n)})^k \equiv m \pmod{n}

Classic Example

p=61p = 61, q=53q = 53, e=17e = 17:

  • n=3233n = 3233
  • φ(n)=3120\varphi(n) = 3120
  • d=171mod3120=2753d = 17^{-1} \bmod 3120 = 2753

Encrypt 42: 4217mod3233=255742^{17} \bmod 3233 = 2557 Decrypt 2557: 25572753mod3233=422557^{2753} \bmod 3233 = 42

Your Task

Implement:

  • rsa_keypair(p, q, e)(n, e, d)
  • rsa_encrypt(m, e, n) — returns memodnm^e \bmod n
  • rsa_decrypt(c, d, n) — returns cdmodnc^d \bmod n

Use Python's built-in pow(base, exp, mod) for efficient modular exponentiation.

Python runtime loading...
Loading...
Click "Run" to execute your code.