TExcelTAD
Home › Number Theory & Cryptography › Fast Modular Exponentiation

Fast Modular Exponentiation

RSA raises 2048-bit numbers to 2048-bit powers. Multiplying mm by itself ee times would take 220482^{2048} 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, e=∑ibi2ie = \sum_i b_i 2^i. Then

ae=∏i:bi=1a2ia^e = \prod_{i : b_i = 1} a^{2^i}

and the powers a,a2,a4,a8,…a, a^2, a^4, a^8, \ldots come from repeated squaring. Reduce modulo nn after every step so numbers stay below n2n^2. Example: 3133^{13} with 13=1101213 = 1101_2 is 38⋅34⋅313^8 \cdot 3^4 \cdot 3^1.

Right-to-left binary method

python · try it yourself
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 2log⁡2e2\log_2 e 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 aa when the bit is 1.

python · try it yourself
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 e=65537e = 65537

65537=216+165537 = 2^{16} + 1 has only two 1-bits, so encryption costs 16 squarings and 1 multiplication. The private exponent dd is a full-size random number, so decryption is much slower, which is one reason for the CRT speed-up.

python · try it yourself
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 R0=akR_0 = a^k and R1=ak+1R_1 = a^{k+1} and, for each bit, does one multiplication and one squaring regardless of the bit's value.

python · try it yourself
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 522 mod 235^{22} \bmod 23 with repeated squaring. What theorem predicts the answer?

Answer

1, by Fermat's little theorem.

Solution

22=101102=16+4+222 = 10110_2 = 16 + 4 + 2. Squares modulo 23: 52=25≡25^2 = 25 \equiv 2, 54≡45^4 \equiv 4, 58≡165^8 \equiv 16, 516≡256≡35^{16} \equiv 256 \equiv 3. So 522≡3⋅4⋅2=24≡15^{22} \equiv 3 \cdot 4 \cdot 2 = 24 \equiv 1. Fermat says a22≡1(mod23)a^{22} \equiv 1 \pmod{23} for any aa not divisible by 23.

Exercise 2: Count the work

How many squarings and multiplications does the right-to-left method need for e=1000e = 1000?

Answer

10 squarings and 6 multiplications (16 in total, counting as in power_mod).

Solution

1000=111110100021000 = 1111101000_2 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 2×22 \times 2 matrix [1110]\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix} to compute F1018 mod (109+7)F_{10^{18}} \bmod (10^9 + 7).

Answer

F1018≡209783453(mod109+7)F_{10^{18}} \equiv 209783453 \pmod{10^9 + 7}, after about 100 matrix multiplications.

Solution

Mk=[Fk+1FkFkFk−1]M^k = \begin{bmatrix} F_{k+1} & F_k \\ F_k & F_{k-1} \end{bmatrix}, so FkF_k is the top-right entry.

python · try it yourself
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

F10=55F_{10} = 55 checks the method; 101810^{18} has 60 bits, so about 60 squarings plus one multiplication per 1-bit.

Test yourself

Square-and-multiply computes ae mod na^e \bmod n with about how many multiplications?

  1. ee
  2. 2log⁡2e2 \log_2 e
  3. e\sqrt{e}
  4. e2e^2

Why is e=65537e = 65537 fast for RSA encryption?

  1. it is prime
  2. its binary form 1000000000000000110000000000000001 has only two 1-bits
  3. it is small
  4. it equals dd

The Montgomery ladder protects against timing attacks because…

  1. it is faster
  2. it performs the same operations for every exponent bit
  3. it uses floating point
  4. it skips zero bits