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