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