]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - sshbn.c
Move BignumInt definitions into a header file.
[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 #include <ctype.h>
11
12 #include "misc.h"
13
14 #include "sshbn.h"
15
16 #define BIGNUM_INTERNAL
17 typedef BignumInt *Bignum;
18
19 #include "ssh.h"
20
21 BignumInt bnZero[1] = { 0 };
22 BignumInt bnOne[2] = { 1, 1 };
23 BignumInt bnTen[2] = { 1, 10 };
24
25 /*
26  * The Bignum format is an array of `BignumInt'. The first
27  * element of the array counts the remaining elements. The
28  * remaining elements express the actual number, base 2^BIGNUM_INT_BITS, _least_
29  * significant digit first. (So it's trivial to extract the bit
30  * with value 2^n for any n.)
31  *
32  * All Bignums in this module are positive. Negative numbers must
33  * be dealt with outside it.
34  *
35  * INVARIANT: the most significant word of any Bignum must be
36  * nonzero.
37  */
38
39 Bignum Zero = bnZero, One = bnOne, Ten = bnTen;
40
41 static Bignum newbn(int length)
42 {
43     Bignum b;
44
45     assert(length >= 0 && length < INT_MAX / BIGNUM_INT_BITS);
46
47     b = snewn(length + 1, BignumInt);
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 Bignum modsub(const Bignum a, const Bignum b, const Bignum n)
1013 {
1014     Bignum a1, b1, ret;
1015
1016     if (bignum_cmp(a, n) >= 0) a1 = bigmod(a, n);
1017     else a1 = a;
1018     if (bignum_cmp(b, n) >= 0) b1 = bigmod(b, n);
1019     else b1 = b;
1020
1021     if (bignum_cmp(a1, b1) >= 0) /* a >= b */
1022     {
1023         ret = bigsub(a1, b1);
1024     }
1025     else
1026     {
1027         /* Handle going round the corner of the modulus without having
1028          * negative support in Bignum */
1029         Bignum tmp = bigsub(n, b1);
1030         assert(tmp);
1031         ret = bigadd(tmp, a1);
1032         freebn(tmp);
1033     }
1034
1035     if (a != a1) freebn(a1);
1036     if (b != b1) freebn(b1);
1037
1038     return ret;
1039 }
1040
1041 /*
1042  * Compute p % mod.
1043  * The most significant word of mod MUST be non-zero.
1044  * We assume that the result array is the same size as the mod array.
1045  * We optionally write out a quotient if `quotient' is non-NULL.
1046  * We can avoid writing out the result if `result' is NULL.
1047  */
1048 static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
1049 {
1050     BignumInt *n, *m;
1051     int mshift;
1052     int plen, mlen, i, j;
1053
1054     /*
1055      * The most significant word of mod needs to be non-zero. It
1056      * should already be, but let's make sure.
1057      */
1058     assert(mod[mod[0]] != 0);
1059
1060     /* Allocate m of size mlen, copy mod to m */
1061     /* We use big endian internally */
1062     mlen = mod[0];
1063     m = snewn(mlen, BignumInt);
1064     for (j = 0; j < mlen; j++)
1065         m[j] = mod[mod[0] - j];
1066
1067     /* Shift m left to make msb bit set */
1068     for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
1069         if ((m[0] << mshift) & BIGNUM_TOP_BIT)
1070             break;
1071     if (mshift) {
1072         for (i = 0; i < mlen - 1; i++)
1073             m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
1074         m[mlen - 1] = m[mlen - 1] << mshift;
1075     }
1076
1077     plen = p[0];
1078     /* Ensure plen > mlen */
1079     if (plen <= mlen)
1080         plen = mlen + 1;
1081
1082     /* Allocate n of size plen, copy p to n */
1083     n = snewn(plen, BignumInt);
1084     for (j = 0; j < plen; j++)
1085         n[j] = 0;
1086     for (j = 1; j <= (int)p[0]; j++)
1087         n[plen - j] = p[j];
1088
1089     /* Main computation */
1090     internal_mod(n, plen, m, mlen, quotient, mshift);
1091
1092     /* Fixup result in case the modulus was shifted */
1093     if (mshift) {
1094         for (i = plen - mlen - 1; i < plen - 1; i++)
1095             n[i] = (n[i] << mshift) | (n[i + 1] >> (BIGNUM_INT_BITS - mshift));
1096         n[plen - 1] = n[plen - 1] << mshift;
1097         internal_mod(n, plen, m, mlen, quotient, 0);
1098         for (i = plen - 1; i >= plen - mlen; i--)
1099             n[i] = (n[i] >> mshift) | (n[i - 1] << (BIGNUM_INT_BITS - mshift));
1100     }
1101
1102     /* Copy result to buffer */
1103     if (result) {
1104         for (i = 1; i <= (int)result[0]; i++) {
1105             int j = plen - i;
1106             result[i] = j >= 0 ? n[j] : 0;
1107         }
1108     }
1109
1110     /* Free temporary arrays */
1111     smemclr(m, mlen * sizeof(*m));
1112     sfree(m);
1113     smemclr(n, plen * sizeof(*n));
1114     sfree(n);
1115 }
1116
1117 /*
1118  * Decrement a number.
1119  */
1120 void decbn(Bignum bn)
1121 {
1122     int i = 1;
1123     while (i < (int)bn[0] && bn[i] == 0)
1124         bn[i++] = BIGNUM_INT_MASK;
1125     bn[i]--;
1126 }
1127
1128 Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
1129 {
1130     Bignum result;
1131     int w, i;
1132
1133     assert(nbytes >= 0 && nbytes < INT_MAX/8);
1134
1135     w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
1136
1137     result = newbn(w);
1138     for (i = 1; i <= w; i++)
1139         result[i] = 0;
1140     for (i = nbytes; i--;) {
1141         unsigned char byte = *data++;
1142         result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);
1143     }
1144
1145     while (result[0] > 1 && result[result[0]] == 0)
1146         result[0]--;
1147     return result;
1148 }
1149
1150 Bignum bignum_from_bytes_le(const unsigned char *data, int nbytes)
1151 {
1152     Bignum result;
1153     int w, i;
1154
1155     assert(nbytes >= 0 && nbytes < INT_MAX/8);
1156
1157     w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
1158
1159     result = newbn(w);
1160     for (i = 1; i <= w; i++)
1161         result[i] = 0;
1162     for (i = 0; i < nbytes; ++i) {
1163         unsigned char byte = *data++;
1164         result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);
1165     }
1166
1167     while (result[0] > 1 && result[result[0]] == 0)
1168         result[0]--;
1169     return result;
1170 }
1171
1172 Bignum bignum_from_decimal(const char *decimal)
1173 {
1174     Bignum result = copybn(Zero);
1175
1176     while (*decimal) {
1177         Bignum tmp, tmp2;
1178
1179         if (!isdigit((unsigned char)*decimal)) {
1180             freebn(result);
1181             return 0;
1182         }
1183
1184         tmp = bigmul(result, Ten);
1185         tmp2 = bignum_from_long(*decimal - '0');
1186         result = bigadd(tmp, tmp2);
1187         freebn(tmp);
1188         freebn(tmp2);
1189
1190         decimal++;
1191     }
1192
1193     return result;
1194 }
1195
1196 Bignum bignum_random_in_range(const Bignum lower, const Bignum upper)
1197 {
1198     Bignum ret = NULL;
1199     unsigned char *bytes;
1200     int upper_len = bignum_bitcount(upper);
1201     int upper_bytes = upper_len / 8;
1202     int upper_bits = upper_len % 8;
1203     if (upper_bits) ++upper_bytes;
1204
1205     bytes = snewn(upper_bytes, unsigned char);
1206     do {
1207         int i;
1208
1209         if (ret) freebn(ret);
1210
1211         for (i = 0; i < upper_bytes; ++i)
1212         {
1213             bytes[i] = (unsigned char)random_byte();
1214         }
1215         /* Mask the top to reduce failure rate to 50/50 */
1216         if (upper_bits)
1217         {
1218             bytes[i - 1] &= 0xFF >> (8 - upper_bits);
1219         }
1220
1221         ret = bignum_from_bytes(bytes, upper_bytes);
1222     } while (bignum_cmp(ret, lower) < 0 || bignum_cmp(ret, upper) > 0);
1223     smemclr(bytes, upper_bytes);
1224     sfree(bytes);
1225
1226     return ret;
1227 }
1228
1229 /*
1230  * Read an SSH-1-format bignum from a data buffer. Return the number
1231  * of bytes consumed, or -1 if there wasn't enough data.
1232  */
1233 int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)
1234 {
1235     const unsigned char *p = data;
1236     int i;
1237     int w, b;
1238
1239     if (len < 2)
1240         return -1;
1241
1242     w = 0;
1243     for (i = 0; i < 2; i++)
1244         w = (w << 8) + *p++;
1245     b = (w + 7) / 8;                   /* bits -> bytes */
1246
1247     if (len < b+2)
1248         return -1;
1249
1250     if (!result)                       /* just return length */
1251         return b + 2;
1252
1253     *result = bignum_from_bytes(p, b);
1254
1255     return p + b - data;
1256 }
1257
1258 /*
1259  * Return the bit count of a bignum, for SSH-1 encoding.
1260  */
1261 int bignum_bitcount(Bignum bn)
1262 {
1263     int bitcount = bn[0] * BIGNUM_INT_BITS - 1;
1264     while (bitcount >= 0
1265            && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;
1266     return bitcount + 1;
1267 }
1268
1269 /*
1270  * Return the byte length of a bignum when SSH-1 encoded.
1271  */
1272 int ssh1_bignum_length(Bignum bn)
1273 {
1274     return 2 + (bignum_bitcount(bn) + 7) / 8;
1275 }
1276
1277 /*
1278  * Return the byte length of a bignum when SSH-2 encoded.
1279  */
1280 int ssh2_bignum_length(Bignum bn)
1281 {
1282     return 4 + (bignum_bitcount(bn) + 8) / 8;
1283 }
1284
1285 /*
1286  * Return a byte from a bignum; 0 is least significant, etc.
1287  */
1288 int bignum_byte(Bignum bn, int i)
1289 {
1290     if (i < 0 || i >= (int)(BIGNUM_INT_BYTES * bn[0]))
1291         return 0;                      /* beyond the end */
1292     else
1293         return (bn[i / BIGNUM_INT_BYTES + 1] >>
1294                 ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;
1295 }
1296
1297 /*
1298  * Return a bit from a bignum; 0 is least significant, etc.
1299  */
1300 int bignum_bit(Bignum bn, int i)
1301 {
1302     if (i < 0 || i >= (int)(BIGNUM_INT_BITS * bn[0]))
1303         return 0;                      /* beyond the end */
1304     else
1305         return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;
1306 }
1307
1308 /*
1309  * Set a bit in a bignum; 0 is least significant, etc.
1310  */
1311 void bignum_set_bit(Bignum bn, int bitnum, int value)
1312 {
1313     if (bitnum < 0 || bitnum >= (int)(BIGNUM_INT_BITS * bn[0]))
1314         abort();                       /* beyond the end */
1315     else {
1316         int v = bitnum / BIGNUM_INT_BITS + 1;
1317         int mask = 1 << (bitnum % BIGNUM_INT_BITS);
1318         if (value)
1319             bn[v] |= mask;
1320         else
1321             bn[v] &= ~mask;
1322     }
1323 }
1324
1325 /*
1326  * Write a SSH-1-format bignum into a buffer. It is assumed the
1327  * buffer is big enough. Returns the number of bytes used.
1328  */
1329 int ssh1_write_bignum(void *data, Bignum bn)
1330 {
1331     unsigned char *p = data;
1332     int len = ssh1_bignum_length(bn);
1333     int i;
1334     int bitc = bignum_bitcount(bn);
1335
1336     *p++ = (bitc >> 8) & 0xFF;
1337     *p++ = (bitc) & 0xFF;
1338     for (i = len - 2; i--;)
1339         *p++ = bignum_byte(bn, i);
1340     return len;
1341 }
1342
1343 /*
1344  * Compare two bignums. Returns like strcmp.
1345  */
1346 int bignum_cmp(Bignum a, Bignum b)
1347 {
1348     int amax = a[0], bmax = b[0];
1349     int i;
1350
1351     /* Annoyingly we have two representations of zero */
1352     if (amax == 1 && a[amax] == 0)
1353         amax = 0;
1354     if (bmax == 1 && b[bmax] == 0)
1355         bmax = 0;
1356
1357     assert(amax == 0 || a[amax] != 0);
1358     assert(bmax == 0 || b[bmax] != 0);
1359
1360     i = (amax > bmax ? amax : bmax);
1361     while (i) {
1362         BignumInt aval = (i > amax ? 0 : a[i]);
1363         BignumInt bval = (i > bmax ? 0 : b[i]);
1364         if (aval < bval)
1365             return -1;
1366         if (aval > bval)
1367             return +1;
1368         i--;
1369     }
1370     return 0;
1371 }
1372
1373 /*
1374  * Right-shift one bignum to form another.
1375  */
1376 Bignum bignum_rshift(Bignum a, int shift)
1377 {
1378     Bignum ret;
1379     int i, shiftw, shiftb, shiftbb, bits;
1380     BignumInt ai, ai1;
1381
1382     assert(shift >= 0);
1383
1384     bits = bignum_bitcount(a) - shift;
1385     ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
1386
1387     if (ret) {
1388         shiftw = shift / BIGNUM_INT_BITS;
1389         shiftb = shift % BIGNUM_INT_BITS;
1390         shiftbb = BIGNUM_INT_BITS - shiftb;
1391
1392         ai1 = a[shiftw + 1];
1393         for (i = 1; i <= (int)ret[0]; i++) {
1394             ai = ai1;
1395             ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);
1396             ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;
1397         }
1398     }
1399
1400     return ret;
1401 }
1402
1403 /*
1404  * Left-shift one bignum to form another.
1405  */
1406 Bignum bignum_lshift(Bignum a, int shift)
1407 {
1408     Bignum ret;
1409     int bits, shiftWords, shiftBits;
1410
1411     assert(shift >= 0);
1412
1413     bits = bignum_bitcount(a) + shift;
1414     ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
1415
1416     shiftWords = shift / BIGNUM_INT_BITS;
1417     shiftBits = shift % BIGNUM_INT_BITS;
1418
1419     if (shiftBits == 0)
1420     {
1421         memcpy(&ret[1 + shiftWords], &a[1], sizeof(BignumInt) * a[0]);
1422     }
1423     else
1424     {
1425         int i;
1426         BignumInt carry = 0;
1427
1428         /* Remember that Bignum[0] is length, so add 1 */
1429         for (i = shiftWords + 1; i < ((int)a[0]) + shiftWords + 1; ++i)
1430         {
1431             BignumInt from = a[i - shiftWords];
1432             ret[i] = (from << shiftBits) | carry;
1433             carry = from >> (BIGNUM_INT_BITS - shiftBits);
1434         }
1435         if (carry) ret[i] = carry;
1436     }
1437
1438     return ret;
1439 }
1440
1441 /*
1442  * Non-modular multiplication and addition.
1443  */
1444 Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
1445 {
1446     int alen = a[0], blen = b[0];
1447     int mlen = (alen > blen ? alen : blen);
1448     int rlen, i, maxspot;
1449     int wslen;
1450     BignumInt *workspace;
1451     Bignum ret;
1452
1453     /* mlen space for a, mlen space for b, 2*mlen for result,
1454      * plus scratch space for multiplication */
1455     wslen = mlen * 4 + mul_compute_scratch(mlen);
1456     workspace = snewn(wslen, BignumInt);
1457     for (i = 0; i < mlen; i++) {
1458         workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);
1459         workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);
1460     }
1461
1462     internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
1463                  workspace + 2 * mlen, mlen, workspace + 4 * mlen);
1464
1465     /* now just copy the result back */
1466     rlen = alen + blen + 1;
1467     if (addend && rlen <= (int)addend[0])
1468         rlen = addend[0] + 1;
1469     ret = newbn(rlen);
1470     maxspot = 0;
1471     for (i = 1; i <= (int)ret[0]; i++) {
1472         ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
1473         if (ret[i] != 0)
1474             maxspot = i;
1475     }
1476     ret[0] = maxspot;
1477
1478     /* now add in the addend, if any */
1479     if (addend) {
1480         BignumDblInt carry = 0;
1481         for (i = 1; i <= rlen; i++) {
1482             carry += (i <= (int)ret[0] ? ret[i] : 0);
1483             carry += (i <= (int)addend[0] ? addend[i] : 0);
1484             ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1485             carry >>= BIGNUM_INT_BITS;
1486             if (ret[i] != 0 && i > maxspot)
1487                 maxspot = i;
1488         }
1489     }
1490     ret[0] = maxspot;
1491
1492     smemclr(workspace, wslen * sizeof(*workspace));
1493     sfree(workspace);
1494     return ret;
1495 }
1496
1497 /*
1498  * Non-modular multiplication.
1499  */
1500 Bignum bigmul(Bignum a, Bignum b)
1501 {
1502     return bigmuladd(a, b, NULL);
1503 }
1504
1505 /*
1506  * Simple addition.
1507  */
1508 Bignum bigadd(Bignum a, Bignum b)
1509 {
1510     int alen = a[0], blen = b[0];
1511     int rlen = (alen > blen ? alen : blen) + 1;
1512     int i, maxspot;
1513     Bignum ret;
1514     BignumDblInt carry;
1515
1516     ret = newbn(rlen);
1517
1518     carry = 0;
1519     maxspot = 0;
1520     for (i = 1; i <= rlen; i++) {
1521         carry += (i <= (int)a[0] ? a[i] : 0);
1522         carry += (i <= (int)b[0] ? b[i] : 0);
1523         ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1524         carry >>= BIGNUM_INT_BITS;
1525         if (ret[i] != 0 && i > maxspot)
1526             maxspot = i;
1527     }
1528     ret[0] = maxspot;
1529
1530     return ret;
1531 }
1532
1533 /*
1534  * Subtraction. Returns a-b, or NULL if the result would come out
1535  * negative (recall that this entire bignum module only handles
1536  * positive numbers).
1537  */
1538 Bignum bigsub(Bignum a, Bignum b)
1539 {
1540     int alen = a[0], blen = b[0];
1541     int rlen = (alen > blen ? alen : blen);
1542     int i, maxspot;
1543     Bignum ret;
1544     BignumDblInt carry;
1545
1546     ret = newbn(rlen);
1547
1548     carry = 1;
1549     maxspot = 0;
1550     for (i = 1; i <= rlen; i++) {
1551         carry += (i <= (int)a[0] ? a[i] : 0);
1552         carry += (i <= (int)b[0] ? b[i] ^ BIGNUM_INT_MASK : BIGNUM_INT_MASK);
1553         ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1554         carry >>= BIGNUM_INT_BITS;
1555         if (ret[i] != 0 && i > maxspot)
1556             maxspot = i;
1557     }
1558     ret[0] = maxspot;
1559
1560     if (!carry) {
1561         freebn(ret);
1562         return NULL;
1563     }
1564
1565     return ret;
1566 }
1567
1568 /*
1569  * Create a bignum which is the bitmask covering another one. That
1570  * is, the smallest integer which is >= N and is also one less than
1571  * a power of two.
1572  */
1573 Bignum bignum_bitmask(Bignum n)
1574 {
1575     Bignum ret = copybn(n);
1576     int i;
1577     BignumInt j;
1578
1579     i = ret[0];
1580     while (n[i] == 0 && i > 0)
1581         i--;
1582     if (i <= 0)
1583         return ret;                    /* input was zero */
1584     j = 1;
1585     while (j < n[i])
1586         j = 2 * j + 1;
1587     ret[i] = j;
1588     while (--i > 0)
1589         ret[i] = BIGNUM_INT_MASK;
1590     return ret;
1591 }
1592
1593 /*
1594  * Convert a (max 32-bit) long into a bignum.
1595  */
1596 Bignum bignum_from_long(unsigned long nn)
1597 {
1598     Bignum ret;
1599     BignumDblInt n = nn;
1600
1601     ret = newbn(3);
1602     ret[1] = (BignumInt)(n & BIGNUM_INT_MASK);
1603     ret[2] = (BignumInt)((n >> BIGNUM_INT_BITS) & BIGNUM_INT_MASK);
1604     ret[3] = 0;
1605     ret[0] = (ret[2]  ? 2 : 1);
1606     return ret;
1607 }
1608
1609 /*
1610  * Add a long to a bignum.
1611  */
1612 Bignum bignum_add_long(Bignum number, unsigned long addendx)
1613 {
1614     Bignum ret = newbn(number[0] + 1);
1615     int i, maxspot = 0;
1616     BignumDblInt carry = 0, addend = addendx;
1617
1618     for (i = 1; i <= (int)ret[0]; i++) {
1619         carry += addend & BIGNUM_INT_MASK;
1620         carry += (i <= (int)number[0] ? number[i] : 0);
1621         addend >>= BIGNUM_INT_BITS;
1622         ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1623         carry >>= BIGNUM_INT_BITS;
1624         if (ret[i] != 0)
1625             maxspot = i;
1626     }
1627     ret[0] = maxspot;
1628     return ret;
1629 }
1630
1631 /*
1632  * Compute the residue of a bignum, modulo a (max 16-bit) short.
1633  */
1634 unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
1635 {
1636     BignumDblInt mod, r;
1637     int i;
1638
1639     r = 0;
1640     mod = modulus;
1641     for (i = number[0]; i > 0; i--)
1642         r = (r * (BIGNUM_TOP_BIT % mod) * 2 + number[i] % mod) % mod;
1643     return (unsigned short) r;
1644 }
1645
1646 #ifdef DEBUG
1647 void diagbn(char *prefix, Bignum md)
1648 {
1649     int i, nibbles, morenibbles;
1650     static const char hex[] = "0123456789ABCDEF";
1651
1652     debug(("%s0x", prefix ? prefix : ""));
1653
1654     nibbles = (3 + bignum_bitcount(md)) / 4;
1655     if (nibbles < 1)
1656         nibbles = 1;
1657     morenibbles = 4 * md[0] - nibbles;
1658     for (i = 0; i < morenibbles; i++)
1659         debug(("-"));
1660     for (i = nibbles; i--;)
1661         debug(("%c",
1662                hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
1663
1664     if (prefix)
1665         debug(("\n"));
1666 }
1667 #endif
1668
1669 /*
1670  * Simple division.
1671  */
1672 Bignum bigdiv(Bignum a, Bignum b)
1673 {
1674     Bignum q = newbn(a[0]);
1675     bigdivmod(a, b, NULL, q);
1676     while (q[0] > 1 && q[q[0]] == 0)
1677         q[0]--;
1678     return q;
1679 }
1680
1681 /*
1682  * Simple remainder.
1683  */
1684 Bignum bigmod(Bignum a, Bignum b)
1685 {
1686     Bignum r = newbn(b[0]);
1687     bigdivmod(a, b, r, NULL);
1688     while (r[0] > 1 && r[r[0]] == 0)
1689         r[0]--;
1690     return r;
1691 }
1692
1693 /*
1694  * Greatest common divisor.
1695  */
1696 Bignum biggcd(Bignum av, Bignum bv)
1697 {
1698     Bignum a = copybn(av);
1699     Bignum b = copybn(bv);
1700
1701     while (bignum_cmp(b, Zero) != 0) {
1702         Bignum t = newbn(b[0]);
1703         bigdivmod(a, b, t, NULL);
1704         while (t[0] > 1 && t[t[0]] == 0)
1705             t[0]--;
1706         freebn(a);
1707         a = b;
1708         b = t;
1709     }
1710
1711     freebn(b);
1712     return a;
1713 }
1714
1715 /*
1716  * Modular inverse, using Euclid's extended algorithm.
1717  */
1718 Bignum modinv(Bignum number, Bignum modulus)
1719 {
1720     Bignum a = copybn(modulus);
1721     Bignum b = copybn(number);
1722     Bignum xp = copybn(Zero);
1723     Bignum x = copybn(One);
1724     int sign = +1;
1725
1726     assert(number[number[0]] != 0);
1727     assert(modulus[modulus[0]] != 0);
1728
1729     while (bignum_cmp(b, One) != 0) {
1730         Bignum t, q;
1731
1732         if (bignum_cmp(b, Zero) == 0) {
1733             /*
1734              * Found a common factor between the inputs, so we cannot
1735              * return a modular inverse at all.
1736              */
1737             freebn(b);
1738             freebn(a);
1739             freebn(xp);
1740             freebn(x);
1741             return NULL;
1742         }
1743
1744         t = newbn(b[0]);
1745         q = newbn(a[0]);
1746         bigdivmod(a, b, t, q);
1747         while (t[0] > 1 && t[t[0]] == 0)
1748             t[0]--;
1749         while (q[0] > 1 && q[q[0]] == 0)
1750             q[0]--;
1751         freebn(a);
1752         a = b;
1753         b = t;
1754         t = xp;
1755         xp = x;
1756         x = bigmuladd(q, xp, t);
1757         sign = -sign;
1758         freebn(t);
1759         freebn(q);
1760     }
1761
1762     freebn(b);
1763     freebn(a);
1764     freebn(xp);
1765
1766     /* now we know that sign * x == 1, and that x < modulus */
1767     if (sign < 0) {
1768         /* set a new x to be modulus - x */
1769         Bignum newx = newbn(modulus[0]);
1770         BignumInt carry = 0;
1771         int maxspot = 1;
1772         int i;
1773
1774         for (i = 1; i <= (int)newx[0]; i++) {
1775             BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);
1776             BignumInt bword = (i <= (int)x[0] ? x[i] : 0);
1777             newx[i] = aword - bword - carry;
1778             bword = ~bword;
1779             carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
1780             if (newx[i] != 0)
1781                 maxspot = i;
1782         }
1783         newx[0] = maxspot;
1784         freebn(x);
1785         x = newx;
1786     }
1787
1788     /* and return. */
1789     return x;
1790 }
1791
1792 /*
1793  * Render a bignum into decimal. Return a malloced string holding
1794  * the decimal representation.
1795  */
1796 char *bignum_decimal(Bignum x)
1797 {
1798     int ndigits, ndigit;
1799     int i, iszero;
1800     BignumDblInt carry;
1801     char *ret;
1802     BignumInt *workspace;
1803
1804     /*
1805      * First, estimate the number of digits. Since log(10)/log(2)
1806      * is just greater than 93/28 (the joys of continued fraction
1807      * approximations...) we know that for every 93 bits, we need
1808      * at most 28 digits. This will tell us how much to malloc.
1809      *
1810      * Formally: if x has i bits, that means x is strictly less
1811      * than 2^i. Since 2 is less than 10^(28/93), this is less than
1812      * 10^(28i/93). We need an integer power of ten, so we must
1813      * round up (rounding down might make it less than x again).
1814      * Therefore if we multiply the bit count by 28/93, rounding
1815      * up, we will have enough digits.
1816      *
1817      * i=0 (i.e., x=0) is an irritating special case.
1818      */
1819     i = bignum_bitcount(x);
1820     if (!i)
1821         ndigits = 1;                   /* x = 0 */
1822     else
1823         ndigits = (28 * i + 92) / 93;  /* multiply by 28/93 and round up */
1824     ndigits++;                         /* allow for trailing \0 */
1825     ret = snewn(ndigits, char);
1826
1827     /*
1828      * Now allocate some workspace to hold the binary form as we
1829      * repeatedly divide it by ten. Initialise this to the
1830      * big-endian form of the number.
1831      */
1832     workspace = snewn(x[0], BignumInt);
1833     for (i = 0; i < (int)x[0]; i++)
1834         workspace[i] = x[x[0] - i];
1835
1836     /*
1837      * Next, write the decimal number starting with the last digit.
1838      * We use ordinary short division, dividing 10 into the
1839      * workspace.
1840      */
1841     ndigit = ndigits - 1;
1842     ret[ndigit] = '\0';
1843     do {
1844         iszero = 1;
1845         carry = 0;
1846         for (i = 0; i < (int)x[0]; i++) {
1847             carry = (carry << BIGNUM_INT_BITS) + workspace[i];
1848             workspace[i] = (BignumInt) (carry / 10);
1849             if (workspace[i])
1850                 iszero = 0;
1851             carry %= 10;
1852         }
1853         ret[--ndigit] = (char) (carry + '0');
1854     } while (!iszero);
1855
1856     /*
1857      * There's a chance we've fallen short of the start of the
1858      * string. Correct if so.
1859      */
1860     if (ndigit > 0)
1861         memmove(ret, ret + ndigit, ndigits - ndigit);
1862
1863     /*
1864      * Done.
1865      */
1866     smemclr(workspace, x[0] * sizeof(*workspace));
1867     sfree(workspace);
1868     return ret;
1869 }
1870
1871 #ifdef TESTBN
1872
1873 #include <stdio.h>
1874 #include <stdlib.h>
1875 #include <ctype.h>
1876
1877 /*
1878  * gcc -Wall -g -O0 -DTESTBN -o testbn sshbn.c misc.c conf.c tree234.c unix/uxmisc.c -I. -I unix -I charset
1879  *
1880  * Then feed to this program's standard input the output of
1881  * testdata/bignum.py .
1882  */
1883
1884 void modalfatalbox(const char *p, ...)
1885 {
1886     va_list ap;
1887     fprintf(stderr, "FATAL ERROR: ");
1888     va_start(ap, p);
1889     vfprintf(stderr, p, ap);
1890     va_end(ap);
1891     fputc('\n', stderr);
1892     exit(1);
1893 }
1894
1895 #define fromxdigit(c) ( (c)>'9' ? ((c)&0xDF) - 'A' + 10 : (c) - '0' )
1896
1897 int main(int argc, char **argv)
1898 {
1899     char *buf;
1900     int line = 0;
1901     int passes = 0, fails = 0;
1902
1903     while ((buf = fgetline(stdin)) != NULL) {
1904         int maxlen = strlen(buf);
1905         unsigned char *data = snewn(maxlen, unsigned char);
1906         unsigned char *ptrs[5], *q;
1907         int ptrnum;
1908         char *bufp = buf;
1909
1910         line++;
1911
1912         q = data;
1913         ptrnum = 0;
1914
1915         while (*bufp && !isspace((unsigned char)*bufp))
1916             bufp++;
1917         if (bufp)
1918             *bufp++ = '\0';
1919
1920         while (*bufp) {
1921             char *start, *end;
1922             int i;
1923
1924             while (*bufp && !isxdigit((unsigned char)*bufp))
1925                 bufp++;
1926             start = bufp;
1927
1928             if (!*bufp)
1929                 break;
1930
1931             while (*bufp && isxdigit((unsigned char)*bufp))
1932                 bufp++;
1933             end = bufp;
1934
1935             if (ptrnum >= lenof(ptrs))
1936                 break;
1937             ptrs[ptrnum++] = q;
1938             
1939             for (i = -((end - start) & 1); i < end-start; i += 2) {
1940                 unsigned char val = (i < 0 ? 0 : fromxdigit(start[i]));
1941                 val = val * 16 + fromxdigit(start[i+1]);
1942                 *q++ = val;
1943             }
1944
1945             ptrs[ptrnum] = q;
1946         }
1947
1948         if (!strcmp(buf, "mul")) {
1949             Bignum a, b, c, p;
1950
1951             if (ptrnum != 3) {
1952                 printf("%d: mul with %d parameters, expected 3\n", line, ptrnum);
1953                 exit(1);
1954             }
1955             a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1956             b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1957             c = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1958             p = bigmul(a, b);
1959
1960             if (bignum_cmp(c, p) == 0) {
1961                 passes++;
1962             } else {
1963                 char *as = bignum_decimal(a);
1964                 char *bs = bignum_decimal(b);
1965                 char *cs = bignum_decimal(c);
1966                 char *ps = bignum_decimal(p);
1967                 
1968                 printf("%d: fail: %s * %s gave %s expected %s\n",
1969                        line, as, bs, ps, cs);
1970                 fails++;
1971
1972                 sfree(as);
1973                 sfree(bs);
1974                 sfree(cs);
1975                 sfree(ps);
1976             }
1977             freebn(a);
1978             freebn(b);
1979             freebn(c);
1980             freebn(p);
1981         } else if (!strcmp(buf, "modmul")) {
1982             Bignum a, b, m, c, p;
1983
1984             if (ptrnum != 4) {
1985                 printf("%d: modmul with %d parameters, expected 4\n",
1986                        line, ptrnum);
1987                 exit(1);
1988             }
1989             a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1990             b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1991             m = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1992             c = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);
1993             p = modmul(a, b, m);
1994
1995             if (bignum_cmp(c, p) == 0) {
1996                 passes++;
1997             } else {
1998                 char *as = bignum_decimal(a);
1999                 char *bs = bignum_decimal(b);
2000                 char *ms = bignum_decimal(m);
2001                 char *cs = bignum_decimal(c);
2002                 char *ps = bignum_decimal(p);
2003                 
2004                 printf("%d: fail: %s * %s mod %s gave %s expected %s\n",
2005                        line, as, bs, ms, ps, cs);
2006                 fails++;
2007
2008                 sfree(as);
2009                 sfree(bs);
2010                 sfree(ms);
2011                 sfree(cs);
2012                 sfree(ps);
2013             }
2014             freebn(a);
2015             freebn(b);
2016             freebn(m);
2017             freebn(c);
2018             freebn(p);
2019         } else if (!strcmp(buf, "pow")) {
2020             Bignum base, expt, modulus, expected, answer;
2021
2022             if (ptrnum != 4) {
2023                 printf("%d: mul with %d parameters, expected 4\n", line, ptrnum);
2024                 exit(1);
2025             }
2026
2027             base = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
2028             expt = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
2029             modulus = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
2030             expected = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);
2031             answer = modpow(base, expt, modulus);
2032
2033             if (bignum_cmp(expected, answer) == 0) {
2034                 passes++;
2035             } else {
2036                 char *as = bignum_decimal(base);
2037                 char *bs = bignum_decimal(expt);
2038                 char *cs = bignum_decimal(modulus);
2039                 char *ds = bignum_decimal(answer);
2040                 char *ps = bignum_decimal(expected);
2041                 
2042                 printf("%d: fail: %s ^ %s mod %s gave %s expected %s\n",
2043                        line, as, bs, cs, ds, ps);
2044                 fails++;
2045
2046                 sfree(as);
2047                 sfree(bs);
2048                 sfree(cs);
2049                 sfree(ds);
2050                 sfree(ps);
2051             }
2052             freebn(base);
2053             freebn(expt);
2054             freebn(modulus);
2055             freebn(expected);
2056             freebn(answer);
2057         } else {
2058             printf("%d: unrecognised test keyword: '%s'\n", line, buf);
2059             exit(1);
2060         }
2061
2062         sfree(buf);
2063         sfree(data);
2064     }
2065
2066     printf("passed %d failed %d total %d\n", passes, fails, passes+fails);
2067     return fails != 0;
2068 }
2069
2070 #endif