2 * Bignum routines for RSA and DH and stuff.
11 #include "bn-internal.h"
14 BignumInt bnZero
[1] = { 0 };
15 BignumInt bnOne
[2] = { 1, 1 };
18 * The Bignum format is an array of `BignumInt'. The first
19 * element of the array counts the remaining elements. The
20 * remaining elements express the actual number, base 2^BIGNUM_INT_BITS, _least_
21 * significant digit first. (So it's trivial to extract the bit
22 * with value 2^n for any n.)
24 * All Bignums in this module are positive. Negative numbers must
25 * be dealt with outside it.
27 * INVARIANT: the most significant word of any Bignum must be
31 Bignum Zero
= bnZero
, One
= bnOne
;
33 static Bignum
newbn(int length
)
35 Bignum b
= snewn(length
+ 1, BignumInt
);
38 memset(b
, 0, (length
+ 1) * sizeof(*b
));
43 void bn_restore_invariant(Bignum b
)
45 while (b
[0] > 1 && b
[b
[0]] == 0)
49 Bignum
copybn(Bignum orig
)
51 Bignum b
= snewn(orig
[0] + 1, BignumInt
);
54 memcpy(b
, orig
, (orig
[0] + 1) * sizeof(*b
));
61 * Burn the evidence, just in case.
63 smemclr(b
, sizeof(b
[0]) * (b
[0] + 1));
67 Bignum
bn_power_2(int n
)
69 Bignum ret
= newbn(n
/ BIGNUM_INT_BITS
+ 1);
70 bignum_set_bit(ret
, n
, 1);
75 * Internal addition. Sets c = a - b, where 'a', 'b' and 'c' are all
76 * little-endian arrays of 'len' BignumInts. Returns a BignumInt carried
79 static BignumInt
internal_add(const BignumInt
*a
, const BignumInt
*b
,
80 BignumInt
*c
, int len
)
83 BignumDblInt carry
= 0;
85 for (i
= 0; i
< len
; i
++) {
86 carry
+= (BignumDblInt
)a
[i
] + b
[i
];
87 c
[i
] = (BignumInt
)carry
;
88 carry
>>= BIGNUM_INT_BITS
;
91 return (BignumInt
)carry
;
95 * Internal subtraction. Sets c = a - b, where 'a', 'b' and 'c' are
96 * all little-endian arrays of 'len' BignumInts. Any borrow from the top
99 static void internal_sub(const BignumInt
*a
, const BignumInt
*b
,
100 BignumInt
*c
, int len
)
103 BignumDblInt carry
= 1;
105 for (i
= 0; i
< len
; i
++) {
106 carry
+= (BignumDblInt
)a
[i
] + (b
[i
] ^ BIGNUM_INT_MASK
);
107 c
[i
] = (BignumInt
)carry
;
108 carry
>>= BIGNUM_INT_BITS
;
114 * Input is in the first len words of a and b.
115 * Result is returned in the first 2*len words of c.
117 * 'scratch' must point to an array of BignumInt of size at least
118 * mul_compute_scratch(len). (This covers the needs of internal_mul
119 * and all its recursive calls to itself.)
121 #define KARATSUBA_THRESHOLD 50
122 static int mul_compute_scratch(int len
)
125 while (len
> KARATSUBA_THRESHOLD
) {
126 int toplen
= len
/2, botlen
= len
- toplen
; /* botlen is the bigger */
127 int midlen
= botlen
+ 1;
133 static void internal_mul(const BignumInt
*a
, const BignumInt
*b
,
134 BignumInt
*c
, int len
, BignumInt
*scratch
)
136 if (len
> KARATSUBA_THRESHOLD
) {
140 * Karatsuba divide-and-conquer algorithm. Cut each input in
141 * half, so that it's expressed as two big 'digits' in a giant
147 * Then the product is of course
149 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
151 * and we compute the three coefficients by recursively
152 * calling ourself to do half-length multiplications.
154 * The clever bit that makes this worth doing is that we only
155 * need _one_ half-length multiplication for the central
156 * coefficient rather than the two that it obviouly looks
157 * like, because we can use a single multiplication to compute
159 * (a_1 + a_0) (b_1 + b_0) = a_1 b_1 + a_1 b_0 + a_0 b_1 + a_0 b_0
161 * and then we subtract the other two coefficients (a_1 b_1
162 * and a_0 b_0) which we were computing anyway.
164 * Hence we get to multiply two numbers of length N in about
165 * three times as much work as it takes to multiply numbers of
166 * length N/2, which is obviously better than the four times
167 * as much work it would take if we just did a long
168 * conventional multiply.
171 int toplen
= len
/2, botlen
= len
- toplen
; /* botlen is the bigger */
172 int midlen
= botlen
+ 1;
176 * The coefficients a_1 b_1 and a_0 b_0 just avoid overlapping
177 * in the output array, so we can compute them immediately in
182 printf("a1,a0 = 0x");
183 for (i
= 0; i
< len
; i
++) {
184 if (i
== toplen
) printf(", 0x");
185 printf("%0*x", BIGNUM_INT_BITS
/4, a
[len
- 1 - i
]);
188 printf("b1,b0 = 0x");
189 for (i
= 0; i
< len
; i
++) {
190 if (i
== toplen
) printf(", 0x");
191 printf("%0*x", BIGNUM_INT_BITS
/4, b
[len
- 1 - i
]);
197 internal_mul(a
+ botlen
, b
+ botlen
, c
+ 2*botlen
, toplen
, scratch
);
200 for (i
= 0; i
< 2*toplen
; i
++) {
201 printf("%0*x", BIGNUM_INT_BITS
/4, c
[2*len
- 1 - i
]);
207 internal_mul(a
, b
, c
, botlen
, scratch
);
210 for (i
= 0; i
< 2*botlen
; i
++) {
211 printf("%0*x", BIGNUM_INT_BITS
/4, c
[2*botlen
- 1 - i
]);
216 /* Zero padding. botlen exceeds toplen by at most 1, and we'll set
217 * the extra carry explicitly below, so we only need to zero at most
218 * one of the top words here.
220 scratch
[midlen
- 2] = scratch
[2*midlen
- 2] = 0;
222 for (i
= 0; i
< toplen
; i
++) {
223 scratch
[i
] = a
[i
+ botlen
]; /* a_1 */
224 scratch
[midlen
+ i
] = b
[i
+ botlen
]; /* b_1 */
227 /* compute a_1 + a_0 */
228 scratch
[midlen
- 1] = internal_add(scratch
, a
, scratch
, botlen
);
230 printf("a1plusa0 = 0x");
231 for (i
= 0; i
< midlen
; i
++) {
232 printf("%0*x", BIGNUM_INT_BITS
/4, scratch
[midlen
- 1 - i
]);
236 /* compute b_1 + b_0 */
237 scratch
[2*midlen
- 1] = internal_add(scratch
+midlen
, b
,
238 scratch
+midlen
, botlen
);
240 printf("b1plusb0 = 0x");
241 for (i
= 0; i
< midlen
; i
++) {
242 printf("%0*x", BIGNUM_INT_BITS
/4, scratch
[2*midlen
- 1 - i
]);
248 * Now we can do the third multiplication.
250 internal_mul(scratch
, scratch
+ midlen
, scratch
+ 2*midlen
, midlen
,
253 printf("a1plusa0timesb1plusb0 = 0x");
254 for (i
= 0; i
< 2*midlen
; i
++) {
255 printf("%0*x", BIGNUM_INT_BITS
/4, scratch
[4*midlen
- 1 - i
]);
261 * Now we can reuse the first half of 'scratch' to compute the
262 * sum of the outer two coefficients, to subtract from that
263 * product to obtain the middle one.
265 scratch
[2*botlen
- 2] = scratch
[2*botlen
- 1] = 0;
266 for (i
= 0; i
< 2*toplen
; i
++)
267 scratch
[i
] = c
[2*botlen
+ i
];
268 scratch
[2*botlen
] = internal_add(scratch
, c
, scratch
, 2*botlen
);
269 scratch
[2*botlen
+ 1] = 0;
271 printf("a1b1plusa0b0 = 0x");
272 for (i
= 0; i
< 2*midlen
; i
++) {
273 printf("%0*x", BIGNUM_INT_BITS
/4, scratch
[2*midlen
- 1 - i
]);
278 internal_sub(scratch
+ 2*midlen
, scratch
, scratch
, 2*midlen
);
280 printf("a1b0plusa0b1 = 0x");
281 for (i
= 0; i
< 2*midlen
; i
++) {
282 printf("%0*x", BIGNUM_INT_BITS
/4, scratch
[4*midlen
- 1 - i
]);
288 * And now all we need to do is to add that middle coefficient
289 * back into the output. We may have to propagate a carry
290 * further up the output, but we can be sure it won't
291 * propagate right the way off the top.
293 carry
= internal_add(c
+ botlen
, scratch
, c
+ botlen
, 2*midlen
);
294 i
= botlen
+ 2*midlen
;
298 c
[i
] = (BignumInt
)carry
;
299 carry
>>= BIGNUM_INT_BITS
;
304 for (i
= 0; i
< 2*len
; i
++) {
305 printf("%0*x", BIGNUM_INT_BITS
/4, c
[2*len
- i
]);
314 const BignumInt
*ap
, *alim
= a
+ len
, *bp
, *blim
= b
+ len
;
318 * Multiply in the ordinary O(N^2) way.
321 for (i
= 0; i
< 2 * len
; i
++)
324 for (cps
= c
, ap
= a
; ap
< alim
; ap
++, cps
++) {
326 for (cp
= cps
, bp
= b
, i
= blim
- bp
; i
--; bp
++, cp
++) {
327 t
= (MUL_WORD(*ap
, *bp
) + carry
) + *cp
;
329 carry
= (BignumInt
)(t
>> BIGNUM_INT_BITS
);
337 * Variant form of internal_mul used for the initial step of
338 * Montgomery reduction. Only bothers outputting 'len' words
339 * (everything above that is thrown away).
341 static void internal_mul_low(const BignumInt
*a
, const BignumInt
*b
,
342 BignumInt
*c
, int len
, BignumInt
*scratch
)
344 if (len
> KARATSUBA_THRESHOLD
) {
348 * Karatsuba-aware version of internal_mul_low. As before, we
349 * express each input value as a shifted combination of two
355 * Then the full product is, as before,
357 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
359 * Provided we choose D on the large side (so that a_0 and b_0
360 * are _at least_ as long as a_1 and b_1), we don't need the
361 * topmost term at all, and we only need half of the middle
362 * term. So there's no point in doing the proper Karatsuba
363 * optimisation which computes the middle term using the top
364 * one, because we'd take as long computing the top one as
365 * just computing the middle one directly.
367 * So instead, we do a much more obvious thing: we call the
368 * fully optimised internal_mul to compute a_0 b_0, and we
369 * recursively call ourself to compute the _bottom halves_ of
370 * a_1 b_0 and a_0 b_1, each of which we add into the result
371 * in the obvious way.
373 * In other words, there's no actual Karatsuba _optimisation_
374 * in this function; the only benefit in doing it this way is
375 * that we call internal_mul proper for a large part of the
376 * work, and _that_ can optimise its operation.
379 int toplen
= len
/2, botlen
= len
- toplen
; /* botlen is the bigger */
382 * Scratch space for the various bits and pieces we're going
383 * to be adding together: we need botlen*2 words for a_0 b_0
384 * (though we may end up throwing away its topmost word), and
385 * toplen words for each of a_1 b_0 and a_0 b_1. That adds up
390 internal_mul(a
, b
, scratch
+ 2*toplen
, botlen
, scratch
+ 2*len
);
393 internal_mul_low(a
+ botlen
, b
, scratch
+ toplen
, toplen
,
397 internal_mul_low(a
, b
+ botlen
, scratch
, toplen
, scratch
+ 2*len
);
399 /* Copy the bottom half of the big coefficient into place */
400 for (i
= 0; i
< botlen
; i
++)
401 c
[i
] = scratch
[2*toplen
+ i
];
403 /* Add the two small coefficients, throwing away the returned carry */
404 internal_add(scratch
, scratch
+ toplen
, scratch
, toplen
);
406 /* And add that to the large coefficient, leaving the result in c. */
407 internal_add(scratch
, scratch
+ 2*toplen
+ botlen
,
414 const BignumInt
*ap
, *alim
= a
+ len
, *bp
;
415 BignumInt
*cp
, *cps
, *clim
= c
+ len
;
418 * Multiply in the ordinary O(N^2) way.
421 for (i
= 0; i
< len
; i
++)
424 for (cps
= c
, ap
= a
; ap
< alim
; ap
++, cps
++) {
426 for (cp
= cps
, bp
= b
, i
= clim
- cp
; i
--; bp
++, cp
++) {
427 t
= (MUL_WORD(*ap
, *bp
) + carry
) + *cp
;
429 carry
= (BignumInt
)(t
>> BIGNUM_INT_BITS
);
436 * Montgomery reduction. Expects x to be a little-endian array of 2*len
437 * BignumInts whose value satisfies 0 <= x < rn (where r = 2^(len *
438 * BIGNUM_INT_BITS) is the Montgomery base). Returns in the same array
439 * a value x' which is congruent to xr^{-1} mod n, and satisfies 0 <=
442 * 'n' and 'mninv' should be little-endian arrays of 'len' BignumInts
443 * each, containing respectively n and the multiplicative inverse of
446 * 'tmp' is an array of BignumInt used as scratch space, of length at
447 * least 3*len + mul_compute_scratch(len).
449 static void monty_reduce(BignumInt
*x
, const BignumInt
*n
,
450 const BignumInt
*mninv
, BignumInt
*tmp
, int len
)
456 * Multiply x by (-n)^{-1} mod r. This gives us a value m such
457 * that mn is congruent to -x mod r. Hence, mn+x is an exact
458 * multiple of r, and is also (obviously) congruent to x mod n.
460 internal_mul_low(x
, mninv
, tmp
, len
, tmp
+ 3*len
);
463 * Compute t = (mn+x)/r in ordinary, non-modular, integer
464 * arithmetic. By construction this is exact, and is congruent mod
465 * n to x * r^{-1}, i.e. the answer we want.
467 * The following multiply leaves that answer in the _most_
468 * significant half of the 'x' array, so then we must shift it
471 internal_mul(tmp
, n
, tmp
+len
, len
, tmp
+ 3*len
);
472 carry
= internal_add(x
, tmp
+len
, x
, 2*len
);
473 for (i
= 0; i
< len
; i
++)
474 x
[i
] = x
[len
+ i
], x
[len
+ i
] = 0;
477 * Reduce t mod n. This doesn't require a full-on division by n,
478 * but merely a test and single optional subtraction, since we can
479 * show that 0 <= t < 2n.
482 * + we computed m mod r, so 0 <= m < r.
483 * + so 0 <= mn < rn, obviously
484 * + hence we only need 0 <= x < rn to guarantee that 0 <= mn+x < 2rn
485 * + yielding 0 <= (mn+x)/r < 2n as required.
488 for (i
= len
; i
-- > 0; )
492 if (carry
|| i
< 0 || x
[i
] > n
[i
])
493 internal_sub(x
, n
, x
, len
);
496 static void internal_add_shifted(BignumInt
*number
,
497 unsigned n
, int shift
)
499 int word
= 1 + (shift
/ BIGNUM_INT_BITS
);
500 int bshift
= shift
% BIGNUM_INT_BITS
;
503 addend
= (BignumDblInt
)n
<< bshift
;
506 addend
+= number
[word
];
507 number
[word
] = (BignumInt
) addend
& BIGNUM_INT_MASK
;
508 addend
>>= BIGNUM_INT_BITS
;
515 * Input in first alen words of a and first mlen words of m.
516 * Output in first alen words of a
517 * (of which last alen-mlen words will be zero).
518 * The MSW of m MUST have its high bit set.
519 * Quotient is accumulated in the `quotient' array. Quotient parts
520 * are shifted left by `qshift' before adding into quot.
522 static void internal_mod(BignumInt
*a
, int alen
,
523 BignumInt
*m
, int mlen
,
524 BignumInt
*quot
, int qshift
)
536 for (i
= alen
, h
= 0; i
-- >= mlen
; ) {
538 unsigned int q
, r
, c
, ai1
;
545 /* Find q = h:a[i] / m0 */
550 * To illustrate it, suppose a BignumInt is 8 bits, and
551 * we are dividing (say) A1:23:45:67 by A1:B2:C3. Then
552 * our initial division will be 0xA123 / 0xA1, which
553 * will give a quotient of 0x100 and a divide overflow.
554 * However, the invariants in this division algorithm
555 * are not violated, since the full number A1:23:... is
556 * _less_ than the quotient prefix A1:B2:... and so the
557 * following correction loop would have sorted it out.
559 * In this situation we set q to be the largest
560 * quotient we _can_ stomach (0xFF, of course).
564 /* Macro doesn't want an array subscript expression passed
565 * into it (see definition), so use a temporary. */
566 BignumInt tmplo
= a
[i
];
567 DIVMOD_WORD(q
, r
, h
, tmplo
, m0
);
569 /* Refine our estimate of q by looking at
570 h:a[i]:a[i-1] / m0:m1 */
572 if (t
> ((BignumDblInt
) r
<< BIGNUM_INT_BITS
) + ai1
) {
575 r
= (r
+ m0
) & BIGNUM_INT_MASK
; /* overflow? */
576 if (r
>= (BignumDblInt
) m0
&&
577 t
> ((BignumDblInt
) r
<< BIGNUM_INT_BITS
) + ai1
) q
--;
583 /* Subtract q * m from a[i...] */
585 for (k
= 0; k
< mlen
; k
++) {
586 t
= MUL_WORD(q
, m
[k
]);
588 c
= (unsigned)(t
>> BIGNUM_INT_BITS
);
589 if ((BignumInt
) t
> a
[j
+ k
])
591 a
[j
+ k
] -= (BignumInt
) t
;
594 /* Add back m in case of borrow */
597 for (k
= 0; k
< mlen
; k
++) {
600 a
[j
+ k
] = (BignumInt
) t
;
601 t
= t
>> BIGNUM_INT_BITS
;
607 internal_add_shifted(quot
, q
,
608 qshift
+ BIGNUM_INT_BITS
* (i
+ 1 - mlen
));
617 static void shift_left(BignumInt
*x
, int xlen
, int shift
)
623 for (i
= xlen
; --i
> 0; )
624 x
[i
] = (x
[i
] << shift
) | (x
[i
- 1] >> (BIGNUM_INT_BITS
- shift
));
625 x
[0] = x
[0] << shift
;
628 static void shift_right(BignumInt
*x
, int xlen
, int shift
)
635 for (i
= 0; i
< xlen
; i
++)
636 x
[i
] = (x
[i
] >> shift
) | (x
[i
+ 1] << (BIGNUM_INT_BITS
- shift
));
637 x
[i
] = x
[i
] >> shift
;
641 * Compute (base ^ exp) % mod, the pedestrian way.
643 Bignum
modpow_simple(Bignum base_in
, Bignum exp
, Bignum mod
)
645 BignumInt
*a
, *b
, *n
, *m
, *scratch
;
647 int mlen
, scratchlen
, i
, j
;
651 * The most significant word of mod needs to be non-zero. It
652 * should already be, but let's make sure.
654 assert(mod
[mod
[0]] != 0);
657 * Make sure the base is smaller than the modulus, by reducing
658 * it modulo the modulus if not.
660 base
= bigmod(base_in
, mod
);
662 /* Allocate m of size mlen, copy mod to m */
664 m
= snewn(mlen
, BignumInt
);
665 for (j
= 0; j
< mlen
; j
++)
668 /* Shift m left to make msb bit set */
669 for (mshift
= 0; mshift
< BIGNUM_INT_BITS
-1; mshift
++)
670 if ((m
[mlen
- 1] << mshift
) & BIGNUM_TOP_BIT
)
673 shift_left(m
, mlen
, mshift
);
675 /* Allocate n of size mlen, copy base to n */
676 n
= snewn(mlen
, BignumInt
);
677 for (i
= 0; i
< (int)base
[0]; i
++)
679 for (; i
< mlen
; i
++)
682 /* Allocate a and b of size 2*mlen. Set a = 1 */
683 a
= snewn(2 * mlen
, BignumInt
);
684 b
= snewn(2 * mlen
, BignumInt
);
686 for (i
= 1; i
< 2 * mlen
; i
++)
689 /* Scratch space for multiplies */
690 scratchlen
= mul_compute_scratch(mlen
);
691 scratch
= snewn(scratchlen
, BignumInt
);
693 /* Skip leading zero bits of exp. */
695 j
= BIGNUM_INT_BITS
-1;
696 while (i
< (int)exp
[0] && (exp
[exp
[0] - i
] & (1 << j
)) == 0) {
700 j
= BIGNUM_INT_BITS
-1;
704 /* Main computation */
705 while (i
< (int)exp
[0]) {
707 internal_mul(a
, a
, b
, mlen
, scratch
);
708 internal_mod(b
, mlen
* 2, m
, mlen
, NULL
, 0);
709 if ((exp
[exp
[0] - i
] & (1 << j
)) != 0) {
710 internal_mul(b
, n
, a
, mlen
, scratch
);
711 internal_mod(a
, mlen
* 2, m
, mlen
, NULL
, 0);
721 j
= BIGNUM_INT_BITS
-1;
724 /* Fixup result in case the modulus was shifted */
726 shift_left(a
, mlen
+ 1, mshift
);
727 internal_mod(a
, mlen
+ 1, m
, mlen
, NULL
, 0);
728 shift_right(a
, mlen
, mshift
);
731 /* Copy result to buffer */
732 result
= newbn(mod
[0]);
733 for (i
= 0; i
< mlen
; i
++)
734 result
[i
+ 1] = a
[i
];
735 while (result
[0] > 1 && result
[result
[0]] == 0)
738 /* Free temporary arrays */
739 for (i
= 0; i
< 2 * mlen
; i
++)
742 for (i
= 0; i
< scratchlen
; i
++)
745 for (i
= 0; i
< 2 * mlen
; i
++)
748 for (i
= 0; i
< mlen
; i
++)
751 for (i
= 0; i
< mlen
; i
++)
761 * Compute (base ^ exp) % mod. Uses the Montgomery multiplication
762 * technique where possible, falling back to modpow_simple otherwise.
764 Bignum
modpow(Bignum base_in
, Bignum exp
, Bignum mod
)
766 BignumInt
*a
, *b
, *x
, *n
, *mninv
, *scratch
;
767 int len
, scratchlen
, i
, j
;
768 Bignum base
, base2
, r
, rn
, inv
, result
;
771 * The most significant word of mod needs to be non-zero. It
772 * should already be, but let's make sure.
774 assert(mod
[mod
[0]] != 0);
777 * mod had better be odd, or we can't do Montgomery multiplication
778 * using a power of two at all.
781 return modpow_simple(base_in
, exp
, mod
);
784 * Make sure the base is smaller than the modulus, by reducing
785 * it modulo the modulus if not.
787 base
= bigmod(base_in
, mod
);
790 * Compute the inverse of n mod r, for monty_reduce. (In fact we
791 * want the inverse of _minus_ n mod r, but we'll sort that out
795 r
= bn_power_2(BIGNUM_INT_BITS
* len
);
796 inv
= modinv(mod
, r
);
799 * Multiply the base by r mod n, to get it into Montgomery
802 base2
= modmul(base
, r
, mod
);
806 rn
= bigmod(r
, mod
); /* r mod n, i.e. Montgomerified 1 */
808 freebn(r
); /* won't need this any more */
811 * Set up internal arrays of the right lengths containing the base,
812 * the modulus, and the modulus's inverse.
814 n
= snewn(len
, BignumInt
);
815 for (j
= 0; j
< len
; j
++)
818 mninv
= snewn(len
, BignumInt
);
819 for (j
= 0; j
< len
; j
++)
820 mninv
[j
] = (j
< (int)inv
[0] ? inv
[j
+ 1] : 0);
821 freebn(inv
); /* we don't need this copy of it any more */
822 /* Now negate mninv mod r, so it's the inverse of -n rather than +n. */
823 x
= snewn(len
, BignumInt
);
824 for (j
= 0; j
< len
; j
++)
826 internal_sub(x
, mninv
, mninv
, len
);
828 /* x = snewn(len, BignumInt); */ /* already done above */
829 for (j
= 0; j
< len
; j
++)
830 x
[j
] = (j
< (int)base
[0] ? base
[j
+ 1] : 0);
831 freebn(base
); /* we don't need this copy of it any more */
833 a
= snewn(2*len
, BignumInt
);
834 b
= snewn(2*len
, BignumInt
);
835 for (j
= 0; j
< len
; j
++)
836 a
[j
] = (j
< (int)rn
[0] ? rn
[j
+ 1] : 0);
839 /* Scratch space for multiplies */
840 scratchlen
= 3*len
+ mul_compute_scratch(len
);
841 scratch
= snewn(scratchlen
, BignumInt
);
843 /* Skip leading zero bits of exp. */
845 j
= BIGNUM_INT_BITS
-1;
846 while (i
< (int)exp
[0] && (exp
[exp
[0] - i
] & (1 << j
)) == 0) {
850 j
= BIGNUM_INT_BITS
-1;
854 /* Main computation */
855 while (i
< (int)exp
[0]) {
857 internal_mul(a
, a
, b
, len
, scratch
);
858 monty_reduce(b
, n
, mninv
, scratch
, len
);
859 if ((exp
[exp
[0] - i
] & (1 << j
)) != 0) {
860 internal_mul(b
, x
, a
, len
, scratch
);
861 monty_reduce(a
, n
, mninv
, scratch
, len
);
871 j
= BIGNUM_INT_BITS
-1;
875 * Final monty_reduce to get back from the adjusted Montgomery
878 monty_reduce(a
, n
, mninv
, scratch
, len
);
880 /* Copy result to buffer */
881 result
= newbn(mod
[0]);
882 for (i
= 0; i
< len
; i
++)
883 result
[i
+ 1] = a
[i
];
884 while (result
[0] > 1 && result
[result
[0]] == 0)
887 /* Free temporary arrays */
888 for (i
= 0; i
< scratchlen
; i
++)
891 for (i
= 0; i
< 2 * len
; i
++)
894 for (i
= 0; i
< 2 * len
; i
++)
897 for (i
= 0; i
< len
; i
++)
900 for (i
= 0; i
< len
; i
++)
903 for (i
= 0; i
< len
; i
++)
911 * Compute (p * q) % mod.
912 * The most significant word of mod MUST be non-zero.
913 * We assume that the result array is the same size as the mod array.
915 Bignum
modmul(Bignum p
, Bignum q
, Bignum mod
)
917 BignumInt
*a
, *n
, *m
, *o
, *scratch
;
918 int mshift
, scratchlen
;
919 int pqlen
, mlen
, rlen
, i
, j
;
922 /* Allocate m of size mlen, copy mod to m */
924 m
= snewn(mlen
, BignumInt
);
925 for (j
= 0; j
< mlen
; j
++)
928 /* Shift m left to make msb bit set */
929 for (mshift
= 0; mshift
< BIGNUM_INT_BITS
-1; mshift
++)
930 if ((m
[mlen
- 1] << mshift
) & BIGNUM_TOP_BIT
)
933 shift_left(m
, mlen
, mshift
);
935 pqlen
= (p
[0] > q
[0] ? p
[0] : q
[0]);
937 /* Make sure that we're allowing enough space. The shifting below will
938 * underflow the vectors we allocate if `pqlen' is too small.
943 /* Allocate n of size pqlen, copy p to n */
944 n
= snewn(pqlen
, BignumInt
);
945 for (i
= 0; i
< (int)p
[0]; i
++)
947 for (; i
< pqlen
; i
++)
950 /* Allocate o of size pqlen, copy q to o */
951 o
= snewn(pqlen
, BignumInt
);
952 for (i
= 0; i
< (int)q
[0]; i
++)
954 for (; i
< pqlen
; i
++)
957 /* Allocate a of size 2*pqlen for result */
958 a
= snewn(2 * pqlen
, BignumInt
);
960 /* Scratch space for multiplies */
961 scratchlen
= mul_compute_scratch(pqlen
);
962 scratch
= snewn(scratchlen
, BignumInt
);
964 /* Main computation */
965 internal_mul(n
, o
, a
, pqlen
, scratch
);
966 internal_mod(a
, pqlen
* 2, m
, mlen
, NULL
, 0);
968 /* Fixup result in case the modulus was shifted */
970 shift_left(a
, mlen
+ 1, mshift
);
971 internal_mod(a
, mlen
+ 1, m
, mlen
, NULL
, 0);
972 shift_right(a
, mlen
, mshift
);
975 /* Copy result to buffer */
976 rlen
= (mlen
< pqlen
* 2 ? mlen
: pqlen
* 2);
977 result
= newbn(rlen
);
978 for (i
= 0; i
< rlen
; i
++)
979 result
[i
+ 1] = a
[i
];
980 while (result
[0] > 1 && result
[result
[0]] == 0)
983 /* Free temporary arrays */
984 for (i
= 0; i
< scratchlen
; i
++)
987 for (i
= 0; i
< 2 * pqlen
; i
++)
990 for (i
= 0; i
< mlen
; i
++)
993 for (i
= 0; i
< pqlen
; i
++)
996 for (i
= 0; i
< pqlen
; i
++)
1005 * The most significant word of mod MUST be non-zero.
1006 * We assume that the result array is the same size as the mod array.
1007 * We optionally write out a quotient if `quotient' is non-NULL.
1008 * We can avoid writing out the result if `result' is NULL.
1010 static void bigdivmod(Bignum p
, Bignum mod
, Bignum result
, Bignum quotient
)
1014 int plen
, mlen
, i
, j
;
1016 /* Allocate m of size mlen, copy mod to m */
1018 m
= snewn(mlen
, BignumInt
);
1019 for (j
= 0; j
< mlen
; j
++)
1022 /* Shift m left to make msb bit set */
1023 for (mshift
= 0; mshift
< BIGNUM_INT_BITS
-1; mshift
++)
1024 if ((m
[mlen
- 1] << mshift
) & BIGNUM_TOP_BIT
)
1027 shift_left(m
, mlen
, mshift
);
1030 /* Ensure plen > mlen */
1034 /* Allocate n of size plen, copy p to n */
1035 n
= snewn(plen
, BignumInt
);
1036 for (i
= 0; i
< (int)p
[0]; i
++)
1038 for (; i
< plen
; i
++)
1041 /* Main computation */
1042 internal_mod(n
, plen
, m
, mlen
, quotient
, mshift
);
1044 /* Fixup result in case the modulus was shifted */
1046 shift_left(n
, mlen
+ 1, mshift
);
1047 internal_mod(n
, plen
, m
, mlen
, quotient
, 0);
1048 shift_right(n
, mlen
, mshift
);
1051 /* Copy result to buffer */
1053 for (i
= 0; i
< (int)result
[0]; i
++)
1054 result
[i
+ 1] = i
< plen ? n
[i
] : 0;
1055 bn_restore_invariant(result
);
1058 /* Free temporary arrays */
1059 for (i
= 0; i
< mlen
; i
++)
1062 for (i
= 0; i
< plen
; i
++)
1068 * Decrement a number.
1070 void decbn(Bignum bn
)
1073 while (i
< (int)bn
[0] && bn
[i
] == 0)
1074 bn
[i
++] = BIGNUM_INT_MASK
;
1078 Bignum
bignum_from_bytes(const unsigned char *data
, int nbytes
)
1083 w
= (nbytes
+ BIGNUM_INT_BYTES
- 1) / BIGNUM_INT_BYTES
; /* bytes->words */
1086 for (i
= 1; i
<= w
; i
++)
1088 for (i
= nbytes
; i
--;) {
1089 unsigned char byte
= *data
++;
1090 result
[1 + i
/ BIGNUM_INT_BYTES
] |= byte
<< (8*i
% BIGNUM_INT_BITS
);
1093 while (result
[0] > 1 && result
[result
[0]] == 0)
1099 * Read an SSH-1-format bignum from a data buffer. Return the number
1100 * of bytes consumed, or -1 if there wasn't enough data.
1102 int ssh1_read_bignum(const unsigned char *data
, int len
, Bignum
* result
)
1104 const unsigned char *p
= data
;
1112 for (i
= 0; i
< 2; i
++)
1113 w
= (w
<< 8) + *p
++;
1114 b
= (w
+ 7) / 8; /* bits -> bytes */
1119 if (!result
) /* just return length */
1122 *result
= bignum_from_bytes(p
, b
);
1124 return p
+ b
- data
;
1128 * Return the bit count of a bignum, for SSH-1 encoding.
1130 int bignum_bitcount(Bignum bn
)
1132 int bitcount
= bn
[0] * BIGNUM_INT_BITS
- 1;
1133 while (bitcount
>= 0
1134 && (bn
[bitcount
/ BIGNUM_INT_BITS
+ 1] >> (bitcount
% BIGNUM_INT_BITS
)) == 0) bitcount
--;
1135 return bitcount
+ 1;
1139 * Return the byte length of a bignum when SSH-1 encoded.
1141 int ssh1_bignum_length(Bignum bn
)
1143 return 2 + (bignum_bitcount(bn
) + 7) / 8;
1147 * Return the byte length of a bignum when SSH-2 encoded.
1149 int ssh2_bignum_length(Bignum bn
)
1151 return 4 + (bignum_bitcount(bn
) + 8) / 8;
1155 * Return a byte from a bignum; 0 is least significant, etc.
1157 int bignum_byte(Bignum bn
, int i
)
1159 if (i
>= (int)(BIGNUM_INT_BYTES
* bn
[0]))
1160 return 0; /* beyond the end */
1162 return (bn
[i
/ BIGNUM_INT_BYTES
+ 1] >>
1163 ((i
% BIGNUM_INT_BYTES
)*8)) & 0xFF;
1167 * Return a bit from a bignum; 0 is least significant, etc.
1169 int bignum_bit(Bignum bn
, int i
)
1171 if (i
>= (int)(BIGNUM_INT_BITS
* bn
[0]))
1172 return 0; /* beyond the end */
1174 return (bn
[i
/ BIGNUM_INT_BITS
+ 1] >> (i
% BIGNUM_INT_BITS
)) & 1;
1178 * Set a bit in a bignum; 0 is least significant, etc.
1180 void bignum_set_bit(Bignum bn
, int bitnum
, int value
)
1182 if (bitnum
>= (int)(BIGNUM_INT_BITS
* bn
[0]))
1183 abort(); /* beyond the end */
1185 int v
= bitnum
/ BIGNUM_INT_BITS
+ 1;
1186 int mask
= 1 << (bitnum
% BIGNUM_INT_BITS
);
1195 * Write a SSH-1-format bignum into a buffer. It is assumed the
1196 * buffer is big enough. Returns the number of bytes used.
1198 int ssh1_write_bignum(void *data
, Bignum bn
)
1200 unsigned char *p
= data
;
1201 int len
= ssh1_bignum_length(bn
);
1203 int bitc
= bignum_bitcount(bn
);
1205 *p
++ = (bitc
>> 8) & 0xFF;
1206 *p
++ = (bitc
) & 0xFF;
1207 for (i
= len
- 2; i
--;)
1208 *p
++ = bignum_byte(bn
, i
);
1213 * Compare two bignums. Returns like strcmp.
1215 int bignum_cmp(Bignum a
, Bignum b
)
1217 int amax
= a
[0], bmax
= b
[0];
1218 int i
= (amax
> bmax ? amax
: bmax
);
1220 BignumInt aval
= (i
> amax ?
0 : a
[i
]);
1221 BignumInt bval
= (i
> bmax ?
0 : b
[i
]);
1232 * Right-shift one bignum to form another.
1234 Bignum
bignum_rshift(Bignum a
, int shift
)
1237 int i
, shiftw
, shiftb
, shiftbb
, bits
;
1240 bits
= bignum_bitcount(a
) - shift
;
1241 ret
= newbn((bits
+ BIGNUM_INT_BITS
- 1) / BIGNUM_INT_BITS
);
1244 shiftw
= shift
/ BIGNUM_INT_BITS
;
1245 shiftb
= shift
% BIGNUM_INT_BITS
;
1246 shiftbb
= BIGNUM_INT_BITS
- shiftb
;
1248 ai1
= a
[shiftw
+ 1];
1249 for (i
= 1; i
<= (int)ret
[0]; i
++) {
1251 ai1
= (i
+ shiftw
+ 1 <= (int)a
[0] ? a
[i
+ shiftw
+ 1] : 0);
1252 ret
[i
] = ((ai
>> shiftb
) | (ai1
<< shiftbb
)) & BIGNUM_INT_MASK
;
1260 * Non-modular multiplication and addition.
1262 Bignum
bigmuladd(Bignum a
, Bignum b
, Bignum addend
)
1264 int alen
= a
[0], blen
= b
[0];
1265 int mlen
= (alen
> blen ? alen
: blen
);
1266 int rlen
, i
, maxspot
;
1268 BignumInt
*workspace
;
1271 /* mlen space for a, mlen space for b, 2*mlen for result,
1272 * plus scratch space for multiplication */
1273 wslen
= mlen
* 4 + mul_compute_scratch(mlen
);
1274 workspace
= snewn(wslen
, BignumInt
);
1275 for (i
= 0; i
< mlen
; i
++) {
1276 workspace
[0 * mlen
+ i
] = i
< (int)a
[0] ? a
[i
+ 1] : 0;
1277 workspace
[1 * mlen
+ i
] = i
< (int)b
[0] ? b
[i
+ 1] : 0;
1280 internal_mul(workspace
+ 0 * mlen
, workspace
+ 1 * mlen
,
1281 workspace
+ 2 * mlen
, mlen
, workspace
+ 4 * mlen
);
1283 /* now just copy the result back */
1284 rlen
= alen
+ blen
+ 1;
1285 if (addend
&& rlen
<= (int)addend
[0])
1286 rlen
= addend
[0] + 1;
1289 for (i
= 0; i
< (int)ret
[0]; i
++) {
1290 ret
[i
+ 1] = (i
< 2 * mlen ? workspace
[2 * mlen
+ i
] : 0);
1291 if (ret
[i
+ 1] != 0)
1296 /* now add in the addend, if any */
1298 BignumDblInt carry
= 0;
1299 for (i
= 1; i
<= rlen
; i
++) {
1300 carry
+= (i
<= (int)ret
[0] ? ret
[i
] : 0);
1301 carry
+= (i
<= (int)addend
[0] ? addend
[i
] : 0);
1302 ret
[i
] = (BignumInt
) carry
& BIGNUM_INT_MASK
;
1303 carry
>>= BIGNUM_INT_BITS
;
1304 if (ret
[i
] != 0 && i
> maxspot
)
1310 for (i
= 0; i
< wslen
; i
++)
1317 * Non-modular multiplication.
1319 Bignum
bigmul(Bignum a
, Bignum b
)
1321 return bigmuladd(a
, b
, NULL
);
1327 Bignum
bigadd(Bignum a
, Bignum b
)
1329 int alen
= a
[0], blen
= b
[0];
1330 int rlen
= (alen
> blen ? alen
: blen
) + 1;
1339 for (i
= 1; i
<= rlen
; i
++) {
1340 carry
+= (i
<= (int)a
[0] ? a
[i
] : 0);
1341 carry
+= (i
<= (int)b
[0] ? b
[i
] : 0);
1342 ret
[i
] = (BignumInt
) carry
& BIGNUM_INT_MASK
;
1343 carry
>>= BIGNUM_INT_BITS
;
1344 if (ret
[i
] != 0 && i
> maxspot
)
1353 * Subtraction. Returns a-b, or NULL if the result would come out
1354 * negative (recall that this entire bignum module only handles
1355 * positive numbers).
1357 Bignum
bigsub(Bignum a
, Bignum b
)
1359 int alen
= a
[0], blen
= b
[0];
1360 int rlen
= (alen
> blen ? alen
: blen
);
1369 for (i
= 1; i
<= rlen
; i
++) {
1370 carry
+= (i
<= (int)a
[0] ? a
[i
] : 0);
1371 carry
+= (i
<= (int)b
[0] ? b
[i
] ^ BIGNUM_INT_MASK
: BIGNUM_INT_MASK
);
1372 ret
[i
] = (BignumInt
) carry
& BIGNUM_INT_MASK
;
1373 carry
>>= BIGNUM_INT_BITS
;
1374 if (ret
[i
] != 0 && i
> maxspot
)
1388 * Return a bignum which is the result of shifting another left by N bits.
1389 * If N is negative then you get a right shift instead.
1391 Bignum
biglsl(Bignum x
, int n
)
1396 /* Eliminate some simple special cases. */
1397 if (!n
|| !x
[0]) return copybn(x
);
1398 else if (n
< 0) return biglsr(x
, -n
);
1400 /* Some initial setup. */
1401 o
= n
/BIGNUM_INT_BITS
;
1402 n
%= BIGNUM_INT_BITS
;
1403 d
= newbn(x
[0] + o
+ !!n
);
1405 /* Clear the low-significant words of d. */
1406 for (i
= 1; i
<= o
; i
++) d
[i
] = 0;
1409 /* Easy case: we're shifting by a multiple of the word size, so we
1410 * can just copy whole words.
1412 for (i
= 1; i
<= x
[0]; i
++) d
[o
+ i
] = x
[i
];
1414 /* Hard case: destination words can be a combination of two source
1418 /* Take the low bits from the least significant source word. */
1419 d
[o
+ 1] = x
[1] << n
;
1421 /* The intermediate words really are a combination of two source
1424 for (i
= 2; i
<= x
[0]; i
++)
1425 d
[o
+ i
] = (x
[i
] << n
) | (x
[i
- 1] >> (BIGNUM_INT_BITS
- n
));
1427 /* Finally, the high bits of the most significant input word. */
1428 d
[o
+ i
+ 1] = x
[i
] >> (BIGNUM_INT_BITS
- n
);
1431 /* The destination length is a conservative estimate, so we'll need to
1434 bn_restore_invariant(d
);
1441 * Return a bignum which is the result of shifting another right by N bits
1442 * (discarding the least significant N bits, and shifting zeroes in at the
1443 * most significant end). If N is negative then you get a left shift
1446 Bignum
biglsr(Bignum x
, int n
)
1451 /* Eliminate some simple special cases. */
1452 if (!n
|| !x
[0]) return copybn(x
);
1453 else if (n
< 0) return biglsl(x
, -n
);
1455 /* Some initial setup. */
1456 o
= n
/BIGNUM_INT_BITS
;
1457 n
%= BIGNUM_INT_BITS
;
1458 d
= newbn(x
[0] - o
);
1461 /* Simple case: we're shifting by a multiple of the word size, so we
1462 * can just copy whole words across.
1464 for (i
= o
+ 1; i
<= x
[0]; i
++) d
[i
- o
] = x
[i
];
1466 /* Hard case: some destination words will be a combination of two
1467 * source words. We get to discard some of the input words.
1470 /* The intermediate words are combinations of two input words. */
1471 for (i
= o
+ 1; i
< x
[0]; i
++)
1472 d
[i
- o
] = (x
[i
] >> n
) | (x
[i
+ 1] << (BIGNUM_INT_BITS
- n
));
1474 /* And finally the high-significance bits of the top source word. */
1475 d
[i
- o
+ 1] = x
[i
] << (BIGNUM_INT_BITS
- n
);
1478 /* The destination length is a conservative estimate, so we'll need to
1481 bn_restore_invariant(d
);
1483 /* And we're done. */
1488 * Create a bignum which is the bitmask covering another one. That
1489 * is, the smallest integer which is >= N and is also one less than
1492 Bignum
bignum_bitmask(Bignum n
)
1494 Bignum ret
= copybn(n
);
1499 while (n
[i
] == 0 && i
> 0)
1502 return ret
; /* input was zero */
1508 ret
[i
] = BIGNUM_INT_MASK
;
1513 * Convert a (max 32-bit) long into a bignum.
1515 Bignum
bignum_from_long(unsigned long nn
)
1518 BignumDblInt n
= nn
;
1521 ret
[1] = (BignumInt
)(n
& BIGNUM_INT_MASK
);
1522 ret
[2] = (BignumInt
)((n
>> BIGNUM_INT_BITS
) & BIGNUM_INT_MASK
);
1524 ret
[0] = (ret
[2] ?
2 : 1);
1529 * Add a long to a bignum.
1531 Bignum
bignum_add_long(Bignum number
, unsigned long addendx
)
1533 Bignum ret
= newbn(number
[0] + 1);
1535 BignumDblInt carry
= 0, addend
= addendx
;
1537 for (i
= 1; i
<= (int)ret
[0]; i
++) {
1538 carry
+= addend
& BIGNUM_INT_MASK
;
1539 carry
+= (i
<= (int)number
[0] ? number
[i
] : 0);
1540 addend
>>= BIGNUM_INT_BITS
;
1541 ret
[i
] = (BignumInt
) carry
& BIGNUM_INT_MASK
;
1542 carry
>>= BIGNUM_INT_BITS
;
1551 * Compute the residue of a bignum, modulo a (max 16-bit) short.
1553 unsigned short bignum_mod_short(Bignum number
, unsigned short modulus
)
1555 BignumDblInt mod
, r
;
1560 for (i
= number
[0]; i
> 0; i
--)
1561 r
= (r
* (BIGNUM_TOP_BIT
% mod
) * 2 + number
[i
] % mod
) % mod
;
1562 return (unsigned short) r
;
1566 void diagbn(char *prefix
, Bignum md
)
1568 int i
, nibbles
, morenibbles
;
1569 static const char hex
[] = "0123456789ABCDEF";
1571 debug(("%s0x", prefix ? prefix
: ""));
1573 nibbles
= (3 + bignum_bitcount(md
)) / 4;
1576 morenibbles
= 4 * md
[0] - nibbles
;
1577 for (i
= 0; i
< morenibbles
; i
++)
1579 for (i
= nibbles
; i
--;)
1581 hex
[(bignum_byte(md
, i
/ 2) >> (4 * (i
% 2))) & 0xF]));
1591 Bignum
bigdiv(Bignum a
, Bignum b
)
1593 Bignum q
= newbn(a
[0]);
1594 bigdivmod(a
, b
, NULL
, q
);
1601 Bignum
bigmod(Bignum a
, Bignum b
)
1603 Bignum r
= newbn(b
[0]);
1604 bigdivmod(a
, b
, r
, NULL
);
1609 * Greatest common divisor.
1611 Bignum
biggcd(Bignum av
, Bignum bv
)
1613 Bignum a
= copybn(av
);
1614 Bignum b
= copybn(bv
);
1616 while (bignum_cmp(b
, Zero
) != 0) {
1617 Bignum t
= newbn(b
[0]);
1618 bigdivmod(a
, b
, t
, NULL
);
1619 while (t
[0] > 1 && t
[t
[0]] == 0)
1631 * Modular inverse, using Euclid's extended algorithm.
1633 Bignum
modinv(Bignum number
, Bignum modulus
)
1635 Bignum a
= copybn(modulus
);
1636 Bignum b
= copybn(number
);
1637 Bignum xp
= copybn(Zero
);
1638 Bignum x
= copybn(One
);
1641 while (bignum_cmp(b
, One
) != 0) {
1642 Bignum t
= newbn(b
[0]);
1643 Bignum q
= newbn(a
[0]);
1644 bigdivmod(a
, b
, t
, q
);
1645 while (t
[0] > 1 && t
[t
[0]] == 0)
1652 x
= bigmuladd(q
, xp
, t
);
1662 /* now we know that sign * x == 1, and that x < modulus */
1664 /* set a new x to be modulus - x */
1665 Bignum newx
= newbn(modulus
[0]);
1666 BignumInt carry
= 0;
1670 for (i
= 1; i
<= (int)newx
[0]; i
++) {
1671 BignumInt aword
= (i
<= (int)modulus
[0] ? modulus
[i
] : 0);
1672 BignumInt bword
= (i
<= (int)x
[0] ? x
[i
] : 0);
1673 newx
[i
] = aword
- bword
- carry
;
1675 carry
= carry ?
(newx
[i
] >= bword
) : (newx
[i
] > bword
);
1689 * Extract the largest power of 2 dividing x, storing it in p2, and returning
1690 * the product of the remaining factors.
1692 static Bignum
extract_p2(Bignum x
, unsigned *p2
)
1694 unsigned i
, j
, k
, n
;
1697 /* If x is zero then the following won't work. And if x is odd then
1698 * there's nothing very useful to do.
1700 if (!x
[0] || (x
[1] & 1)) {
1705 /* Find the power of two. */
1706 for (i
= 0; !x
[i
+ 1]; i
++);
1707 for (j
= 0; !((x
[i
+ 1] >> j
) & 1); j
++);
1708 *p2
= i
*BIGNUM_INT_BITS
+ j
;
1710 /* Work out how big the copy should be. */
1712 if (x
[x
[0]] >> j
) n
++;
1714 /* Copy and shift down. */
1716 for (k
= 1; k
<= n
; k
++) {
1717 y
[k
] = x
[k
+ i
] >> j
;
1718 if (j
&& k
< x
[0]) y
[k
] |= x
[k
+ i
+ 1] << (BIGNUM_INT_BITS
- j
);
1726 * Kronecker symbol (a|n). The result is always in { -1, 0, +1 }, and is
1727 * zero if and only if a and n have a nontrivial common factor. Most
1728 * usefully, if n is prime, this is the Legendre symbol, taking the value +1
1729 * if a is a quadratic residue mod n, and -1 otherwise; i.e., (a|p) ==
1730 * a^{(p-1)/2} (mod p).
1732 int kronecker(Bignum a
, Bignum n
)
1738 /* Special case for n = 0. This is the same convention PARI uses,
1739 * except that we can't represent negative numbers.
1741 if (bignum_cmp(n
, Zero
) == 0) {
1742 if (bignum_cmp(a
, One
) == 0) return +1;
1746 /* Write n = 2^s t, with t odd. If s > 0 and a is even, then the answer
1747 * is zero; otherwise throw in a factor of (-1)^s if a == 3 or 5 (mod 8).
1749 * At this point, we have a copy of n, and must remember to free it when
1750 * we're done. It's convenient to take a copy of a at the same time.
1753 n
= extract_p2(n
, &s
);
1755 if (s
&& (!a
[0] || !(a
[1] & 1))) { r
= 0; goto done
; }
1756 else if ((s
& 1) && ((a
[1] & 7) == 3 || (a
[1] & 7) == 5)) r
= -r
;
1758 /* If n is (now) a unit then we're done. */
1759 if (bignum_cmp(n
, One
) == 0) goto done
;
1761 /* Reduce a modulo n before we go any further. */
1762 if (bignum_cmp(a
, n
) >= 0) { t
= bigmod(a
, n
); freebn(a
); a
= t
; }
1766 if (bignum_cmp(a
, Zero
) == 0) { r
= 0; goto done
; }
1768 /* Strip out and handle powers of two from a. */
1769 t
= extract_p2(a
, &s
); freebn(a
); a
= t
;
1771 if ((s
& 1) && (nn
== 3 || nn
== 5)) r
= -r
;
1772 if (bignum_cmp(a
, One
) == 0) break;
1774 /* Swap, applying quadratic reciprocity. */
1775 if ((nn
& 3) == 3 && (a
[1] & 3) == 3) r
= -r
;
1776 t
= bigmod(n
, a
); freebn(n
); n
= a
; a
= t
;
1779 /* Tidy up: we're done. */
1781 freebn(a
); freebn(n
);
1786 * Modular square root. We must have p prime: extracting square roots modulo
1787 * composites is equivalent to factoring (but we don't check: you'll just get
1788 * the wrong answer). Returns NULL if x is not a quadratic residue mod p.
1790 Bignum
modsqrt(Bignum x
, Bignum p
)
1792 Bignum xinv
, b
, c
, r
, t
, z
, X
, mone
;
1795 /* If x is not a quadratic residue then we will not go to space today. */
1796 if (kronecker(x
, p
) != +1) return NULL
;
1798 /* We need a quadratic nonresidue from somewhere. Exactly half of all
1799 * units mod p are quadratic residues, but no efficient deterministic
1800 * algorithm for finding one is known. So pick at random: we don't
1801 * expect this to take long.
1805 for (i
= 1; i
<= p
[0]; i
++) z
[i
] = rand();
1806 z
[0] = p
[0]; bn_restore_invariant(z
);
1807 } while (kronecker(z
, p
) != -1);
1808 b
= bigmod(z
, p
); freebn(z
);
1810 /* We need to compute a few things before we really get started. */
1811 xinv
= modinv(x
, p
); /* x^{-1} mod p */
1812 mone
= bigsub(p
, One
); /* p - 1 == -1 (mod p) */
1813 t
= extract_p2(mone
, &s
); /* 2^s t = p - 1 */
1814 c
= modpow(b
, t
, p
); /* b^t (mod p) */
1815 z
= bigadd(t
, One
); freebn(t
); t
= z
; /* (t + 1) */
1816 shift_right(t
+ 1, t
[0], 1); if (!t
[t
[0]]) t
[0]--;
1817 r
= modpow(x
, t
, p
); /* x^{(t+1)/2} (mod p) */
1818 freebn(b
); freebn(mone
); freebn(t
);
1820 /* OK, so how does this work anyway?
1822 * We know that x^t is somewhere in the order-2^s subgroup of GF(p)^*;
1823 * and g = c^{-1} is a generator for this subgroup (since we know that
1824 * g^{2^{s-1}} = b^{(p-1)/2} = (b|p) = -1); so x^t = g^m for some m. In
1825 * fact, we know that m is even because x is a square. Suppose we can
1826 * determine m; then we know that x^t/g^m = 1, so x^{t+1}/c^m = x -- but
1827 * both t + 1 and m are even, so x^{(t+1)/2}/g^{m/2} is a square root of
1830 * Conveniently, finding the discrete log of an element X in a group of
1831 * order 2^s is easy. Write X = g^m = g^{m_0+2k'}; then X^{2^{s-1}} =
1832 * g^{m_0 2^{s-1}} c^{m' 2^s} = g^{m_0 2^{s-1}} is either -1 or +1,
1833 * telling us that m_0 is 1 or 0 respectively. Then X/g^{m_0} =
1834 * (g^2)^{m'} has order 2^{s-1} so we can continue inductively. What we
1835 * end up with at the end is X/g^m.
1837 * There are a few wrinkles. As we proceed through the induction, the
1838 * generator for the subgroup will be c^{-2}, since we know that m is
1839 * even. While we want the discrete log of X = x^t, we're actually going
1840 * to keep track of r, which will eventually be x^{(t+1)/2}/g^{m/2} =
1841 * x^{(t+1)/2} c^m, recovering X/g^m = r^2/x as we go. We don't actually
1842 * form the discrete log explicitly, because the final result will
1843 * actually be the square root we want.
1845 for (i
= 1; i
< s
; i
++) {
1847 /* Determine X. We could optimize this, only recomputing it when
1848 * it's been invalidated, but that's fiddlier and this isn't
1849 * performance critical.
1851 z
= modmul(r
, r
, p
);
1852 X
= modmul(z
, xinv
, p
);
1855 /* Determine X^{2^{s-1-i}}. */
1856 for (j
= i
+ 1; j
< s
; j
++)
1857 z
= modmul(X
, X
, p
), freebn(X
), X
= z
;
1859 /* Maybe accumulate a factor of c. */
1860 if (bignum_cmp(X
, One
) != 0)
1861 z
= modmul(r
, c
, p
), freebn(r
), r
= z
;
1863 /* Move on to the next smaller subgroup. */
1864 z
= modmul(c
, c
, p
), freebn(c
), c
= z
;
1868 /* Of course, there are two square roots of x. For predictability's sake
1869 * we'll always return the one in [1..(p - 1)/2]. The other is, of
1873 if (bignum_cmp(r
, z
) < 0)
1881 freebn(xinv
); freebn(c
);
1886 * Render a bignum into decimal. Return a malloced string holding
1887 * the decimal representation.
1889 char *bignum_decimal(Bignum x
)
1891 int ndigits
, ndigit
;
1895 BignumInt
*workspace
;
1898 * First, estimate the number of digits. Since log(10)/log(2)
1899 * is just greater than 93/28 (the joys of continued fraction
1900 * approximations...) we know that for every 93 bits, we need
1901 * at most 28 digits. This will tell us how much to malloc.
1903 * Formally: if x has i bits, that means x is strictly less
1904 * than 2^i. Since 2 is less than 10^(28/93), this is less than
1905 * 10^(28i/93). We need an integer power of ten, so we must
1906 * round up (rounding down might make it less than x again).
1907 * Therefore if we multiply the bit count by 28/93, rounding
1908 * up, we will have enough digits.
1910 * i=0 (i.e., x=0) is an irritating special case.
1912 i
= bignum_bitcount(x
);
1914 ndigits
= 1; /* x = 0 */
1916 ndigits
= (28 * i
+ 92) / 93; /* multiply by 28/93 and round up */
1917 ndigits
++; /* allow for trailing \0 */
1918 ret
= snewn(ndigits
, char);
1921 * Now allocate some workspace to hold the binary form as we
1922 * repeatedly divide it by ten. Initialise this to the
1923 * big-endian form of the number.
1925 workspace
= snewn(x
[0], BignumInt
);
1926 for (i
= 0; i
< (int)x
[0]; i
++)
1927 workspace
[i
] = x
[x
[0] - i
];
1930 * Next, write the decimal number starting with the last digit.
1931 * We use ordinary short division, dividing 10 into the
1934 ndigit
= ndigits
- 1;
1939 for (i
= 0; i
< (int)x
[0]; i
++) {
1940 carry
= (carry
<< BIGNUM_INT_BITS
) + workspace
[i
];
1941 workspace
[i
] = (BignumInt
) (carry
/ 10);
1946 ret
[--ndigit
] = (char) (carry
+ '0');
1950 * There's a chance we've fallen short of the start of the
1951 * string. Correct if so.
1954 memmove(ret
, ret
+ ndigit
, ndigits
- ndigit
);
1970 * gcc -Wall -g -O0 -DTESTBN -o testbn sshbn.c misc.c conf.c tree234.c unix/uxmisc.c -I. -I unix -I charset
1972 * Then feed to this program's standard input the output of
1973 * testdata/bignum.py .
1976 void modalfatalbox(char *p
, ...)
1979 fprintf(stderr
, "FATAL ERROR: ");
1981 vfprintf(stderr
, p
, ap
);
1983 fputc('\n', stderr
);
1987 #define fromxdigit(c) ( (c)>'9' ? ((c)&0xDF) - 'A' + 10 : (c) - '0' )
1989 int main(int argc
, char **argv
)
1993 int passes
= 0, fails
= 0;
1995 while ((buf
= fgetline(stdin
)) != NULL
) {
1996 int maxlen
= strlen(buf
);
1997 unsigned char *data
= snewn(maxlen
, unsigned char);
1998 unsigned char *ptrs
[5], *q
;
2007 while (*bufp
&& !isspace((unsigned char)*bufp
))
2016 while (*bufp
&& !isxdigit((unsigned char)*bufp
))
2023 while (*bufp
&& isxdigit((unsigned char)*bufp
))
2027 if (ptrnum
>= lenof(ptrs
))
2031 for (i
= -((end
- start
) & 1); i
< end
-start
; i
+= 2) {
2032 unsigned char val
= (i
< 0 ?
0 : fromxdigit(start
[i
]));
2033 val
= val
* 16 + fromxdigit(start
[i
+1]);
2040 if (!strcmp(buf
, "mul")) {
2044 printf("%d: mul with %d parameters, expected 3\n", line
, ptrnum
);
2047 a
= bignum_from_bytes(ptrs
[0], ptrs
[1]-ptrs
[0]);
2048 b
= bignum_from_bytes(ptrs
[1], ptrs
[2]-ptrs
[1]);
2049 c
= bignum_from_bytes(ptrs
[2], ptrs
[3]-ptrs
[2]);
2052 if (bignum_cmp(c
, p
) == 0) {
2055 char *as
= bignum_decimal(a
);
2056 char *bs
= bignum_decimal(b
);
2057 char *cs
= bignum_decimal(c
);
2058 char *ps
= bignum_decimal(p
);
2060 printf("%d: fail: %s * %s gave %s expected %s\n",
2061 line
, as
, bs
, ps
, cs
);
2073 } else if (!strcmp(buf
, "pow")) {
2074 Bignum base
, expt
, modulus
, expected
, answer
;
2077 printf("%d: mul with %d parameters, expected 4\n", line
, ptrnum
);
2081 base
= bignum_from_bytes(ptrs
[0], ptrs
[1]-ptrs
[0]);
2082 expt
= bignum_from_bytes(ptrs
[1], ptrs
[2]-ptrs
[1]);
2083 modulus
= bignum_from_bytes(ptrs
[2], ptrs
[3]-ptrs
[2]);
2084 expected
= bignum_from_bytes(ptrs
[3], ptrs
[4]-ptrs
[3]);
2085 answer
= modpow(base
, expt
, modulus
);
2087 if (bignum_cmp(expected
, answer
) == 0) {
2090 char *as
= bignum_decimal(base
);
2091 char *bs
= bignum_decimal(expt
);
2092 char *cs
= bignum_decimal(modulus
);
2093 char *ds
= bignum_decimal(answer
);
2094 char *ps
= bignum_decimal(expected
);
2096 printf("%d: fail: %s ^ %s mod %s gave %s expected %s\n",
2097 line
, as
, bs
, cs
, ds
, ps
);
2111 } else if (!strcmp(buf
, "modsqrt")) {
2112 Bignum x
, p
, expected
, answer
;
2115 printf("%d: modsqrt with %d parameters, expected 3\n", line
, ptrnum
);
2119 x
= bignum_from_bytes(ptrs
[0], ptrs
[1]-ptrs
[0]);
2120 p
= bignum_from_bytes(ptrs
[1], ptrs
[2]-ptrs
[1]);
2121 expected
= bignum_from_bytes(ptrs
[2], ptrs
[3]-ptrs
[2]);
2122 answer
= modsqrt(x
, p
);
2124 answer
= copybn(Zero
);
2126 if (bignum_cmp(expected
, answer
) == 0) {
2129 char *xs
= bignum_decimal(x
);
2130 char *ps
= bignum_decimal(p
);
2131 char *qs
= bignum_decimal(answer
);
2132 char *ws
= bignum_decimal(expected
);
2134 printf("%d: fail: sqrt(%s) mod %s gave %s expected %s\n",
2135 line
, xs
, ps
, qs
, ws
);
2148 printf("%d: unrecognised test keyword: '%s'\n", line
, buf
);
2156 printf("passed %d failed %d total %d\n", passes
, fails
, passes
+fails
);