RSA: generating a key pair and exponentiating by squaring
◈ 8 cardsGenerate an RSA key pair end to end from two primes — n, φ(n), a coprime e and the modular inverse d — then compute a modular exponentiation the way the exam calculator can, by square-and-multiply.
RSA is a block cipher over integers
Rivest, Shamir and Adleman published RSA at MIT in 1978, and it is still the public-key algorithm most likely to appear on an exam paper. It is a block cipher in which the plaintext and the ciphertext are integers in the range for some modulus . Encryption and decryption are the same operation with different exponents:
The public key is the pair and the private key is . The modulus is in both, so the secret is alone.
Key generation in five steps
- Pick two distinct primes
pandq, kept private. - Compute the modulus , which becomes public.
- Compute — Euler's totient, the count of integers below
nthat share no factor with it. This step is where the primality of both factors is doing the work. - Choose a public exponent
ewith and . - Compute the private exponent as the modular inverse , i.e. the
dsatisfying .
Step 5 is the reason step 4 demands coprimality: an inverse of e modulo exists if and only if the two are relatively prime. Pick an e that shares a factor with and there is no d at all, and what you have built is not RSA.
Worked example — our key pair, end to end
Take p = 59 and q = 71.
- .
- .
- Choose
e = 13. Check coprimality: , which does not include 13, so and an inverse exists. - Invert:
d = 937. Verify without trusting anything — , and , so . That single multiplication is the whole check, and it costs five seconds on the permitted calculator.
Publish ; keep and destroy p, q and , because any one of them hands an attacker the private key immediately.
Now encrypt the plaintext block M = 1234: . Decrypt it: . The message comes back.
Doing that exponentiation by hand
is a 41-digit number. You do not compute it. Square-and-multiply decomposes the exponent into powers of two and reduces modulo n at every single step, so no intermediate value ever exceeds .
Write the exponent in binary: . So . Build the squarings mod 4189:
Multiply the ones the binary expansion selected, reducing as you go: , then . That is four squarings and two multiplications instead of twelve multiplications and a 41-digit intermediate — and the cost of the exponent's 1 bits, versus its 0 bits, is exactly the leak the timing attack in L5.3 exploits.
Reduce at every step. Computing first and taking the modulus last is arithmetically identical and computationally hopeless; on a 2048-bit modulus it is not merely slow, it does not fit in memory.