RSA Key Generation

What RSA Does

RSA gives you two keys:

  • Public key: two numbers (e,n)(e, n)
  • Private key: two numbers (d,n)(d, n)

To encrypt a message MM:

C=MemodnC = M^e \mod n

To decrypt ciphertext CC:

M=CdmodnM = C^d \mod n

Raise to a power, take the remainder. That’s it.



Let’s Do It With Real Numbers

Say we have:

ValueNumber
nn55
ee (public exponent)3
dd (private exponent)27

Encrypt the message 2:

23=82^3 = 8

8mod55=88 \mod 55 = 8

Ciphertext is 8.


Decrypt 8:

827mod55=?8^{27} \mod 55 = \text{?}

8278^{27} is a huge number. But when you divide by 55 and take the remainder, you get 2.

The original message comes back.


Where Do These Numbers Come From?

This is key generation. Here’s how we got 55, 3, and 27.



Step 1: Pick two prime numbers. Call them pp and qq.

p=5,q=11p = 5, \quad q = 11


Step 2: Multiply them to get nn.

n=5×11=55n = 5 \times 11 = 55

This nn is public. Everyone can know it.


Step 3: Calculate ϕ(n)\phi(n).

For two primes, there’s a simple formula:

ϕ(n)=(p1)×(q1)\phi(n) = (p-1) \times (q-1)

ϕ(n)=(51)×(111)\phantom{\phi(n)} = (5-1) \times (11-1)

ϕ(n)=4×10\phantom{\phi(n)} = 4 \times 10

ϕ(n)=40\phantom{\phi(n)} = 40

This is the secret. You can calculate ϕ(n)\phi(n) because you know pp and qq. Someone who only knows n=55n = 55 would have to factor it first.


Step 4: Pick ee, the public exponent.

Choose any number that shares no common factors with ϕ(n)\phi(n).

e=3e = 3

Does 3 share any factors with 40? No. Good.


Step 5: Find dd, the private exponent.

We need dd where 3×dmod40=13 \times d \mod 40 = 1.

In other words: when we multiply dd by 3 and divide by 40, the remainder should be 1.

How do we find it? We search.

d=27d = 27 works because 3×27=813 \times 27 = 81, and 81÷40=281 \div 40 = 2 remainder 11.


The Keys

KeyComponentsWho knows it
Public(e,n)=(3,55)(e, n) = (3, 55)Everyone
Private(d,n)=(27,55)(d, n) = (27, 55)Only you

Why Does Decryption Work?

When you encrypt then decrypt, you’re doing:

Me then raised to d=Me×dM^e \text{ then raised to } d = M^{e \times d}

For us: e×d=3×27=81e \times d = 3 \times 27 = 81


Why Is It Secure?

An attacker knows e=3e = 3 and n=55n = 55.

To find dd, they need ϕ(n)\phi(n).

To find ϕ(n)\phi(n), they need pp and qq.

To find pp and qq, they must factor nn.


For n=55n = 55? Trivial. 55=5×1155 = 5 \times 11.

For a 600-digit nn? Nobody knows how to factor it efficiently.

RSA’s security rests on the difficulty of factoring large numbers.