Public-key encryption with toy RSA

Introduction

Symmetric encryption needs both sides to share a key first. But how do you send a secret key to a website you have never visited, over a network where anyone may be listening? For most of history there was no answer: keys travelled by trusted messenger.

In the 1970s came a different idea: two keys. A public key that anyone may have, and a matching private key that only its owner keeps. What the public key locks, only the private key opens. It works like a letter box: anyone can drop a letter through the slot, but only the person with the key can open the box and read them. RSA, published in 1977 by Rivest, Shamir and Adleman, was the first widely used system built this way.

How it works

RSA rests on a fact about numbers: multiplying two large primes is easy, but splitting the product back into those primes is extremely hard. Making the keys takes five steps:

  1. Pick two different primes, p and q.
  2. Multiply them: n = p × q. This n is part of both keys.
  3. Work out φ(n) = (p − 1)(q − 1), the count of numbers below n that share no factor with it.
  4. Choose e with no common factor with φ(n). Real systems almost always use 65537.
  5. Find d with e × d = 1 (mod φ(n)), using the extended Euclidean algorithm.

The public key is (e, n) and the private key is (d, n). To encrypt a number m smaller than n, compute c = mᵉ mod n. To decrypt, compute cᵈ mod n, which gives m back. Anyone can compute d from e and φ(n), but φ(n) needs p and q, and getting them from n means factoring it. With 2048-bit numbers, no one knows how to do that in any useful time.

Change the numbers in the calculator and follow each step. Try e = 15, which shares a factor with 3120, to see why e must be chosen carefully.

Encrypting uses repeated squaring to keep the numbers small: instead of computing m to the 17th power and then dividing, it squares and reduces modulo n at every step. That is why RSA works even with exponents hundreds of digits long.

Example

The textbook numbers: p = 61, q = 53 and e = 17, encrypting the message 65.

// Toy RSA with the textbook numbers. Real keys use primes hundreds of digits long.
function modPow(base, exp, m) {
  let result = 1;
  base = base % m;
  while (exp > 0) {
    if (exp % 2 === 1) result = (result * base) % m;
    base = (base * base) % m;
    exp = Math.floor(exp / 2);
  }
  return result;
}

// d is the number with e * d = 1 (mod phi), found by the extended Euclidean algorithm.
function inverse(e, phi) {
  let [r0, r1] = [e, phi];
  let [s0, s1] = [1, 0];
  while (r1 !== 0) {
    const q = Math.floor(r0 / r1);
    [r0, r1] = [r1, r0 - q * r1];
    [s0, s1] = [s1, s0 - q * s1];
  }
  return ((s0 % phi) + phi) % phi;
}

const p = 61, q = 53, e = 17;
const n = p * q;
const phi = (p - 1) * (q - 1);
const d = inverse(e, phi);
console.log("n = " + n + ", phi = " + phi + ", d = " + d);
console.log("check: e * d mod phi = " + ((e * d) % phi));

const m = 65;
const c = modPow(m, e, n);
console.log("encrypt " + m + " -> " + c);
console.log("decrypt " + c + " -> " + modPow(c, d, n));
Open in compiler

Line by line

  1. modPow computes base^exp mod m by repeated squaring: it squares base each time round the loop, and multiplies it into result when the current bit of exp is 1.
  2. inverse runs the extended Euclidean algorithm. r0 and r1 follow Euclid's remainders, while s0 and s1 track how to build each remainder from e, so when the remainder reaches 1, s0 is the inverse.
  3. n = 61 × 53 = 3233 and φ = 60 × 52 = 3120.
  4. d = 2753, and the check confirms 17 × 2753 = 46801 = 15 × 3120 + 1.
  5. 65¹⁷ mod 3233 = 2790 is the cipher text, and 2790²⁷⁵³ mod 3233 gives 65 back.

Expected result

n = 3233, phi = 3120, d = 2753
check: e * d mod phi = 1
encrypt 65 -> 2790
decrypt 2790 -> 65

A 3233 can be factored instantly by hand. Real RSA keys are at least 2048 bits, over 600 decimal digits.

In the real world

  • RSA is slow compared with AES, so it is not used to encrypt whole files. It is used to protect a small secret, such as an AES key, or to sign data.
  • Textbook RSA, exactly as above, is not safe: the same message always gives the same cipher text. Real RSA adds random padding (a scheme called OAEP) before encrypting.
  • Many systems now use elliptic-curve cryptography, which gives the same security with much shorter keys.
  • A large enough quantum computer could factor RSA numbers quickly. Governments and companies are moving to new "post-quantum" algorithms for that reason.

Common mistakes

  • Thinking the public key must be hidden. It is meant to be shared; only d, p and q are secret.
  • Encrypting a message bigger than n. The result wraps around modulo n and cannot be recovered.
  • Using textbook RSA without padding. Equal messages give equal cipher texts, and small messages can sometimes be found directly.
  • Computing mᵉ before reducing. The number becomes astronomically large; reduce at every step.

Best practices

  • Use a library's RSA with OAEP padding for encryption, or a modern elliptic-curve scheme.
  • Use keys of at least 2048 bits for RSA.
  • Use RSA (or another public-key method) to exchange or protect a symmetric key, then encrypt the data with AES.
  • Keep private keys in a key store, never in code or e-mail.

Summary

Public-key cryptography uses two keys: what the public key locks, only the private key opens. RSA builds the pair from two large primes: n = pq, φ(n) = (p − 1)(q − 1), a public e, and a private d with ed = 1 (mod φ(n)). Encryption is mᵉ mod n and decryption is cᵈ mod n, both done by repeated squaring. Its security rests on how hard it is to factor n, so real keys are huge, padded and used mainly to protect symmetric keys.

Quick check

1. With p = 5 and q = 11, what is φ(n)?
2. Which part of an RSA key pair must stay secret?
3. Why is RSA usually used to protect an AES key, not a whole file?
4. Someone chooses e = 15 with φ(n) = 3120. What goes wrong?

Key takeaways

  • Public-key cryptography lets strangers communicate secretly without sharing a secret first.
  • RSA keys come from two primes: n = pq, φ(n) = (p − 1)(q − 1), and d is the inverse of e modulo φ(n).
  • RSA is secure only because factoring a huge n is infeasible, so real keys have at least 2048 bits.
  • Real systems pad RSA and use it to protect a symmetric key, not to encrypt bulk data.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.