Fast Modular Exponentiation
RSA raises 2048-bit numbers to 2048-bit powers. Multiplying by itself times would take steps; square-and-multiply needs about 3000 multiplications. It is the single most important algorithm in public-key cryptography.
The idea
Write the exponent in binary, . Then
and the powers come from repeated squaring. Reduce modulo after every step so numbers stay below . Example: with is .
Right-to-left binary method
def power_mod(a, e, n):
result, base, mults = 1, a % n, 0
while e > 0:
if e & 1:
result = result * base % n
mults += 1
base = base * base % n
mults += 1
e >>= 1
return result, mults
print(power_mod(3, 13, 1000), 3**13 % 1000)
r, m = power_mod(7, 2**2048 - 1, 10**9 + 7)
print(r == pow(7, 2**2048 - 1, 10**9 + 7), "multiplications:", m)(323, 7) 323
True multiplications: 4096
The cost is at most multiplications: one squaring per bit and one multiplication per 1-bit. An exponent of all ones (as above) is the worst case.
Left-to-right and the trace
Scanning bits from the top is equally fast and needs only one variable: square for every bit, multiply by when the bit is 1.
def power_mod_lr(a, e, n, trace=False):
r = 1
for bit in bin(e)[2:]:
r = r * r % n
if bit == "1":
r = r * a % n
if trace:
print(f"bit {bit}: r = {r}")
return r
print(power_mod_lr(3, 13, 1000, trace=True))bit 1: r = 3
bit 1: r = 27
bit 0: r = 729
bit 1: r = 323
323
Why RSA uses
has only two 1-bits, so encryption costs 16 squarings and 1 multiplication. The private exponent is a full-size random number, so decryption is much slower, which is one reason for the CRT speed-up.
def count_ops(e):
return e.bit_length() - 1, bin(e).count("1") - 1 # squarings, extra multiplications
print("e = 65537:", count_ops(65537))
d = pow(65537, -1, (2**61 - 2) * (2**31 - 2)) # some large exponent
print("a large d:", count_ops(d))e = 65537: (16, 1)
a large d: (91, 48)
Timing attacks and the Montgomery ladder
In square-and-multiply, the extra multiplication happens only for 1-bits. If an attacker can time (or measure the power draw of) each step, they read the secret exponent bit by bit. Kocher's 1996 timing attack did exactly that to RSA implementations.
The Montgomery ladder does the same work for every bit: it keeps and and, for each bit, does one multiplication and one squaring regardless of the bit's value.
def ladder(a, e, n):
r0, r1 = 1, a % n
for bit in bin(e)[2:]:
if bit == "0":
r1 = r0 * r1 % n
r0 = r0 * r0 % n
else:
r0 = r0 * r1 % n
r1 = r1 * r1 % n
return r0
print(ladder(3, 13, 1000), ladder(5, 123456789, 10**9 + 7) == pow(5, 123456789, 10**9 + 7))323 True
The branch on bit still leaks through caches and branch predictors; real code replaces it with a constant-time conditional swap. Python's big integers are not constant-time at all, one more reason why this course's code is for learning only.
In software
- Python's
pow(a, e, n)uses a windowed left-to-right method (processing several bits at a time with a small table of odd powers). - OpenSSL uses fixed-window exponentiation with Montgomery multiplication and constant-time table lookups for private keys, and blinding to randomize the base.
- The same square-and-multiply pattern computes elliptic-curve scalar multiples ("double-and-add") and matrix powers for Fibonacci numbers.
Exercises
Exercise 1: By hand
Compute with repeated squaring. What theorem predicts the answer?
Answer
1, by Fermat's little theorem.
Solution
. Squares modulo 23: , , , . So . Fermat says for any not divisible by 23.
Exercise 2: Count the work
How many squarings and multiplications does the right-to-left method need for ?
Answer
10 squarings and 6 multiplications (16 in total, counting as in power_mod).
Solution
has 10 bits and six 1-bits. power_mod squares once per bit (10) and multiplies once per 1-bit (6). The last squaring is wasted; a careful implementation does 9 squarings and 5 multiplications after initializing with the base.
Exercise 3: Matrix power Fibonacci (code)
Use square-and-multiply on the matrix to compute .
Answer
, after about 100 matrix multiplications.
Solution
, so is the top-right entry.
P = 10**9 + 7
def mat_mul(A, B):
return [[(A[0][0] * B[0][0] + A[0][1] * B[1][0]) % P, (A[0][0] * B[0][1] + A[0][1] * B[1][1]) % P],
[(A[1][0] * B[0][0] + A[1][1] * B[1][0]) % P, (A[1][0] * B[0][1] + A[1][1] * B[1][1]) % P]]
def mat_pow(M, k):
R = [[1, 0], [0, 1]]
while k:
if k & 1:
R = mat_mul(R, M)
M = mat_mul(M, M)
k >>= 1
return R
print(mat_pow([[1, 1], [1, 0]], 10)[0][1], mat_pow([[1, 1], [1, 0]], 10**18)[0][1])55 209783453
checks the method; has 60 bits, so about 60 squarings plus one multiplication per 1-bit.
Test yourself
Square-and-multiply computes with about how many multiplications?
Why is fast for RSA encryption?
- it is prime
- its binary form has only two 1-bits
- it is small
- it equals
The Montgomery ladder protects against timing attacks because…
- it is faster
- it performs the same operations for every exponent bit
- it uses floating point
- it skips zero bits