StringMash.com

RSA calculator

Small primes, every step of the arithmetic shown. For learning, not for secrets.

11 characters
Updates as you type
Public key (n, e)(3233, 17)
Private key d2753
Ciphertext c2790
Decrypted65

Show the steps
  1. n = p × q = 61 × 53 = 3233.
  2. φ(n) = (p − 1)(q − 1) = 60 × 52 = 3120.
  3. d is the inverse of e modulo φ(n): the number with e × d leaving remainder 1. The extended Euclidean algorithm finds it: 3120 = 183 × 17 + 9; 17 = 1 × 9 + 8; 9 = 1 × 8 + 1; 8 = 8 × 1 + 0.
  4. d = 2753. Check: 17 × 2753 = 46801, which is 15 × 3120 + 1.
  5. Encrypt: c = m^e mod n = 65^17 mod 3233 = 2790.
  6. Decrypt: m = c^d mod n = 2790^2753 mod 3233 = 65.
  7. Real RSA keys use primes hundreds of digits long, so factoring n to find d is out of reach. With small primes like these, anyone could factor n.

Using it

Type four whole numbers separated by spaces: two different primes p and q, a public exponent e, and a message number m smaller than p × q. The output is the ciphertext, the rows give both keys and the message decrypted again, and the steps show every calculation, including the extended Euclidean algorithm that finds d.

The sample, 61 53 17 65, is the example many textbooks use: n = 3233, d = 2753, and 65 encrypts to 2790.

The steps

Multiply the primes to get n. Work out φ(n) = (p − 1)(q − 1), which counts the numbers below n that share no factor with it. Choose e between 1 and φ(n) sharing no factor with φ(n); 65537 is the usual choice for real keys. Find d so that e × d leaves remainder 1 when divided by φ(n). The public key is (n, e); the private key is d.

To encrypt, c = mᵉ mod n. To decrypt, m = cᵈ mod n. It works because of Euler's theorem: raising to e and then to d comes back round to the start.

Why this isn't real encryption

Everything rests on n being too hard to factor. With p and q under 100,000, as here, anyone can factor n in a moment and work out d. Real keys use primes hundreds of digits long, and real systems also pad the message with random bytes before encrypting, so the same message never gives the same ciphertext. Use a proper library for anything secret.

Questions

Who invented RSA?

Ron Rivest, Adi Shamir and Leonard Adleman, at MIT in 1977. The name is their initials.

Why must e share no factor with φ(n)?

Otherwise no d exists: e has no inverse modulo φ(n), and the encryption can't be undone.

How do I encrypt text?

Turn each letter into a number first, such as A = 65 in ASCII, and encrypt the numbers one at a time. With a small n, that's just a substitution cipher in disguise.

Sources

Added . What's new