These are the human proofs of Montgomery multiplication, at full length.
Correctness of Montgomery multiplication full
This proof shows: correctness, termination.
Let n≥1 be odd, let r be the number of binary digits of n, and let R=2r. Then 2r−1≤n<2r, so R>n, and gcd(n,R)=1 because n is odd. So R has an inverse R−1 modulo n. (The same proof works for any r with 2r>n.)
Lemma 1 (setup, lines L2 to L6). The loop of lines L4 and L5 terminates, and afterwards nx≡1(modR). Hence n′=(−x)modR satisfies nn′≡−1(modR) and 0≤n′<R.
Proof. We show the invariant nx≡1(mod2j). At the start, x=1, j=1, and n⋅1≡1(mod2) because n is odd. Suppose nx≡1(mod2j) before a pass, and let j′=min(2j,r) and x′=x(2−nx)mod2j′. Then
1−nx(2−nx)=1−2nx+(nx)2=(1−nx)2,
and 2j∣1−nx gives 22j∣(1−nx)2, so nx(2−nx)≡1(mod22j) and hence modulo 2j′, since j′≤2j. Reducing x(2−nx) modulo 2j′ does not change this congruence. So the invariant holds after the pass. Each pass strictly increases j, because j<r and j≥1 give min(2j,r)>j, and j never exceeds r. So the loop stops, with j=r, and then nx≡1(mod2r). Line L6 gives nn′≡−nx≡−1(modR). □
Line L7 sets R2=R2modn by ordinary division with remainder.
Lemma 2 (REDC, lines L8 to L11). For every integer T with 0≤T<nR, REDC(T) returns t with 0≤t<n and t≡TR−1(modn).
Proof. Line L8 sets m=((TmodR)⋅n′)modR, so 0≤m<R and m≡Tn′(modR). Then
T+mn≡T+Tn′n≡T+T⋅(−1)=0(modR)
by Lemma 1. So R divides T+mn, and t=(T+mn)/R in line L9 is an integer. The equation tR=T+mn gives tR≡T(modn), and multiplying by R−1 gives t≡TR−1(modn).
Bounds: T+mn≥0, so t≥0. And T<nR and m≤R−1 give T+mn<nR+(R−1)n<2nR, so t<2n. If t≥n, line L10 replaces t by t−n, which lies in [0,n) and is congruent to t modulo n. If t<n, it is already in [0,n). In both cases the returned value is the unique residue in [0,n) congruent to TR−1, that is, TR−1modn. □
Theorem. For a,b∈{0,…,n−1}, write a~=aRmodn for the Montgomery form. Then:
Proof. (1) The argument of REDC in line L13 is T=a⋅R2 with 0≤a<n and 0≤R2<n<R, so 0≤T<nR. By Lemma 2 the result is ≡aR2R−1=aR(modn) and lies in [0,n), so it equals a~.
(2) In line L14, T=a~<n<nR, so Lemma 2 gives a~R−1≡aRR−1=a, and the result in [0,n) is a.
(3) In line L12, T=a~b~ with 0≤a~,b~<n, so 0≤T<n2<nR. Lemma 2 gives a~b~R−1≡aR⋅bR⋅R−1=abR(modn), and the result in [0,n) is (abmodn)Rmodn.
(4) follows from (1), (3) and (2), applied in this order to abmodn. ■
Termination. The setup loop terminates by Lemma 1, and REDC, MONT-MUL, TO-MONT and FROM-MONT have no loops. So every call returns.
Exponentiation. By (3), every MONT-MUL in square-and-multiply maps forms to forms; so if the accumulator starts as the form of 1 and the base as the form of x, then after processing the exponent e the accumulator is the form of xemodn, and FROM-MONT returns xemodn by (2).