The bignum code has two representations of zero, since
[u/mdw/putty] / sshbn.c
1 /*
2 * Bignum routines for RSA and DH and stuff.
3 */
4
5 #include <stdio.h>
6 #include <assert.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <limits.h>
10
11 #include "misc.h"
12
13 /*
14 * Usage notes:
15 * * Do not call the DIVMOD_WORD macro with expressions such as array
16 * subscripts, as some implementations object to this (see below).
17 * * Note that none of the division methods below will cope if the
18 * quotient won't fit into BIGNUM_INT_BITS. Callers should be careful
19 * to avoid this case.
20 * If this condition occurs, in the case of the x86 DIV instruction,
21 * an overflow exception will occur, which (according to a correspondent)
22 * will manifest on Windows as something like
23 * 0xC0000095: Integer overflow
24 * The C variant won't give the right answer, either.
25 */
26
27 #if defined __GNUC__ && defined __i386__
28 typedef unsigned long BignumInt;
29 typedef unsigned long long BignumDblInt;
30 #define BIGNUM_INT_MASK 0xFFFFFFFFUL
31 #define BIGNUM_TOP_BIT 0x80000000UL
32 #define BIGNUM_INT_BITS 32
33 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
34 #define DIVMOD_WORD(q, r, hi, lo, w) \
35 __asm__("div %2" : \
36 "=d" (r), "=a" (q) : \
37 "r" (w), "d" (hi), "a" (lo))
38 #elif defined _MSC_VER && defined _M_IX86
39 typedef unsigned __int32 BignumInt;
40 typedef unsigned __int64 BignumDblInt;
41 #define BIGNUM_INT_MASK 0xFFFFFFFFUL
42 #define BIGNUM_TOP_BIT 0x80000000UL
43 #define BIGNUM_INT_BITS 32
44 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
45 /* Note: MASM interprets array subscripts in the macro arguments as
46 * assembler syntax, which gives the wrong answer. Don't supply them.
47 * <http://msdn2.microsoft.com/en-us/library/bf1dw62z.aspx> */
48 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
49 __asm mov edx, hi \
50 __asm mov eax, lo \
51 __asm div w \
52 __asm mov r, edx \
53 __asm mov q, eax \
54 } while(0)
55 #elif defined _LP64
56 /* 64-bit architectures can do 32x32->64 chunks at a time */
57 typedef unsigned int BignumInt;
58 typedef unsigned long BignumDblInt;
59 #define BIGNUM_INT_MASK 0xFFFFFFFFU
60 #define BIGNUM_TOP_BIT 0x80000000U
61 #define BIGNUM_INT_BITS 32
62 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
63 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
64 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
65 q = n / w; \
66 r = n % w; \
67 } while (0)
68 #elif defined _LLP64
69 /* 64-bit architectures in which unsigned long is 32 bits, not 64 */
70 typedef unsigned long BignumInt;
71 typedef unsigned long long BignumDblInt;
72 #define BIGNUM_INT_MASK 0xFFFFFFFFUL
73 #define BIGNUM_TOP_BIT 0x80000000UL
74 #define BIGNUM_INT_BITS 32
75 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
76 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
77 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
78 q = n / w; \
79 r = n % w; \
80 } while (0)
81 #else
82 /* Fallback for all other cases */
83 typedef unsigned short BignumInt;
84 typedef unsigned long BignumDblInt;
85 #define BIGNUM_INT_MASK 0xFFFFU
86 #define BIGNUM_TOP_BIT 0x8000U
87 #define BIGNUM_INT_BITS 16
88 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
89 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
90 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
91 q = n / w; \
92 r = n % w; \
93 } while (0)
94 #endif
95
96 #define BIGNUM_INT_BYTES (BIGNUM_INT_BITS / 8)
97
98 #define BIGNUM_INTERNAL
99 typedef BignumInt *Bignum;
100
101 #include "ssh.h"
102
103 BignumInt bnZero[1] = { 0 };
104 BignumInt bnOne[2] = { 1, 1 };
105
106 /*
107 * The Bignum format is an array of `BignumInt'. The first
108 * element of the array counts the remaining elements. The
109 * remaining elements express the actual number, base 2^BIGNUM_INT_BITS, _least_
110 * significant digit first. (So it's trivial to extract the bit
111 * with value 2^n for any n.)
112 *
113 * All Bignums in this module are positive. Negative numbers must
114 * be dealt with outside it.
115 *
116 * INVARIANT: the most significant word of any Bignum must be
117 * nonzero.
118 */
119
120 Bignum Zero = bnZero, One = bnOne;
121
122 static Bignum newbn(int length)
123 {
124 Bignum b;
125
126 assert(length >= 0 && length < INT_MAX / BIGNUM_INT_BITS);
127
128 b = snewn(length + 1, BignumInt);
129 if (!b)
130 abort(); /* FIXME */
131 memset(b, 0, (length + 1) * sizeof(*b));
132 b[0] = length;
133 return b;
134 }
135
136 void bn_restore_invariant(Bignum b)
137 {
138 while (b[0] > 1 && b[b[0]] == 0)
139 b[0]--;
140 }
141
142 Bignum copybn(Bignum orig)
143 {
144 Bignum b = snewn(orig[0] + 1, BignumInt);
145 if (!b)
146 abort(); /* FIXME */
147 memcpy(b, orig, (orig[0] + 1) * sizeof(*b));
148 return b;
149 }
150
151 void freebn(Bignum b)
152 {
153 /*
154 * Burn the evidence, just in case.
155 */
156 smemclr(b, sizeof(b[0]) * (b[0] + 1));
157 sfree(b);
158 }
159
160 Bignum bn_power_2(int n)
161 {
162 Bignum ret;
163
164 assert(n >= 0);
165
166 ret = newbn(n / BIGNUM_INT_BITS + 1);
167 bignum_set_bit(ret, n, 1);
168 return ret;
169 }
170
171 /*
172 * Internal addition. Sets c = a - b, where 'a', 'b' and 'c' are all
173 * big-endian arrays of 'len' BignumInts. Returns a BignumInt carried
174 * off the top.
175 */
176 static BignumInt internal_add(const BignumInt *a, const BignumInt *b,
177 BignumInt *c, int len)
178 {
179 int i;
180 BignumDblInt carry = 0;
181
182 for (i = len-1; i >= 0; i--) {
183 carry += (BignumDblInt)a[i] + b[i];
184 c[i] = (BignumInt)carry;
185 carry >>= BIGNUM_INT_BITS;
186 }
187
188 return (BignumInt)carry;
189 }
190
191 /*
192 * Internal subtraction. Sets c = a - b, where 'a', 'b' and 'c' are
193 * all big-endian arrays of 'len' BignumInts. Any borrow from the top
194 * is ignored.
195 */
196 static void internal_sub(const BignumInt *a, const BignumInt *b,
197 BignumInt *c, int len)
198 {
199 int i;
200 BignumDblInt carry = 1;
201
202 for (i = len-1; i >= 0; i--) {
203 carry += (BignumDblInt)a[i] + (b[i] ^ BIGNUM_INT_MASK);
204 c[i] = (BignumInt)carry;
205 carry >>= BIGNUM_INT_BITS;
206 }
207 }
208
209 /*
210 * Compute c = a * b.
211 * Input is in the first len words of a and b.
212 * Result is returned in the first 2*len words of c.
213 *
214 * 'scratch' must point to an array of BignumInt of size at least
215 * mul_compute_scratch(len). (This covers the needs of internal_mul
216 * and all its recursive calls to itself.)
217 */
218 #define KARATSUBA_THRESHOLD 50
219 static int mul_compute_scratch(int len)
220 {
221 int ret = 0;
222 while (len > KARATSUBA_THRESHOLD) {
223 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
224 int midlen = botlen + 1;
225 ret += 4*midlen;
226 len = midlen;
227 }
228 return ret;
229 }
230 static void internal_mul(const BignumInt *a, const BignumInt *b,
231 BignumInt *c, int len, BignumInt *scratch)
232 {
233 if (len > KARATSUBA_THRESHOLD) {
234 int i;
235
236 /*
237 * Karatsuba divide-and-conquer algorithm. Cut each input in
238 * half, so that it's expressed as two big 'digits' in a giant
239 * base D:
240 *
241 * a = a_1 D + a_0
242 * b = b_1 D + b_0
243 *
244 * Then the product is of course
245 *
246 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
247 *
248 * and we compute the three coefficients by recursively
249 * calling ourself to do half-length multiplications.
250 *
251 * The clever bit that makes this worth doing is that we only
252 * need _one_ half-length multiplication for the central
253 * coefficient rather than the two that it obviouly looks
254 * like, because we can use a single multiplication to compute
255 *
256 * (a_1 + a_0) (b_1 + b_0) = a_1 b_1 + a_1 b_0 + a_0 b_1 + a_0 b_0
257 *
258 * and then we subtract the other two coefficients (a_1 b_1
259 * and a_0 b_0) which we were computing anyway.
260 *
261 * Hence we get to multiply two numbers of length N in about
262 * three times as much work as it takes to multiply numbers of
263 * length N/2, which is obviously better than the four times
264 * as much work it would take if we just did a long
265 * conventional multiply.
266 */
267
268 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
269 int midlen = botlen + 1;
270 BignumDblInt carry;
271 #ifdef KARA_DEBUG
272 int i;
273 #endif
274
275 /*
276 * The coefficients a_1 b_1 and a_0 b_0 just avoid overlapping
277 * in the output array, so we can compute them immediately in
278 * place.
279 */
280
281 #ifdef KARA_DEBUG
282 printf("a1,a0 = 0x");
283 for (i = 0; i < len; i++) {
284 if (i == toplen) printf(", 0x");
285 printf("%0*x", BIGNUM_INT_BITS/4, a[i]);
286 }
287 printf("\n");
288 printf("b1,b0 = 0x");
289 for (i = 0; i < len; i++) {
290 if (i == toplen) printf(", 0x");
291 printf("%0*x", BIGNUM_INT_BITS/4, b[i]);
292 }
293 printf("\n");
294 #endif
295
296 /* a_1 b_1 */
297 internal_mul(a, b, c, toplen, scratch);
298 #ifdef KARA_DEBUG
299 printf("a1b1 = 0x");
300 for (i = 0; i < 2*toplen; i++) {
301 printf("%0*x", BIGNUM_INT_BITS/4, c[i]);
302 }
303 printf("\n");
304 #endif
305
306 /* a_0 b_0 */
307 internal_mul(a + toplen, b + toplen, c + 2*toplen, botlen, scratch);
308 #ifdef KARA_DEBUG
309 printf("a0b0 = 0x");
310 for (i = 0; i < 2*botlen; i++) {
311 printf("%0*x", BIGNUM_INT_BITS/4, c[2*toplen+i]);
312 }
313 printf("\n");
314 #endif
315
316 /* Zero padding. midlen exceeds toplen by at most 2, so just
317 * zero the first two words of each input and the rest will be
318 * copied over. */
319 scratch[0] = scratch[1] = scratch[midlen] = scratch[midlen+1] = 0;
320
321 for (i = 0; i < toplen; i++) {
322 scratch[midlen - toplen + i] = a[i]; /* a_1 */
323 scratch[2*midlen - toplen + i] = b[i]; /* b_1 */
324 }
325
326 /* compute a_1 + a_0 */
327 scratch[0] = internal_add(scratch+1, a+toplen, scratch+1, botlen);
328 #ifdef KARA_DEBUG
329 printf("a1plusa0 = 0x");
330 for (i = 0; i < midlen; i++) {
331 printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);
332 }
333 printf("\n");
334 #endif
335 /* compute b_1 + b_0 */
336 scratch[midlen] = internal_add(scratch+midlen+1, b+toplen,
337 scratch+midlen+1, botlen);
338 #ifdef KARA_DEBUG
339 printf("b1plusb0 = 0x");
340 for (i = 0; i < midlen; i++) {
341 printf("%0*x", BIGNUM_INT_BITS/4, scratch[midlen+i]);
342 }
343 printf("\n");
344 #endif
345
346 /*
347 * Now we can do the third multiplication.
348 */
349 internal_mul(scratch, scratch + midlen, scratch + 2*midlen, midlen,
350 scratch + 4*midlen);
351 #ifdef KARA_DEBUG
352 printf("a1plusa0timesb1plusb0 = 0x");
353 for (i = 0; i < 2*midlen; i++) {
354 printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);
355 }
356 printf("\n");
357 #endif
358
359 /*
360 * Now we can reuse the first half of 'scratch' to compute the
361 * sum of the outer two coefficients, to subtract from that
362 * product to obtain the middle one.
363 */
364 scratch[0] = scratch[1] = scratch[2] = scratch[3] = 0;
365 for (i = 0; i < 2*toplen; i++)
366 scratch[2*midlen - 2*toplen + i] = c[i];
367 scratch[1] = internal_add(scratch+2, c + 2*toplen,
368 scratch+2, 2*botlen);
369 #ifdef KARA_DEBUG
370 printf("a1b1plusa0b0 = 0x");
371 for (i = 0; i < 2*midlen; i++) {
372 printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);
373 }
374 printf("\n");
375 #endif
376
377 internal_sub(scratch + 2*midlen, scratch,
378 scratch + 2*midlen, 2*midlen);
379 #ifdef KARA_DEBUG
380 printf("a1b0plusa0b1 = 0x");
381 for (i = 0; i < 2*midlen; i++) {
382 printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);
383 }
384 printf("\n");
385 #endif
386
387 /*
388 * And now all we need to do is to add that middle coefficient
389 * back into the output. We may have to propagate a carry
390 * further up the output, but we can be sure it won't
391 * propagate right the way off the top.
392 */
393 carry = internal_add(c + 2*len - botlen - 2*midlen,
394 scratch + 2*midlen,
395 c + 2*len - botlen - 2*midlen, 2*midlen);
396 i = 2*len - botlen - 2*midlen - 1;
397 while (carry) {
398 assert(i >= 0);
399 carry += c[i];
400 c[i] = (BignumInt)carry;
401 carry >>= BIGNUM_INT_BITS;
402 i--;
403 }
404 #ifdef KARA_DEBUG
405 printf("ab = 0x");
406 for (i = 0; i < 2*len; i++) {
407 printf("%0*x", BIGNUM_INT_BITS/4, c[i]);
408 }
409 printf("\n");
410 #endif
411
412 } else {
413 int i;
414 BignumInt carry;
415 BignumDblInt t;
416 const BignumInt *ap, *bp;
417 BignumInt *cp, *cps;
418
419 /*
420 * Multiply in the ordinary O(N^2) way.
421 */
422
423 for (i = 0; i < 2 * len; i++)
424 c[i] = 0;
425
426 for (cps = c + 2*len, ap = a + len; ap-- > a; cps--) {
427 carry = 0;
428 for (cp = cps, bp = b + len; cp--, bp-- > b ;) {
429 t = (MUL_WORD(*ap, *bp) + carry) + *cp;
430 *cp = (BignumInt) t;
431 carry = (BignumInt)(t >> BIGNUM_INT_BITS);
432 }
433 *cp = carry;
434 }
435 }
436 }
437
438 /*
439 * Variant form of internal_mul used for the initial step of
440 * Montgomery reduction. Only bothers outputting 'len' words
441 * (everything above that is thrown away).
442 */
443 static void internal_mul_low(const BignumInt *a, const BignumInt *b,
444 BignumInt *c, int len, BignumInt *scratch)
445 {
446 if (len > KARATSUBA_THRESHOLD) {
447 int i;
448
449 /*
450 * Karatsuba-aware version of internal_mul_low. As before, we
451 * express each input value as a shifted combination of two
452 * halves:
453 *
454 * a = a_1 D + a_0
455 * b = b_1 D + b_0
456 *
457 * Then the full product is, as before,
458 *
459 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
460 *
461 * Provided we choose D on the large side (so that a_0 and b_0
462 * are _at least_ as long as a_1 and b_1), we don't need the
463 * topmost term at all, and we only need half of the middle
464 * term. So there's no point in doing the proper Karatsuba
465 * optimisation which computes the middle term using the top
466 * one, because we'd take as long computing the top one as
467 * just computing the middle one directly.
468 *
469 * So instead, we do a much more obvious thing: we call the
470 * fully optimised internal_mul to compute a_0 b_0, and we
471 * recursively call ourself to compute the _bottom halves_ of
472 * a_1 b_0 and a_0 b_1, each of which we add into the result
473 * in the obvious way.
474 *
475 * In other words, there's no actual Karatsuba _optimisation_
476 * in this function; the only benefit in doing it this way is
477 * that we call internal_mul proper for a large part of the
478 * work, and _that_ can optimise its operation.
479 */
480
481 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
482
483 /*
484 * Scratch space for the various bits and pieces we're going
485 * to be adding together: we need botlen*2 words for a_0 b_0
486 * (though we may end up throwing away its topmost word), and
487 * toplen words for each of a_1 b_0 and a_0 b_1. That adds up
488 * to exactly 2*len.
489 */
490
491 /* a_0 b_0 */
492 internal_mul(a + toplen, b + toplen, scratch + 2*toplen, botlen,
493 scratch + 2*len);
494
495 /* a_1 b_0 */
496 internal_mul_low(a, b + len - toplen, scratch + toplen, toplen,
497 scratch + 2*len);
498
499 /* a_0 b_1 */
500 internal_mul_low(a + len - toplen, b, scratch, toplen,
501 scratch + 2*len);
502
503 /* Copy the bottom half of the big coefficient into place */
504 for (i = 0; i < botlen; i++)
505 c[toplen + i] = scratch[2*toplen + botlen + i];
506
507 /* Add the two small coefficients, throwing away the returned carry */
508 internal_add(scratch, scratch + toplen, scratch, toplen);
509
510 /* And add that to the large coefficient, leaving the result in c. */
511 internal_add(scratch, scratch + 2*toplen + botlen - toplen,
512 c, toplen);
513
514 } else {
515 int i;
516 BignumInt carry;
517 BignumDblInt t;
518 const BignumInt *ap, *bp;
519 BignumInt *cp, *cps;
520
521 /*
522 * Multiply in the ordinary O(N^2) way.
523 */
524
525 for (i = 0; i < len; i++)
526 c[i] = 0;
527
528 for (cps = c + len, ap = a + len; ap-- > a; cps--) {
529 carry = 0;
530 for (cp = cps, bp = b + len; bp--, cp-- > c ;) {
531 t = (MUL_WORD(*ap, *bp) + carry) + *cp;
532 *cp = (BignumInt) t;
533 carry = (BignumInt)(t >> BIGNUM_INT_BITS);
534 }
535 }
536 }
537 }
538
539 /*
540 * Montgomery reduction. Expects x to be a big-endian array of 2*len
541 * BignumInts whose value satisfies 0 <= x < rn (where r = 2^(len *
542 * BIGNUM_INT_BITS) is the Montgomery base). Returns in the same array
543 * a value x' which is congruent to xr^{-1} mod n, and satisfies 0 <=
544 * x' < n.
545 *
546 * 'n' and 'mninv' should be big-endian arrays of 'len' BignumInts
547 * each, containing respectively n and the multiplicative inverse of
548 * -n mod r.
549 *
550 * 'tmp' is an array of BignumInt used as scratch space, of length at
551 * least 3*len + mul_compute_scratch(len).
552 */
553 static void monty_reduce(BignumInt *x, const BignumInt *n,
554 const BignumInt *mninv, BignumInt *tmp, int len)
555 {
556 int i;
557 BignumInt carry;
558
559 /*
560 * Multiply x by (-n)^{-1} mod r. This gives us a value m such
561 * that mn is congruent to -x mod r. Hence, mn+x is an exact
562 * multiple of r, and is also (obviously) congruent to x mod n.
563 */
564 internal_mul_low(x + len, mninv, tmp, len, tmp + 3*len);
565
566 /*
567 * Compute t = (mn+x)/r in ordinary, non-modular, integer
568 * arithmetic. By construction this is exact, and is congruent mod
569 * n to x * r^{-1}, i.e. the answer we want.
570 *
571 * The following multiply leaves that answer in the _most_
572 * significant half of the 'x' array, so then we must shift it
573 * down.
574 */
575 internal_mul(tmp, n, tmp+len, len, tmp + 3*len);
576 carry = internal_add(x, tmp+len, x, 2*len);
577 for (i = 0; i < len; i++)
578 x[len + i] = x[i], x[i] = 0;
579
580 /*
581 * Reduce t mod n. This doesn't require a full-on division by n,
582 * but merely a test and single optional subtraction, since we can
583 * show that 0 <= t < 2n.
584 *
585 * Proof:
586 * + we computed m mod r, so 0 <= m < r.
587 * + so 0 <= mn < rn, obviously
588 * + hence we only need 0 <= x < rn to guarantee that 0 <= mn+x < 2rn
589 * + yielding 0 <= (mn+x)/r < 2n as required.
590 */
591 if (!carry) {
592 for (i = 0; i < len; i++)
593 if (x[len + i] != n[i])
594 break;
595 }
596 if (carry || i >= len || x[len + i] > n[i])
597 internal_sub(x+len, n, x+len, len);
598 }
599
600 static void internal_add_shifted(BignumInt *number,
601 unsigned n, int shift)
602 {
603 int word = 1 + (shift / BIGNUM_INT_BITS);
604 int bshift = shift % BIGNUM_INT_BITS;
605 BignumDblInt addend;
606
607 addend = (BignumDblInt)n << bshift;
608
609 while (addend) {
610 addend += number[word];
611 number[word] = (BignumInt) addend & BIGNUM_INT_MASK;
612 addend >>= BIGNUM_INT_BITS;
613 word++;
614 }
615 }
616
617 /*
618 * Compute a = a % m.
619 * Input in first alen words of a and first mlen words of m.
620 * Output in first alen words of a
621 * (of which first alen-mlen words will be zero).
622 * The MSW of m MUST have its high bit set.
623 * Quotient is accumulated in the `quotient' array, which is a Bignum
624 * rather than the internal bigendian format. Quotient parts are shifted
625 * left by `qshift' before adding into quot.
626 */
627 static void internal_mod(BignumInt *a, int alen,
628 BignumInt *m, int mlen,
629 BignumInt *quot, int qshift)
630 {
631 BignumInt m0, m1;
632 unsigned int h;
633 int i, k;
634
635 m0 = m[0];
636 assert(m0 >> (BIGNUM_INT_BITS-1) == 1);
637 if (mlen > 1)
638 m1 = m[1];
639 else
640 m1 = 0;
641
642 for (i = 0; i <= alen - mlen; i++) {
643 BignumDblInt t;
644 unsigned int q, r, c, ai1;
645
646 if (i == 0) {
647 h = 0;
648 } else {
649 h = a[i - 1];
650 a[i - 1] = 0;
651 }
652
653 if (i == alen - 1)
654 ai1 = 0;
655 else
656 ai1 = a[i + 1];
657
658 /* Find q = h:a[i] / m0 */
659 if (h >= m0) {
660 /*
661 * Special case.
662 *
663 * To illustrate it, suppose a BignumInt is 8 bits, and
664 * we are dividing (say) A1:23:45:67 by A1:B2:C3. Then
665 * our initial division will be 0xA123 / 0xA1, which
666 * will give a quotient of 0x100 and a divide overflow.
667 * However, the invariants in this division algorithm
668 * are not violated, since the full number A1:23:... is
669 * _less_ than the quotient prefix A1:B2:... and so the
670 * following correction loop would have sorted it out.
671 *
672 * In this situation we set q to be the largest
673 * quotient we _can_ stomach (0xFF, of course).
674 */
675 q = BIGNUM_INT_MASK;
676 } else {
677 /* Macro doesn't want an array subscript expression passed
678 * into it (see definition), so use a temporary. */
679 BignumInt tmplo = a[i];
680 DIVMOD_WORD(q, r, h, tmplo, m0);
681
682 /* Refine our estimate of q by looking at
683 h:a[i]:a[i+1] / m0:m1 */
684 t = MUL_WORD(m1, q);
685 if (t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) {
686 q--;
687 t -= m1;
688 r = (r + m0) & BIGNUM_INT_MASK; /* overflow? */
689 if (r >= (BignumDblInt) m0 &&
690 t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) q--;
691 }
692 }
693
694 /* Subtract q * m from a[i...] */
695 c = 0;
696 for (k = mlen - 1; k >= 0; k--) {
697 t = MUL_WORD(q, m[k]);
698 t += c;
699 c = (unsigned)(t >> BIGNUM_INT_BITS);
700 if ((BignumInt) t > a[i + k])
701 c++;
702 a[i + k] -= (BignumInt) t;
703 }
704
705 /* Add back m in case of borrow */
706 if (c != h) {
707 t = 0;
708 for (k = mlen - 1; k >= 0; k--) {
709 t += m[k];
710 t += a[i + k];
711 a[i + k] = (BignumInt) t;
712 t = t >> BIGNUM_INT_BITS;
713 }
714 q--;
715 }
716 if (quot)
717 internal_add_shifted(quot, q, qshift + BIGNUM_INT_BITS * (alen - mlen - i));
718 }
719 }
720
721 /*
722 * Compute (base ^ exp) % mod, the pedestrian way.
723 */
724 Bignum modpow_simple(Bignum base_in, Bignum exp, Bignum mod)
725 {
726 BignumInt *a, *b, *n, *m, *scratch;
727 int mshift;
728 int mlen, scratchlen, i, j;
729 Bignum base, result;
730
731 /*
732 * The most significant word of mod needs to be non-zero. It
733 * should already be, but let's make sure.
734 */
735 assert(mod[mod[0]] != 0);
736
737 /*
738 * Make sure the base is smaller than the modulus, by reducing
739 * it modulo the modulus if not.
740 */
741 base = bigmod(base_in, mod);
742
743 /* Allocate m of size mlen, copy mod to m */
744 /* We use big endian internally */
745 mlen = mod[0];
746 m = snewn(mlen, BignumInt);
747 for (j = 0; j < mlen; j++)
748 m[j] = mod[mod[0] - j];
749
750 /* Shift m left to make msb bit set */
751 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
752 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
753 break;
754 if (mshift) {
755 for (i = 0; i < mlen - 1; i++)
756 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
757 m[mlen - 1] = m[mlen - 1] << mshift;
758 }
759
760 /* Allocate n of size mlen, copy base to n */
761 n = snewn(mlen, BignumInt);
762 i = mlen - base[0];
763 for (j = 0; j < i; j++)
764 n[j] = 0;
765 for (j = 0; j < (int)base[0]; j++)
766 n[i + j] = base[base[0] - j];
767
768 /* Allocate a and b of size 2*mlen. Set a = 1 */
769 a = snewn(2 * mlen, BignumInt);
770 b = snewn(2 * mlen, BignumInt);
771 for (i = 0; i < 2 * mlen; i++)
772 a[i] = 0;
773 a[2 * mlen - 1] = 1;
774
775 /* Scratch space for multiplies */
776 scratchlen = mul_compute_scratch(mlen);
777 scratch = snewn(scratchlen, BignumInt);
778
779 /* Skip leading zero bits of exp. */
780 i = 0;
781 j = BIGNUM_INT_BITS-1;
782 while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
783 j--;
784 if (j < 0) {
785 i++;
786 j = BIGNUM_INT_BITS-1;
787 }
788 }
789
790 /* Main computation */
791 while (i < (int)exp[0]) {
792 while (j >= 0) {
793 internal_mul(a + mlen, a + mlen, b, mlen, scratch);
794 internal_mod(b, mlen * 2, m, mlen, NULL, 0);
795 if ((exp[exp[0] - i] & (1 << j)) != 0) {
796 internal_mul(b + mlen, n, a, mlen, scratch);
797 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
798 } else {
799 BignumInt *t;
800 t = a;
801 a = b;
802 b = t;
803 }
804 j--;
805 }
806 i++;
807 j = BIGNUM_INT_BITS-1;
808 }
809
810 /* Fixup result in case the modulus was shifted */
811 if (mshift) {
812 for (i = mlen - 1; i < 2 * mlen - 1; i++)
813 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
814 a[2 * mlen - 1] = a[2 * mlen - 1] << mshift;
815 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
816 for (i = 2 * mlen - 1; i >= mlen; i--)
817 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
818 }
819
820 /* Copy result to buffer */
821 result = newbn(mod[0]);
822 for (i = 0; i < mlen; i++)
823 result[result[0] - i] = a[i + mlen];
824 while (result[0] > 1 && result[result[0]] == 0)
825 result[0]--;
826
827 /* Free temporary arrays */
828 smemclr(a, 2 * mlen * sizeof(*a));
829 sfree(a);
830 smemclr(scratch, scratchlen * sizeof(*scratch));
831 sfree(scratch);
832 smemclr(b, 2 * mlen * sizeof(*b));
833 sfree(b);
834 smemclr(m, mlen * sizeof(*m));
835 sfree(m);
836 smemclr(n, mlen * sizeof(*n));
837 sfree(n);
838
839 freebn(base);
840
841 return result;
842 }
843
844 /*
845 * Compute (base ^ exp) % mod. Uses the Montgomery multiplication
846 * technique where possible, falling back to modpow_simple otherwise.
847 */
848 Bignum modpow(Bignum base_in, Bignum exp, Bignum mod)
849 {
850 BignumInt *a, *b, *x, *n, *mninv, *scratch;
851 int len, scratchlen, i, j;
852 Bignum base, base2, r, rn, inv, result;
853
854 /*
855 * The most significant word of mod needs to be non-zero. It
856 * should already be, but let's make sure.
857 */
858 assert(mod[mod[0]] != 0);
859
860 /*
861 * mod had better be odd, or we can't do Montgomery multiplication
862 * using a power of two at all.
863 */
864 if (!(mod[1] & 1))
865 return modpow_simple(base_in, exp, mod);
866
867 /*
868 * Make sure the base is smaller than the modulus, by reducing
869 * it modulo the modulus if not.
870 */
871 base = bigmod(base_in, mod);
872
873 /*
874 * Compute the inverse of n mod r, for monty_reduce. (In fact we
875 * want the inverse of _minus_ n mod r, but we'll sort that out
876 * below.)
877 */
878 len = mod[0];
879 r = bn_power_2(BIGNUM_INT_BITS * len);
880 inv = modinv(mod, r);
881 assert(inv); /* cannot fail, since mod is odd and r is a power of 2 */
882
883 /*
884 * Multiply the base by r mod n, to get it into Montgomery
885 * representation.
886 */
887 base2 = modmul(base, r, mod);
888 freebn(base);
889 base = base2;
890
891 rn = bigmod(r, mod); /* r mod n, i.e. Montgomerified 1 */
892
893 freebn(r); /* won't need this any more */
894
895 /*
896 * Set up internal arrays of the right lengths, in big-endian
897 * format, containing the base, the modulus, and the modulus's
898 * inverse.
899 */
900 n = snewn(len, BignumInt);
901 for (j = 0; j < len; j++)
902 n[len - 1 - j] = mod[j + 1];
903
904 mninv = snewn(len, BignumInt);
905 for (j = 0; j < len; j++)
906 mninv[len - 1 - j] = (j < (int)inv[0] ? inv[j + 1] : 0);
907 freebn(inv); /* we don't need this copy of it any more */
908 /* Now negate mninv mod r, so it's the inverse of -n rather than +n. */
909 x = snewn(len, BignumInt);
910 for (j = 0; j < len; j++)
911 x[j] = 0;
912 internal_sub(x, mninv, mninv, len);
913
914 /* x = snewn(len, BignumInt); */ /* already done above */
915 for (j = 0; j < len; j++)
916 x[len - 1 - j] = (j < (int)base[0] ? base[j + 1] : 0);
917 freebn(base); /* we don't need this copy of it any more */
918
919 a = snewn(2*len, BignumInt);
920 b = snewn(2*len, BignumInt);
921 for (j = 0; j < len; j++)
922 a[2*len - 1 - j] = (j < (int)rn[0] ? rn[j + 1] : 0);
923 freebn(rn);
924
925 /* Scratch space for multiplies */
926 scratchlen = 3*len + mul_compute_scratch(len);
927 scratch = snewn(scratchlen, BignumInt);
928
929 /* Skip leading zero bits of exp. */
930 i = 0;
931 j = BIGNUM_INT_BITS-1;
932 while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
933 j--;
934 if (j < 0) {
935 i++;
936 j = BIGNUM_INT_BITS-1;
937 }
938 }
939
940 /* Main computation */
941 while (i < (int)exp[0]) {
942 while (j >= 0) {
943 internal_mul(a + len, a + len, b, len, scratch);
944 monty_reduce(b, n, mninv, scratch, len);
945 if ((exp[exp[0] - i] & (1 << j)) != 0) {
946 internal_mul(b + len, x, a, len, scratch);
947 monty_reduce(a, n, mninv, scratch, len);
948 } else {
949 BignumInt *t;
950 t = a;
951 a = b;
952 b = t;
953 }
954 j--;
955 }
956 i++;
957 j = BIGNUM_INT_BITS-1;
958 }
959
960 /*
961 * Final monty_reduce to get back from the adjusted Montgomery
962 * representation.
963 */
964 monty_reduce(a, n, mninv, scratch, len);
965
966 /* Copy result to buffer */
967 result = newbn(mod[0]);
968 for (i = 0; i < len; i++)
969 result[result[0] - i] = a[i + len];
970 while (result[0] > 1 && result[result[0]] == 0)
971 result[0]--;
972
973 /* Free temporary arrays */
974 smemclr(scratch, scratchlen * sizeof(*scratch));
975 sfree(scratch);
976 smemclr(a, 2 * len * sizeof(*a));
977 sfree(a);
978 smemclr(b, 2 * len * sizeof(*b));
979 sfree(b);
980 smemclr(mninv, len * sizeof(*mninv));
981 sfree(mninv);
982 smemclr(n, len * sizeof(*n));
983 sfree(n);
984 smemclr(x, len * sizeof(*x));
985 sfree(x);
986
987 return result;
988 }
989
990 /*
991 * Compute (p * q) % mod.
992 * The most significant word of mod MUST be non-zero.
993 * We assume that the result array is the same size as the mod array.
994 */
995 Bignum modmul(Bignum p, Bignum q, Bignum mod)
996 {
997 BignumInt *a, *n, *m, *o, *scratch;
998 int mshift, scratchlen;
999 int pqlen, mlen, rlen, i, j;
1000 Bignum result;
1001
1002 /*
1003 * The most significant word of mod needs to be non-zero. It
1004 * should already be, but let's make sure.
1005 */
1006 assert(mod[mod[0]] != 0);
1007
1008 /* Allocate m of size mlen, copy mod to m */
1009 /* We use big endian internally */
1010 mlen = mod[0];
1011 m = snewn(mlen, BignumInt);
1012 for (j = 0; j < mlen; j++)
1013 m[j] = mod[mod[0] - j];
1014
1015 /* Shift m left to make msb bit set */
1016 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
1017 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
1018 break;
1019 if (mshift) {
1020 for (i = 0; i < mlen - 1; i++)
1021 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
1022 m[mlen - 1] = m[mlen - 1] << mshift;
1023 }
1024
1025 pqlen = (p[0] > q[0] ? p[0] : q[0]);
1026
1027 /*
1028 * Make sure that we're allowing enough space. The shifting below
1029 * will underflow the vectors we allocate if pqlen is too small.
1030 */
1031 if (2*pqlen <= mlen)
1032 pqlen = mlen/2 + 1;
1033
1034 /* Allocate n of size pqlen, copy p to n */
1035 n = snewn(pqlen, BignumInt);
1036 i = pqlen - p[0];
1037 for (j = 0; j < i; j++)
1038 n[j] = 0;
1039 for (j = 0; j < (int)p[0]; j++)
1040 n[i + j] = p[p[0] - j];
1041
1042 /* Allocate o of size pqlen, copy q to o */
1043 o = snewn(pqlen, BignumInt);
1044 i = pqlen - q[0];
1045 for (j = 0; j < i; j++)
1046 o[j] = 0;
1047 for (j = 0; j < (int)q[0]; j++)
1048 o[i + j] = q[q[0] - j];
1049
1050 /* Allocate a of size 2*pqlen for result */
1051 a = snewn(2 * pqlen, BignumInt);
1052
1053 /* Scratch space for multiplies */
1054 scratchlen = mul_compute_scratch(pqlen);
1055 scratch = snewn(scratchlen, BignumInt);
1056
1057 /* Main computation */
1058 internal_mul(n, o, a, pqlen, scratch);
1059 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
1060
1061 /* Fixup result in case the modulus was shifted */
1062 if (mshift) {
1063 for (i = 2 * pqlen - mlen - 1; i < 2 * pqlen - 1; i++)
1064 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
1065 a[2 * pqlen - 1] = a[2 * pqlen - 1] << mshift;
1066 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
1067 for (i = 2 * pqlen - 1; i >= 2 * pqlen - mlen; i--)
1068 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
1069 }
1070
1071 /* Copy result to buffer */
1072 rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
1073 result = newbn(rlen);
1074 for (i = 0; i < rlen; i++)
1075 result[result[0] - i] = a[i + 2 * pqlen - rlen];
1076 while (result[0] > 1 && result[result[0]] == 0)
1077 result[0]--;
1078
1079 /* Free temporary arrays */
1080 smemclr(scratch, scratchlen * sizeof(*scratch));
1081 sfree(scratch);
1082 smemclr(a, 2 * pqlen * sizeof(*a));
1083 sfree(a);
1084 smemclr(m, mlen * sizeof(*m));
1085 sfree(m);
1086 smemclr(n, pqlen * sizeof(*n));
1087 sfree(n);
1088 smemclr(o, pqlen * sizeof(*o));
1089 sfree(o);
1090
1091 return result;
1092 }
1093
1094 /*
1095 * Compute p % mod.
1096 * The most significant word of mod MUST be non-zero.
1097 * We assume that the result array is the same size as the mod array.
1098 * We optionally write out a quotient if `quotient' is non-NULL.
1099 * We can avoid writing out the result if `result' is NULL.
1100 */
1101 static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
1102 {
1103 BignumInt *n, *m;
1104 int mshift;
1105 int plen, mlen, i, j;
1106
1107 /*
1108 * The most significant word of mod needs to be non-zero. It
1109 * should already be, but let's make sure.
1110 */
1111 assert(mod[mod[0]] != 0);
1112
1113 /* Allocate m of size mlen, copy mod to m */
1114 /* We use big endian internally */
1115 mlen = mod[0];
1116 m = snewn(mlen, BignumInt);
1117 for (j = 0; j < mlen; j++)
1118 m[j] = mod[mod[0] - j];
1119
1120 /* Shift m left to make msb bit set */
1121 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
1122 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
1123 break;
1124 if (mshift) {
1125 for (i = 0; i < mlen - 1; i++)
1126 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
1127 m[mlen - 1] = m[mlen - 1] << mshift;
1128 }
1129
1130 plen = p[0];
1131 /* Ensure plen > mlen */
1132 if (plen <= mlen)
1133 plen = mlen + 1;
1134
1135 /* Allocate n of size plen, copy p to n */
1136 n = snewn(plen, BignumInt);
1137 for (j = 0; j < plen; j++)
1138 n[j] = 0;
1139 for (j = 1; j <= (int)p[0]; j++)
1140 n[plen - j] = p[j];
1141
1142 /* Main computation */
1143 internal_mod(n, plen, m, mlen, quotient, mshift);
1144
1145 /* Fixup result in case the modulus was shifted */
1146 if (mshift) {
1147 for (i = plen - mlen - 1; i < plen - 1; i++)
1148 n[i] = (n[i] << mshift) | (n[i + 1] >> (BIGNUM_INT_BITS - mshift));
1149 n[plen - 1] = n[plen - 1] << mshift;
1150 internal_mod(n, plen, m, mlen, quotient, 0);
1151 for (i = plen - 1; i >= plen - mlen; i--)
1152 n[i] = (n[i] >> mshift) | (n[i - 1] << (BIGNUM_INT_BITS - mshift));
1153 }
1154
1155 /* Copy result to buffer */
1156 if (result) {
1157 for (i = 1; i <= (int)result[0]; i++) {
1158 int j = plen - i;
1159 result[i] = j >= 0 ? n[j] : 0;
1160 }
1161 }
1162
1163 /* Free temporary arrays */
1164 smemclr(m, mlen * sizeof(*m));
1165 sfree(m);
1166 smemclr(n, plen * sizeof(*n));
1167 sfree(n);
1168 }
1169
1170 /*
1171 * Decrement a number.
1172 */
1173 void decbn(Bignum bn)
1174 {
1175 int i = 1;
1176 while (i < (int)bn[0] && bn[i] == 0)
1177 bn[i++] = BIGNUM_INT_MASK;
1178 bn[i]--;
1179 }
1180
1181 Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
1182 {
1183 Bignum result;
1184 int w, i;
1185
1186 assert(nbytes >= 0 && nbytes < INT_MAX/8);
1187
1188 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
1189
1190 result = newbn(w);
1191 for (i = 1; i <= w; i++)
1192 result[i] = 0;
1193 for (i = nbytes; i--;) {
1194 unsigned char byte = *data++;
1195 result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);
1196 }
1197
1198 while (result[0] > 1 && result[result[0]] == 0)
1199 result[0]--;
1200 return result;
1201 }
1202
1203 /*
1204 * Read an SSH-1-format bignum from a data buffer. Return the number
1205 * of bytes consumed, or -1 if there wasn't enough data.
1206 */
1207 int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)
1208 {
1209 const unsigned char *p = data;
1210 int i;
1211 int w, b;
1212
1213 if (len < 2)
1214 return -1;
1215
1216 w = 0;
1217 for (i = 0; i < 2; i++)
1218 w = (w << 8) + *p++;
1219 b = (w + 7) / 8; /* bits -> bytes */
1220
1221 if (len < b+2)
1222 return -1;
1223
1224 if (!result) /* just return length */
1225 return b + 2;
1226
1227 *result = bignum_from_bytes(p, b);
1228
1229 return p + b - data;
1230 }
1231
1232 /*
1233 * Return the bit count of a bignum, for SSH-1 encoding.
1234 */
1235 int bignum_bitcount(Bignum bn)
1236 {
1237 int bitcount = bn[0] * BIGNUM_INT_BITS - 1;
1238 while (bitcount >= 0
1239 && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;
1240 return bitcount + 1;
1241 }
1242
1243 /*
1244 * Return the byte length of a bignum when SSH-1 encoded.
1245 */
1246 int ssh1_bignum_length(Bignum bn)
1247 {
1248 return 2 + (bignum_bitcount(bn) + 7) / 8;
1249 }
1250
1251 /*
1252 * Return the byte length of a bignum when SSH-2 encoded.
1253 */
1254 int ssh2_bignum_length(Bignum bn)
1255 {
1256 return 4 + (bignum_bitcount(bn) + 8) / 8;
1257 }
1258
1259 /*
1260 * Return a byte from a bignum; 0 is least significant, etc.
1261 */
1262 int bignum_byte(Bignum bn, int i)
1263 {
1264 if (i < 0 || i >= (int)(BIGNUM_INT_BYTES * bn[0]))
1265 return 0; /* beyond the end */
1266 else
1267 return (bn[i / BIGNUM_INT_BYTES + 1] >>
1268 ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;
1269 }
1270
1271 /*
1272 * Return a bit from a bignum; 0 is least significant, etc.
1273 */
1274 int bignum_bit(Bignum bn, int i)
1275 {
1276 if (i < 0 || i >= (int)(BIGNUM_INT_BITS * bn[0]))
1277 return 0; /* beyond the end */
1278 else
1279 return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;
1280 }
1281
1282 /*
1283 * Set a bit in a bignum; 0 is least significant, etc.
1284 */
1285 void bignum_set_bit(Bignum bn, int bitnum, int value)
1286 {
1287 if (bitnum < 0 || bitnum >= (int)(BIGNUM_INT_BITS * bn[0]))
1288 abort(); /* beyond the end */
1289 else {
1290 int v = bitnum / BIGNUM_INT_BITS + 1;
1291 int mask = 1 << (bitnum % BIGNUM_INT_BITS);
1292 if (value)
1293 bn[v] |= mask;
1294 else
1295 bn[v] &= ~mask;
1296 }
1297 }
1298
1299 /*
1300 * Write a SSH-1-format bignum into a buffer. It is assumed the
1301 * buffer is big enough. Returns the number of bytes used.
1302 */
1303 int ssh1_write_bignum(void *data, Bignum bn)
1304 {
1305 unsigned char *p = data;
1306 int len = ssh1_bignum_length(bn);
1307 int i;
1308 int bitc = bignum_bitcount(bn);
1309
1310 *p++ = (bitc >> 8) & 0xFF;
1311 *p++ = (bitc) & 0xFF;
1312 for (i = len - 2; i--;)
1313 *p++ = bignum_byte(bn, i);
1314 return len;
1315 }
1316
1317 /*
1318 * Compare two bignums. Returns like strcmp.
1319 */
1320 int bignum_cmp(Bignum a, Bignum b)
1321 {
1322 int amax = a[0], bmax = b[0];
1323 int i;
1324
1325 /* Annoyingly we have two representations of zero */
1326 if (amax == 1 && a[amax] == 0)
1327 amax = 0;
1328 if (bmax == 1 && b[bmax] == 0)
1329 bmax = 0;
1330
1331 assert(amax == 0 || a[amax] != 0);
1332 assert(bmax == 0 || b[bmax] != 0);
1333
1334 i = (amax > bmax ? amax : bmax);
1335 while (i) {
1336 BignumInt aval = (i > amax ? 0 : a[i]);
1337 BignumInt bval = (i > bmax ? 0 : b[i]);
1338 if (aval < bval)
1339 return -1;
1340 if (aval > bval)
1341 return +1;
1342 i--;
1343 }
1344 return 0;
1345 }
1346
1347 /*
1348 * Right-shift one bignum to form another.
1349 */
1350 Bignum bignum_rshift(Bignum a, int shift)
1351 {
1352 Bignum ret;
1353 int i, shiftw, shiftb, shiftbb, bits;
1354 BignumInt ai, ai1;
1355
1356 assert(shift >= 0);
1357
1358 bits = bignum_bitcount(a) - shift;
1359 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
1360
1361 if (ret) {
1362 shiftw = shift / BIGNUM_INT_BITS;
1363 shiftb = shift % BIGNUM_INT_BITS;
1364 shiftbb = BIGNUM_INT_BITS - shiftb;
1365
1366 ai1 = a[shiftw + 1];
1367 for (i = 1; i <= (int)ret[0]; i++) {
1368 ai = ai1;
1369 ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);
1370 ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;
1371 }
1372 }
1373
1374 return ret;
1375 }
1376
1377 /*
1378 * Non-modular multiplication and addition.
1379 */
1380 Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
1381 {
1382 int alen = a[0], blen = b[0];
1383 int mlen = (alen > blen ? alen : blen);
1384 int rlen, i, maxspot;
1385 int wslen;
1386 BignumInt *workspace;
1387 Bignum ret;
1388
1389 /* mlen space for a, mlen space for b, 2*mlen for result,
1390 * plus scratch space for multiplication */
1391 wslen = mlen * 4 + mul_compute_scratch(mlen);
1392 workspace = snewn(wslen, BignumInt);
1393 for (i = 0; i < mlen; i++) {
1394 workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);
1395 workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);
1396 }
1397
1398 internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
1399 workspace + 2 * mlen, mlen, workspace + 4 * mlen);
1400
1401 /* now just copy the result back */
1402 rlen = alen + blen + 1;
1403 if (addend && rlen <= (int)addend[0])
1404 rlen = addend[0] + 1;
1405 ret = newbn(rlen);
1406 maxspot = 0;
1407 for (i = 1; i <= (int)ret[0]; i++) {
1408 ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
1409 if (ret[i] != 0)
1410 maxspot = i;
1411 }
1412 ret[0] = maxspot;
1413
1414 /* now add in the addend, if any */
1415 if (addend) {
1416 BignumDblInt carry = 0;
1417 for (i = 1; i <= rlen; i++) {
1418 carry += (i <= (int)ret[0] ? ret[i] : 0);
1419 carry += (i <= (int)addend[0] ? addend[i] : 0);
1420 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1421 carry >>= BIGNUM_INT_BITS;
1422 if (ret[i] != 0 && i > maxspot)
1423 maxspot = i;
1424 }
1425 }
1426 ret[0] = maxspot;
1427
1428 smemclr(workspace, wslen * sizeof(*workspace));
1429 sfree(workspace);
1430 return ret;
1431 }
1432
1433 /*
1434 * Non-modular multiplication.
1435 */
1436 Bignum bigmul(Bignum a, Bignum b)
1437 {
1438 return bigmuladd(a, b, NULL);
1439 }
1440
1441 /*
1442 * Simple addition.
1443 */
1444 Bignum bigadd(Bignum a, Bignum b)
1445 {
1446 int alen = a[0], blen = b[0];
1447 int rlen = (alen > blen ? alen : blen) + 1;
1448 int i, maxspot;
1449 Bignum ret;
1450 BignumDblInt carry;
1451
1452 ret = newbn(rlen);
1453
1454 carry = 0;
1455 maxspot = 0;
1456 for (i = 1; i <= rlen; i++) {
1457 carry += (i <= (int)a[0] ? a[i] : 0);
1458 carry += (i <= (int)b[0] ? b[i] : 0);
1459 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1460 carry >>= BIGNUM_INT_BITS;
1461 if (ret[i] != 0 && i > maxspot)
1462 maxspot = i;
1463 }
1464 ret[0] = maxspot;
1465
1466 return ret;
1467 }
1468
1469 /*
1470 * Subtraction. Returns a-b, or NULL if the result would come out
1471 * negative (recall that this entire bignum module only handles
1472 * positive numbers).
1473 */
1474 Bignum bigsub(Bignum a, Bignum b)
1475 {
1476 int alen = a[0], blen = b[0];
1477 int rlen = (alen > blen ? alen : blen);
1478 int i, maxspot;
1479 Bignum ret;
1480 BignumDblInt carry;
1481
1482 ret = newbn(rlen);
1483
1484 carry = 1;
1485 maxspot = 0;
1486 for (i = 1; i <= rlen; i++) {
1487 carry += (i <= (int)a[0] ? a[i] : 0);
1488 carry += (i <= (int)b[0] ? b[i] ^ BIGNUM_INT_MASK : BIGNUM_INT_MASK);
1489 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1490 carry >>= BIGNUM_INT_BITS;
1491 if (ret[i] != 0 && i > maxspot)
1492 maxspot = i;
1493 }
1494 ret[0] = maxspot;
1495
1496 if (!carry) {
1497 freebn(ret);
1498 return NULL;
1499 }
1500
1501 return ret;
1502 }
1503
1504 /*
1505 * Create a bignum which is the bitmask covering another one. That
1506 * is, the smallest integer which is >= N and is also one less than
1507 * a power of two.
1508 */
1509 Bignum bignum_bitmask(Bignum n)
1510 {
1511 Bignum ret = copybn(n);
1512 int i;
1513 BignumInt j;
1514
1515 i = ret[0];
1516 while (n[i] == 0 && i > 0)
1517 i--;
1518 if (i <= 0)
1519 return ret; /* input was zero */
1520 j = 1;
1521 while (j < n[i])
1522 j = 2 * j + 1;
1523 ret[i] = j;
1524 while (--i > 0)
1525 ret[i] = BIGNUM_INT_MASK;
1526 return ret;
1527 }
1528
1529 /*
1530 * Convert a (max 32-bit) long into a bignum.
1531 */
1532 Bignum bignum_from_long(unsigned long nn)
1533 {
1534 Bignum ret;
1535 BignumDblInt n = nn;
1536
1537 ret = newbn(3);
1538 ret[1] = (BignumInt)(n & BIGNUM_INT_MASK);
1539 ret[2] = (BignumInt)((n >> BIGNUM_INT_BITS) & BIGNUM_INT_MASK);
1540 ret[3] = 0;
1541 ret[0] = (ret[2] ? 2 : 1);
1542 return ret;
1543 }
1544
1545 /*
1546 * Add a long to a bignum.
1547 */
1548 Bignum bignum_add_long(Bignum number, unsigned long addendx)
1549 {
1550 Bignum ret = newbn(number[0] + 1);
1551 int i, maxspot = 0;
1552 BignumDblInt carry = 0, addend = addendx;
1553
1554 for (i = 1; i <= (int)ret[0]; i++) {
1555 carry += addend & BIGNUM_INT_MASK;
1556 carry += (i <= (int)number[0] ? number[i] : 0);
1557 addend >>= BIGNUM_INT_BITS;
1558 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1559 carry >>= BIGNUM_INT_BITS;
1560 if (ret[i] != 0)
1561 maxspot = i;
1562 }
1563 ret[0] = maxspot;
1564 return ret;
1565 }
1566
1567 /*
1568 * Compute the residue of a bignum, modulo a (max 16-bit) short.
1569 */
1570 unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
1571 {
1572 BignumDblInt mod, r;
1573 int i;
1574
1575 r = 0;
1576 mod = modulus;
1577 for (i = number[0]; i > 0; i--)
1578 r = (r * (BIGNUM_TOP_BIT % mod) * 2 + number[i] % mod) % mod;
1579 return (unsigned short) r;
1580 }
1581
1582 #ifdef DEBUG
1583 void diagbn(char *prefix, Bignum md)
1584 {
1585 int i, nibbles, morenibbles;
1586 static const char hex[] = "0123456789ABCDEF";
1587
1588 debug(("%s0x", prefix ? prefix : ""));
1589
1590 nibbles = (3 + bignum_bitcount(md)) / 4;
1591 if (nibbles < 1)
1592 nibbles = 1;
1593 morenibbles = 4 * md[0] - nibbles;
1594 for (i = 0; i < morenibbles; i++)
1595 debug(("-"));
1596 for (i = nibbles; i--;)
1597 debug(("%c",
1598 hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
1599
1600 if (prefix)
1601 debug(("\n"));
1602 }
1603 #endif
1604
1605 /*
1606 * Simple division.
1607 */
1608 Bignum bigdiv(Bignum a, Bignum b)
1609 {
1610 Bignum q = newbn(a[0]);
1611 bigdivmod(a, b, NULL, q);
1612 return q;
1613 }
1614
1615 /*
1616 * Simple remainder.
1617 */
1618 Bignum bigmod(Bignum a, Bignum b)
1619 {
1620 Bignum r = newbn(b[0]);
1621 bigdivmod(a, b, r, NULL);
1622 return r;
1623 }
1624
1625 /*
1626 * Greatest common divisor.
1627 */
1628 Bignum biggcd(Bignum av, Bignum bv)
1629 {
1630 Bignum a = copybn(av);
1631 Bignum b = copybn(bv);
1632
1633 while (bignum_cmp(b, Zero) != 0) {
1634 Bignum t = newbn(b[0]);
1635 bigdivmod(a, b, t, NULL);
1636 while (t[0] > 1 && t[t[0]] == 0)
1637 t[0]--;
1638 freebn(a);
1639 a = b;
1640 b = t;
1641 }
1642
1643 freebn(b);
1644 return a;
1645 }
1646
1647 /*
1648 * Modular inverse, using Euclid's extended algorithm.
1649 */
1650 Bignum modinv(Bignum number, Bignum modulus)
1651 {
1652 Bignum a = copybn(modulus);
1653 Bignum b = copybn(number);
1654 Bignum xp = copybn(Zero);
1655 Bignum x = copybn(One);
1656 int sign = +1;
1657
1658 assert(number[number[0]] != 0);
1659 assert(modulus[modulus[0]] != 0);
1660
1661 while (bignum_cmp(b, One) != 0) {
1662 Bignum t, q;
1663
1664 if (bignum_cmp(b, Zero) == 0) {
1665 /*
1666 * Found a common factor between the inputs, so we cannot
1667 * return a modular inverse at all.
1668 */
1669 freebn(b);
1670 freebn(a);
1671 freebn(xp);
1672 freebn(x);
1673 return NULL;
1674 }
1675
1676 t = newbn(b[0]);
1677 q = newbn(a[0]);
1678 bigdivmod(a, b, t, q);
1679 while (t[0] > 1 && t[t[0]] == 0)
1680 t[0]--;
1681 freebn(a);
1682 a = b;
1683 b = t;
1684 t = xp;
1685 xp = x;
1686 x = bigmuladd(q, xp, t);
1687 sign = -sign;
1688 freebn(t);
1689 freebn(q);
1690 }
1691
1692 freebn(b);
1693 freebn(a);
1694 freebn(xp);
1695
1696 /* now we know that sign * x == 1, and that x < modulus */
1697 if (sign < 0) {
1698 /* set a new x to be modulus - x */
1699 Bignum newx = newbn(modulus[0]);
1700 BignumInt carry = 0;
1701 int maxspot = 1;
1702 int i;
1703
1704 for (i = 1; i <= (int)newx[0]; i++) {
1705 BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);
1706 BignumInt bword = (i <= (int)x[0] ? x[i] : 0);
1707 newx[i] = aword - bword - carry;
1708 bword = ~bword;
1709 carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
1710 if (newx[i] != 0)
1711 maxspot = i;
1712 }
1713 newx[0] = maxspot;
1714 freebn(x);
1715 x = newx;
1716 }
1717
1718 /* and return. */
1719 return x;
1720 }
1721
1722 /*
1723 * Render a bignum into decimal. Return a malloced string holding
1724 * the decimal representation.
1725 */
1726 char *bignum_decimal(Bignum x)
1727 {
1728 int ndigits, ndigit;
1729 int i, iszero;
1730 BignumDblInt carry;
1731 char *ret;
1732 BignumInt *workspace;
1733
1734 /*
1735 * First, estimate the number of digits. Since log(10)/log(2)
1736 * is just greater than 93/28 (the joys of continued fraction
1737 * approximations...) we know that for every 93 bits, we need
1738 * at most 28 digits. This will tell us how much to malloc.
1739 *
1740 * Formally: if x has i bits, that means x is strictly less
1741 * than 2^i. Since 2 is less than 10^(28/93), this is less than
1742 * 10^(28i/93). We need an integer power of ten, so we must
1743 * round up (rounding down might make it less than x again).
1744 * Therefore if we multiply the bit count by 28/93, rounding
1745 * up, we will have enough digits.
1746 *
1747 * i=0 (i.e., x=0) is an irritating special case.
1748 */
1749 i = bignum_bitcount(x);
1750 if (!i)
1751 ndigits = 1; /* x = 0 */
1752 else
1753 ndigits = (28 * i + 92) / 93; /* multiply by 28/93 and round up */
1754 ndigits++; /* allow for trailing \0 */
1755 ret = snewn(ndigits, char);
1756
1757 /*
1758 * Now allocate some workspace to hold the binary form as we
1759 * repeatedly divide it by ten. Initialise this to the
1760 * big-endian form of the number.
1761 */
1762 workspace = snewn(x[0], BignumInt);
1763 for (i = 0; i < (int)x[0]; i++)
1764 workspace[i] = x[x[0] - i];
1765
1766 /*
1767 * Next, write the decimal number starting with the last digit.
1768 * We use ordinary short division, dividing 10 into the
1769 * workspace.
1770 */
1771 ndigit = ndigits - 1;
1772 ret[ndigit] = '\0';
1773 do {
1774 iszero = 1;
1775 carry = 0;
1776 for (i = 0; i < (int)x[0]; i++) {
1777 carry = (carry << BIGNUM_INT_BITS) + workspace[i];
1778 workspace[i] = (BignumInt) (carry / 10);
1779 if (workspace[i])
1780 iszero = 0;
1781 carry %= 10;
1782 }
1783 ret[--ndigit] = (char) (carry + '0');
1784 } while (!iszero);
1785
1786 /*
1787 * There's a chance we've fallen short of the start of the
1788 * string. Correct if so.
1789 */
1790 if (ndigit > 0)
1791 memmove(ret, ret + ndigit, ndigits - ndigit);
1792
1793 /*
1794 * Done.
1795 */
1796 smemclr(workspace, x[0] * sizeof(*workspace));
1797 sfree(workspace);
1798 return ret;
1799 }
1800
1801 #ifdef TESTBN
1802
1803 #include <stdio.h>
1804 #include <stdlib.h>
1805 #include <ctype.h>
1806
1807 /*
1808 * gcc -Wall -g -O0 -DTESTBN -o testbn sshbn.c misc.c conf.c tree234.c unix/uxmisc.c -I. -I unix -I charset
1809 *
1810 * Then feed to this program's standard input the output of
1811 * testdata/bignum.py .
1812 */
1813
1814 void modalfatalbox(char *p, ...)
1815 {
1816 va_list ap;
1817 fprintf(stderr, "FATAL ERROR: ");
1818 va_start(ap, p);
1819 vfprintf(stderr, p, ap);
1820 va_end(ap);
1821 fputc('\n', stderr);
1822 exit(1);
1823 }
1824
1825 #define fromxdigit(c) ( (c)>'9' ? ((c)&0xDF) - 'A' + 10 : (c) - '0' )
1826
1827 int main(int argc, char **argv)
1828 {
1829 char *buf;
1830 int line = 0;
1831 int passes = 0, fails = 0;
1832
1833 while ((buf = fgetline(stdin)) != NULL) {
1834 int maxlen = strlen(buf);
1835 unsigned char *data = snewn(maxlen, unsigned char);
1836 unsigned char *ptrs[5], *q;
1837 int ptrnum;
1838 char *bufp = buf;
1839
1840 line++;
1841
1842 q = data;
1843 ptrnum = 0;
1844
1845 while (*bufp && !isspace((unsigned char)*bufp))
1846 bufp++;
1847 if (bufp)
1848 *bufp++ = '\0';
1849
1850 while (*bufp) {
1851 char *start, *end;
1852 int i;
1853
1854 while (*bufp && !isxdigit((unsigned char)*bufp))
1855 bufp++;
1856 start = bufp;
1857
1858 if (!*bufp)
1859 break;
1860
1861 while (*bufp && isxdigit((unsigned char)*bufp))
1862 bufp++;
1863 end = bufp;
1864
1865 if (ptrnum >= lenof(ptrs))
1866 break;
1867 ptrs[ptrnum++] = q;
1868
1869 for (i = -((end - start) & 1); i < end-start; i += 2) {
1870 unsigned char val = (i < 0 ? 0 : fromxdigit(start[i]));
1871 val = val * 16 + fromxdigit(start[i+1]);
1872 *q++ = val;
1873 }
1874
1875 ptrs[ptrnum] = q;
1876 }
1877
1878 if (!strcmp(buf, "mul")) {
1879 Bignum a, b, c, p;
1880
1881 if (ptrnum != 3) {
1882 printf("%d: mul with %d parameters, expected 3\n", line, ptrnum);
1883 exit(1);
1884 }
1885 a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1886 b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1887 c = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1888 p = bigmul(a, b);
1889
1890 if (bignum_cmp(c, p) == 0) {
1891 passes++;
1892 } else {
1893 char *as = bignum_decimal(a);
1894 char *bs = bignum_decimal(b);
1895 char *cs = bignum_decimal(c);
1896 char *ps = bignum_decimal(p);
1897
1898 printf("%d: fail: %s * %s gave %s expected %s\n",
1899 line, as, bs, ps, cs);
1900 fails++;
1901
1902 sfree(as);
1903 sfree(bs);
1904 sfree(cs);
1905 sfree(ps);
1906 }
1907 freebn(a);
1908 freebn(b);
1909 freebn(c);
1910 freebn(p);
1911 } else if (!strcmp(buf, "modmul")) {
1912 Bignum a, b, m, c, p;
1913
1914 if (ptrnum != 4) {
1915 printf("%d: modmul with %d parameters, expected 4\n",
1916 line, ptrnum);
1917 exit(1);
1918 }
1919 a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1920 b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1921 m = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1922 c = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);
1923 p = modmul(a, b, m);
1924
1925 if (bignum_cmp(c, p) == 0) {
1926 passes++;
1927 } else {
1928 char *as = bignum_decimal(a);
1929 char *bs = bignum_decimal(b);
1930 char *ms = bignum_decimal(m);
1931 char *cs = bignum_decimal(c);
1932 char *ps = bignum_decimal(p);
1933
1934 printf("%d: fail: %s * %s mod %s gave %s expected %s\n",
1935 line, as, bs, ms, ps, cs);
1936 fails++;
1937
1938 sfree(as);
1939 sfree(bs);
1940 sfree(ms);
1941 sfree(cs);
1942 sfree(ps);
1943 }
1944 freebn(a);
1945 freebn(b);
1946 freebn(m);
1947 freebn(c);
1948 freebn(p);
1949 } else if (!strcmp(buf, "pow")) {
1950 Bignum base, expt, modulus, expected, answer;
1951
1952 if (ptrnum != 4) {
1953 printf("%d: mul with %d parameters, expected 4\n", line, ptrnum);
1954 exit(1);
1955 }
1956
1957 base = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1958 expt = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1959 modulus = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1960 expected = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);
1961 answer = modpow(base, expt, modulus);
1962
1963 if (bignum_cmp(expected, answer) == 0) {
1964 passes++;
1965 } else {
1966 char *as = bignum_decimal(base);
1967 char *bs = bignum_decimal(expt);
1968 char *cs = bignum_decimal(modulus);
1969 char *ds = bignum_decimal(answer);
1970 char *ps = bignum_decimal(expected);
1971
1972 printf("%d: fail: %s ^ %s mod %s gave %s expected %s\n",
1973 line, as, bs, cs, ds, ps);
1974 fails++;
1975
1976 sfree(as);
1977 sfree(bs);
1978 sfree(cs);
1979 sfree(ds);
1980 sfree(ps);
1981 }
1982 freebn(base);
1983 freebn(expt);
1984 freebn(modulus);
1985 freebn(expected);
1986 freebn(answer);
1987 } else {
1988 printf("%d: unrecognised test keyword: '%s'\n", line, buf);
1989 exit(1);
1990 }
1991
1992 sfree(buf);
1993 sfree(data);
1994 }
1995
1996 printf("passed %d failed %d total %d\n", passes, fails, passes+fails);
1997 return fails != 0;
1998 }
1999
2000 #endif