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