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