@@ -43,7 +43,14 @@ mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho)
43
43
x -> used = digs ;
44
44
45
45
for (ix = 0 ; ix < n -> used ; ix ++ ) {
46
- /* mu = ai * m' mod b */
46
+ /* mu = ai * rho mod b
47
+ *
48
+ * The value of rho must be precalculated via
49
+ * bn_mp_montgomery_setup() such that
50
+ * it equals -1/n0 mod b this allows the
51
+ * following inner loop to reduce the
52
+ * input one digit at a time
53
+ */
47
54
mu = ((mp_word )x -> dp [ix ]) * ((mp_word )rho ) & MP_MASK ;
48
55
49
56
/* a = a + mu * m * b**i */
@@ -52,21 +59,31 @@ mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho)
52
59
register mp_digit * tmpn , * tmpx , u ;
53
60
register mp_word r ;
54
61
55
- /* aliases */
62
+ /* alias for digits of the modulus */
56
63
tmpn = n -> dp ;
64
+
65
+ /* alias for the digits of x [the input] */
57
66
tmpx = x -> dp + ix ;
58
67
59
68
/* set the carry to zero */
60
69
u = 0 ;
61
70
62
71
/* Multiply and add in place */
63
72
for (iy = 0 ; iy < n -> used ; iy ++ ) {
73
+ /* compute product and sum */
64
74
r = ((mp_word )mu ) * ((mp_word )* tmpn ++ ) +
65
75
((mp_word ) u ) + ((mp_word ) * tmpx );
76
+
77
+ /* get carry */
66
78
u = (mp_digit )(r >> ((mp_word ) DIGIT_BIT ));
79
+
80
+ /* fix digit */
67
81
* tmpx ++ = (mp_digit )(r & ((mp_word ) MP_MASK ));
68
82
}
69
- /* propagate carries */
83
+ /* At this point the ix'th digit of x should be zero */
84
+
85
+
86
+ /* propagate carries upwards as required*/
70
87
while (u ) {
71
88
* tmpx += u ;
72
89
u = * tmpx >> DIGIT_BIT ;
@@ -75,11 +92,18 @@ mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho)
75
92
}
76
93
}
77
94
95
+ /* at this point the n.used'th least
96
+ * significant digits of x are all zero
97
+ * which means we can shift x to the
98
+ * right by n.used digits and the
99
+ * residue is unchanged.
100
+ */
101
+
78
102
/* x = x/b**n.used */
79
103
mp_clamp (x );
80
104
mp_rshd (x , n -> used );
81
105
82
- /* if A >= m then A = A - m */
106
+ /* if x >= n then x = x - n */
83
107
if (mp_cmp_mag (x , n ) != MP_LT ) {
84
108
return s_mp_sub (x , n , x );
85
109
}
0 commit comments