]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - sshbn.c
Implement the Karatsuba technique for recursive divide-and-conquer
[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
10 #include "misc.h"
11
12 /*
13  * Usage notes:
14  *  * Do not call the DIVMOD_WORD macro with expressions such as array
15  *    subscripts, as some implementations object to this (see below).
16  *  * Note that none of the division methods below will cope if the
17  *    quotient won't fit into BIGNUM_INT_BITS. Callers should be careful
18  *    to avoid this case.
19  *    If this condition occurs, in the case of the x86 DIV instruction,
20  *    an overflow exception will occur, which (according to a correspondent)
21  *    will manifest on Windows as something like
22  *      0xC0000095: Integer overflow
23  *    The C variant won't give the right answer, either.
24  */
25
26 #if defined __GNUC__ && defined __i386__
27 typedef unsigned long BignumInt;
28 typedef unsigned long long BignumDblInt;
29 #define BIGNUM_INT_MASK  0xFFFFFFFFUL
30 #define BIGNUM_TOP_BIT   0x80000000UL
31 #define BIGNUM_INT_BITS  32
32 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
33 #define DIVMOD_WORD(q, r, hi, lo, w) \
34     __asm__("div %2" : \
35             "=d" (r), "=a" (q) : \
36             "r" (w), "d" (hi), "a" (lo))
37 #elif defined _MSC_VER && defined _M_IX86
38 typedef unsigned __int32 BignumInt;
39 typedef unsigned __int64 BignumDblInt;
40 #define BIGNUM_INT_MASK  0xFFFFFFFFUL
41 #define BIGNUM_TOP_BIT   0x80000000UL
42 #define BIGNUM_INT_BITS  32
43 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
44 /* Note: MASM interprets array subscripts in the macro arguments as
45  * assembler syntax, which gives the wrong answer. Don't supply them.
46  * <http://msdn2.microsoft.com/en-us/library/bf1dw62z.aspx> */
47 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
48     __asm mov edx, hi \
49     __asm mov eax, lo \
50     __asm div w \
51     __asm mov r, edx \
52     __asm mov q, eax \
53 } while(0)
54 #elif defined _LP64
55 /* 64-bit architectures can do 32x32->64 chunks at a time */
56 typedef unsigned int BignumInt;
57 typedef unsigned long BignumDblInt;
58 #define BIGNUM_INT_MASK  0xFFFFFFFFU
59 #define BIGNUM_TOP_BIT   0x80000000U
60 #define BIGNUM_INT_BITS  32
61 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
62 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
63     BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
64     q = n / w; \
65     r = n % w; \
66 } while (0)
67 #elif defined _LLP64
68 /* 64-bit architectures in which unsigned long is 32 bits, not 64 */
69 typedef unsigned long BignumInt;
70 typedef unsigned long long BignumDblInt;
71 #define BIGNUM_INT_MASK  0xFFFFFFFFUL
72 #define BIGNUM_TOP_BIT   0x80000000UL
73 #define BIGNUM_INT_BITS  32
74 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
75 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
76     BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
77     q = n / w; \
78     r = n % w; \
79 } while (0)
80 #else
81 /* Fallback for all other cases */
82 typedef unsigned short BignumInt;
83 typedef unsigned long BignumDblInt;
84 #define BIGNUM_INT_MASK  0xFFFFU
85 #define BIGNUM_TOP_BIT   0x8000U
86 #define BIGNUM_INT_BITS  16
87 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
88 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
89     BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
90     q = n / w; \
91     r = n % w; \
92 } while (0)
93 #endif
94
95 #define BIGNUM_INT_BYTES (BIGNUM_INT_BITS / 8)
96
97 #define BIGNUM_INTERNAL
98 typedef BignumInt *Bignum;
99
100 #include "ssh.h"
101
102 BignumInt bnZero[1] = { 0 };
103 BignumInt bnOne[2] = { 1, 1 };
104
105 /*
106  * The Bignum format is an array of `BignumInt'. The first
107  * element of the array counts the remaining elements. The
108  * remaining elements express the actual number, base 2^BIGNUM_INT_BITS, _least_
109  * significant digit first. (So it's trivial to extract the bit
110  * with value 2^n for any n.)
111  *
112  * All Bignums in this module are positive. Negative numbers must
113  * be dealt with outside it.
114  *
115  * INVARIANT: the most significant word of any Bignum must be
116  * nonzero.
117  */
118
119 Bignum Zero = bnZero, One = bnOne;
120
121 static Bignum newbn(int length)
122 {
123     Bignum b = snewn(length + 1, BignumInt);
124     if (!b)
125         abort();                       /* FIXME */
126     memset(b, 0, (length + 1) * sizeof(*b));
127     b[0] = length;
128     return b;
129 }
130
131 void bn_restore_invariant(Bignum b)
132 {
133     while (b[0] > 1 && b[b[0]] == 0)
134         b[0]--;
135 }
136
137 Bignum copybn(Bignum orig)
138 {
139     Bignum b = snewn(orig[0] + 1, BignumInt);
140     if (!b)
141         abort();                       /* FIXME */
142     memcpy(b, orig, (orig[0] + 1) * sizeof(*b));
143     return b;
144 }
145
146 void freebn(Bignum b)
147 {
148     /*
149      * Burn the evidence, just in case.
150      */
151     memset(b, 0, sizeof(b[0]) * (b[0] + 1));
152     sfree(b);
153 }
154
155 Bignum bn_power_2(int n)
156 {
157     Bignum ret = newbn(n / BIGNUM_INT_BITS + 1);
158     bignum_set_bit(ret, n, 1);
159     return ret;
160 }
161
162 /*
163  * Internal addition. Sets c = a - b, where 'a', 'b' and 'c' are all
164  * big-endian arrays of 'len' BignumInts. Returns a BignumInt carried
165  * off the top.
166  */
167 static BignumInt internal_add(const BignumInt *a, const BignumInt *b,
168                               BignumInt *c, int len)
169 {
170     int i;
171     BignumDblInt carry = 0;
172
173     for (i = len-1; i >= 0; i--) {
174         carry += (BignumDblInt)a[i] + b[i];
175         c[i] = (BignumInt)carry;
176         carry >>= BIGNUM_INT_BITS;
177     }
178
179     return (BignumInt)carry;
180 }
181
182 /*
183  * Internal subtraction. Sets c = a - b, where 'a', 'b' and 'c' are
184  * all big-endian arrays of 'len' BignumInts. Any borrow from the top
185  * is ignored.
186  */
187 static void internal_sub(const BignumInt *a, const BignumInt *b,
188                          BignumInt *c, int len)
189 {
190     int i;
191     BignumDblInt carry = 1;
192
193     for (i = len-1; i >= 0; i--) {
194         carry += (BignumDblInt)a[i] + (b[i] ^ BIGNUM_INT_MASK);
195         c[i] = (BignumInt)carry;
196         carry >>= BIGNUM_INT_BITS;
197     }
198 }
199
200 /*
201  * Compute c = a * b.
202  * Input is in the first len words of a and b.
203  * Result is returned in the first 2*len words of c.
204  */
205 #define KARATSUBA_THRESHOLD 50
206 static void internal_mul(BignumInt *a, BignumInt *b,
207                          BignumInt *c, int len)
208 {
209     int i, j;
210     BignumDblInt t;
211
212     if (len > KARATSUBA_THRESHOLD) {
213
214         /*
215          * Karatsuba divide-and-conquer algorithm. Cut each input in
216          * half, so that it's expressed as two big 'digits' in a giant
217          * base D:
218          *
219          *   a = a_1 D + a_0
220          *   b = b_1 D + b_0
221          *
222          * Then the product is of course
223          *
224          *  ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
225          *
226          * and we compute the three coefficients by recursively
227          * calling ourself to do half-length multiplications.
228          *
229          * The clever bit that makes this worth doing is that we only
230          * need _one_ half-length multiplication for the central
231          * coefficient rather than the two that it obviouly looks
232          * like, because we can use a single multiplication to compute
233          *
234          *   (a_1 + a_0) (b_1 + b_0) = a_1 b_1 + a_1 b_0 + a_0 b_1 + a_0 b_0
235          *
236          * and then we subtract the other two coefficients (a_1 b_1
237          * and a_0 b_0) which we were computing anyway.
238          *
239          * Hence we get to multiply two numbers of length N in about
240          * three times as much work as it takes to multiply numbers of
241          * length N/2, which is obviously better than the four times
242          * as much work it would take if we just did a long
243          * conventional multiply.
244          */
245
246         int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
247         int midlen = botlen + 1;
248         BignumInt *scratch;
249         BignumDblInt carry;
250
251         /*
252          * The coefficients a_1 b_1 and a_0 b_0 just avoid overlapping
253          * in the output array, so we can compute them immediately in
254          * place.
255          */
256
257         /* a_1 b_1 */
258         internal_mul(a, b, c, toplen);
259
260         /* a_0 b_0 */
261         internal_mul(a + toplen, b + toplen, c + 2*toplen, botlen);
262
263         /*
264          * We must allocate scratch space for the central coefficient,
265          * and also for the two input values that we multiply when
266          * computing it. Since either or both may carry into the
267          * (botlen+1)th word, we must use a slightly longer length
268          * 'midlen'.
269          */
270         scratch = snewn(4 * midlen, BignumInt);
271
272         /* Zero padding. midlen exceeds toplen by at most 2, so just
273          * zero the first two words of each input and the rest will be
274          * copied over. */
275         scratch[0] = scratch[1] = scratch[midlen] = scratch[midlen+1] = 0;
276
277         for (j = 0; j < toplen; j++) {
278             scratch[midlen - toplen + j] = a[j]; /* a_1 */
279             scratch[2*midlen - toplen + j] = b[j]; /* b_1 */
280         }
281
282         /* compute a_1 + a_0 */
283         scratch[0] = internal_add(scratch+1, a+toplen, scratch+1, botlen);
284         /* compute b_1 + b_0 */
285         scratch[midlen] = internal_add(scratch+midlen+1, b+toplen,
286                                        scratch+midlen+1, botlen);
287
288         /*
289          * Now we can do the third multiplication.
290          */
291         internal_mul(scratch, scratch + midlen, scratch + 2*midlen, midlen);
292
293         /*
294          * Now we can reuse the first half of 'scratch' to compute the
295          * sum of the outer two coefficients, to subtract from that
296          * product to obtain the middle one.
297          */
298         scratch[0] = scratch[1] = scratch[2] = scratch[3] = 0;
299         for (j = 0; j < 2*toplen; j++)
300             scratch[2*midlen - 2*toplen + j] = c[j];
301         scratch[1] = internal_add(scratch+2, c + 2*toplen,
302                                   scratch+2, 2*botlen);
303
304         internal_sub(scratch + 2*midlen, scratch,
305                      scratch + 2*midlen, 2*midlen);
306
307         /*
308          * And now all we need to do is to add that middle coefficient
309          * back into the output. We may have to propagate a carry
310          * further up the output, but we can be sure it won't
311          * propagate right the way off the top.
312          */
313         carry = internal_add(c + 2*len - botlen - 2*midlen,
314                              scratch + 2*midlen,
315                              c + 2*len - botlen - 2*midlen, 2*midlen);
316         j = 2*len - botlen - 2*midlen - 1;
317         while (carry) {
318             assert(j >= 0);
319             carry += c[j];
320             c[j] = (BignumInt)carry;
321             carry >>= BIGNUM_INT_BITS;
322         }
323
324         /* Free scratch. */
325         for (j = 0; j < 4 * midlen; j++)
326             scratch[j] = 0;
327         sfree(scratch);
328
329     } else {
330
331         /*
332          * Multiply in the ordinary O(N^2) way.
333          */
334
335         for (j = 0; j < 2 * len; j++)
336             c[j] = 0;
337
338         for (i = len - 1; i >= 0; i--) {
339             t = 0;
340             for (j = len - 1; j >= 0; j--) {
341                 t += MUL_WORD(a[i], (BignumDblInt) b[j]);
342                 t += (BignumDblInt) c[i + j + 1];
343                 c[i + j + 1] = (BignumInt) t;
344                 t = t >> BIGNUM_INT_BITS;
345             }
346             c[i] = (BignumInt) t;
347         }
348     }
349 }
350
351 static void internal_add_shifted(BignumInt *number,
352                                  unsigned n, int shift)
353 {
354     int word = 1 + (shift / BIGNUM_INT_BITS);
355     int bshift = shift % BIGNUM_INT_BITS;
356     BignumDblInt addend;
357
358     addend = (BignumDblInt)n << bshift;
359
360     while (addend) {
361         addend += number[word];
362         number[word] = (BignumInt) addend & BIGNUM_INT_MASK;
363         addend >>= BIGNUM_INT_BITS;
364         word++;
365     }
366 }
367
368 /*
369  * Compute a = a % m.
370  * Input in first alen words of a and first mlen words of m.
371  * Output in first alen words of a
372  * (of which first alen-mlen words will be zero).
373  * The MSW of m MUST have its high bit set.
374  * Quotient is accumulated in the `quotient' array, which is a Bignum
375  * rather than the internal bigendian format. Quotient parts are shifted
376  * left by `qshift' before adding into quot.
377  */
378 static void internal_mod(BignumInt *a, int alen,
379                          BignumInt *m, int mlen,
380                          BignumInt *quot, int qshift)
381 {
382     BignumInt m0, m1;
383     unsigned int h;
384     int i, k;
385
386     m0 = m[0];
387     if (mlen > 1)
388         m1 = m[1];
389     else
390         m1 = 0;
391
392     for (i = 0; i <= alen - mlen; i++) {
393         BignumDblInt t;
394         unsigned int q, r, c, ai1;
395
396         if (i == 0) {
397             h = 0;
398         } else {
399             h = a[i - 1];
400             a[i - 1] = 0;
401         }
402
403         if (i == alen - 1)
404             ai1 = 0;
405         else
406             ai1 = a[i + 1];
407
408         /* Find q = h:a[i] / m0 */
409         if (h >= m0) {
410             /*
411              * Special case.
412              * 
413              * To illustrate it, suppose a BignumInt is 8 bits, and
414              * we are dividing (say) A1:23:45:67 by A1:B2:C3. Then
415              * our initial division will be 0xA123 / 0xA1, which
416              * will give a quotient of 0x100 and a divide overflow.
417              * However, the invariants in this division algorithm
418              * are not violated, since the full number A1:23:... is
419              * _less_ than the quotient prefix A1:B2:... and so the
420              * following correction loop would have sorted it out.
421              * 
422              * In this situation we set q to be the largest
423              * quotient we _can_ stomach (0xFF, of course).
424              */
425             q = BIGNUM_INT_MASK;
426         } else {
427             /* Macro doesn't want an array subscript expression passed
428              * into it (see definition), so use a temporary. */
429             BignumInt tmplo = a[i];
430             DIVMOD_WORD(q, r, h, tmplo, m0);
431
432             /* Refine our estimate of q by looking at
433              h:a[i]:a[i+1] / m0:m1 */
434             t = MUL_WORD(m1, q);
435             if (t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) {
436                 q--;
437                 t -= m1;
438                 r = (r + m0) & BIGNUM_INT_MASK;     /* overflow? */
439                 if (r >= (BignumDblInt) m0 &&
440                     t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) q--;
441             }
442         }
443
444         /* Subtract q * m from a[i...] */
445         c = 0;
446         for (k = mlen - 1; k >= 0; k--) {
447             t = MUL_WORD(q, m[k]);
448             t += c;
449             c = (unsigned)(t >> BIGNUM_INT_BITS);
450             if ((BignumInt) t > a[i + k])
451                 c++;
452             a[i + k] -= (BignumInt) t;
453         }
454
455         /* Add back m in case of borrow */
456         if (c != h) {
457             t = 0;
458             for (k = mlen - 1; k >= 0; k--) {
459                 t += m[k];
460                 t += a[i + k];
461                 a[i + k] = (BignumInt) t;
462                 t = t >> BIGNUM_INT_BITS;
463             }
464             q--;
465         }
466         if (quot)
467             internal_add_shifted(quot, q, qshift + BIGNUM_INT_BITS * (alen - mlen - i));
468     }
469 }
470
471 /*
472  * Compute (base ^ exp) % mod.
473  */
474 Bignum modpow(Bignum base_in, Bignum exp, Bignum mod)
475 {
476     BignumInt *a, *b, *n, *m;
477     int mshift;
478     int mlen, i, j;
479     Bignum base, result;
480
481     /*
482      * The most significant word of mod needs to be non-zero. It
483      * should already be, but let's make sure.
484      */
485     assert(mod[mod[0]] != 0);
486
487     /*
488      * Make sure the base is smaller than the modulus, by reducing
489      * it modulo the modulus if not.
490      */
491     base = bigmod(base_in, mod);
492
493     /* Allocate m of size mlen, copy mod to m */
494     /* We use big endian internally */
495     mlen = mod[0];
496     m = snewn(mlen, BignumInt);
497     for (j = 0; j < mlen; j++)
498         m[j] = mod[mod[0] - j];
499
500     /* Shift m left to make msb bit set */
501     for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
502         if ((m[0] << mshift) & BIGNUM_TOP_BIT)
503             break;
504     if (mshift) {
505         for (i = 0; i < mlen - 1; i++)
506             m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
507         m[mlen - 1] = m[mlen - 1] << mshift;
508     }
509
510     /* Allocate n of size mlen, copy base to n */
511     n = snewn(mlen, BignumInt);
512     i = mlen - base[0];
513     for (j = 0; j < i; j++)
514         n[j] = 0;
515     for (j = 0; j < (int)base[0]; j++)
516         n[i + j] = base[base[0] - j];
517
518     /* Allocate a and b of size 2*mlen. Set a = 1 */
519     a = snewn(2 * mlen, BignumInt);
520     b = snewn(2 * mlen, BignumInt);
521     for (i = 0; i < 2 * mlen; i++)
522         a[i] = 0;
523     a[2 * mlen - 1] = 1;
524
525     /* Skip leading zero bits of exp. */
526     i = 0;
527     j = BIGNUM_INT_BITS-1;
528     while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
529         j--;
530         if (j < 0) {
531             i++;
532             j = BIGNUM_INT_BITS-1;
533         }
534     }
535
536     /* Main computation */
537     while (i < (int)exp[0]) {
538         while (j >= 0) {
539             internal_mul(a + mlen, a + mlen, b, mlen);
540             internal_mod(b, mlen * 2, m, mlen, NULL, 0);
541             if ((exp[exp[0] - i] & (1 << j)) != 0) {
542                 internal_mul(b + mlen, n, a, mlen);
543                 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
544             } else {
545                 BignumInt *t;
546                 t = a;
547                 a = b;
548                 b = t;
549             }
550             j--;
551         }
552         i++;
553         j = BIGNUM_INT_BITS-1;
554     }
555
556     /* Fixup result in case the modulus was shifted */
557     if (mshift) {
558         for (i = mlen - 1; i < 2 * mlen - 1; i++)
559             a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
560         a[2 * mlen - 1] = a[2 * mlen - 1] << mshift;
561         internal_mod(a, mlen * 2, m, mlen, NULL, 0);
562         for (i = 2 * mlen - 1; i >= mlen; i--)
563             a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
564     }
565
566     /* Copy result to buffer */
567     result = newbn(mod[0]);
568     for (i = 0; i < mlen; i++)
569         result[result[0] - i] = a[i + mlen];
570     while (result[0] > 1 && result[result[0]] == 0)
571         result[0]--;
572
573     /* Free temporary arrays */
574     for (i = 0; i < 2 * mlen; i++)
575         a[i] = 0;
576     sfree(a);
577     for (i = 0; i < 2 * mlen; i++)
578         b[i] = 0;
579     sfree(b);
580     for (i = 0; i < mlen; i++)
581         m[i] = 0;
582     sfree(m);
583     for (i = 0; i < mlen; i++)
584         n[i] = 0;
585     sfree(n);
586
587     freebn(base);
588
589     return result;
590 }
591
592 /*
593  * Compute (p * q) % mod.
594  * The most significant word of mod MUST be non-zero.
595  * We assume that the result array is the same size as the mod array.
596  */
597 Bignum modmul(Bignum p, Bignum q, Bignum mod)
598 {
599     BignumInt *a, *n, *m, *o;
600     int mshift;
601     int pqlen, mlen, rlen, i, j;
602     Bignum result;
603
604     /* Allocate m of size mlen, copy mod to m */
605     /* We use big endian internally */
606     mlen = mod[0];
607     m = snewn(mlen, BignumInt);
608     for (j = 0; j < mlen; j++)
609         m[j] = mod[mod[0] - j];
610
611     /* Shift m left to make msb bit set */
612     for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
613         if ((m[0] << mshift) & BIGNUM_TOP_BIT)
614             break;
615     if (mshift) {
616         for (i = 0; i < mlen - 1; i++)
617             m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
618         m[mlen - 1] = m[mlen - 1] << mshift;
619     }
620
621     pqlen = (p[0] > q[0] ? p[0] : q[0]);
622
623     /* Allocate n of size pqlen, copy p to n */
624     n = snewn(pqlen, BignumInt);
625     i = pqlen - p[0];
626     for (j = 0; j < i; j++)
627         n[j] = 0;
628     for (j = 0; j < (int)p[0]; j++)
629         n[i + j] = p[p[0] - j];
630
631     /* Allocate o of size pqlen, copy q to o */
632     o = snewn(pqlen, BignumInt);
633     i = pqlen - q[0];
634     for (j = 0; j < i; j++)
635         o[j] = 0;
636     for (j = 0; j < (int)q[0]; j++)
637         o[i + j] = q[q[0] - j];
638
639     /* Allocate a of size 2*pqlen for result */
640     a = snewn(2 * pqlen, BignumInt);
641
642     /* Main computation */
643     internal_mul(n, o, a, pqlen);
644     internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
645
646     /* Fixup result in case the modulus was shifted */
647     if (mshift) {
648         for (i = 2 * pqlen - mlen - 1; i < 2 * pqlen - 1; i++)
649             a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
650         a[2 * pqlen - 1] = a[2 * pqlen - 1] << mshift;
651         internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
652         for (i = 2 * pqlen - 1; i >= 2 * pqlen - mlen; i--)
653             a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
654     }
655
656     /* Copy result to buffer */
657     rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
658     result = newbn(rlen);
659     for (i = 0; i < rlen; i++)
660         result[result[0] - i] = a[i + 2 * pqlen - rlen];
661     while (result[0] > 1 && result[result[0]] == 0)
662         result[0]--;
663
664     /* Free temporary arrays */
665     for (i = 0; i < 2 * pqlen; i++)
666         a[i] = 0;
667     sfree(a);
668     for (i = 0; i < mlen; i++)
669         m[i] = 0;
670     sfree(m);
671     for (i = 0; i < pqlen; i++)
672         n[i] = 0;
673     sfree(n);
674     for (i = 0; i < pqlen; i++)
675         o[i] = 0;
676     sfree(o);
677
678     return result;
679 }
680
681 /*
682  * Compute p % mod.
683  * The most significant word of mod MUST be non-zero.
684  * We assume that the result array is the same size as the mod array.
685  * We optionally write out a quotient if `quotient' is non-NULL.
686  * We can avoid writing out the result if `result' is NULL.
687  */
688 static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
689 {
690     BignumInt *n, *m;
691     int mshift;
692     int plen, mlen, i, j;
693
694     /* Allocate m of size mlen, copy mod to m */
695     /* We use big endian internally */
696     mlen = mod[0];
697     m = snewn(mlen, BignumInt);
698     for (j = 0; j < mlen; j++)
699         m[j] = mod[mod[0] - j];
700
701     /* Shift m left to make msb bit set */
702     for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
703         if ((m[0] << mshift) & BIGNUM_TOP_BIT)
704             break;
705     if (mshift) {
706         for (i = 0; i < mlen - 1; i++)
707             m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
708         m[mlen - 1] = m[mlen - 1] << mshift;
709     }
710
711     plen = p[0];
712     /* Ensure plen > mlen */
713     if (plen <= mlen)
714         plen = mlen + 1;
715
716     /* Allocate n of size plen, copy p to n */
717     n = snewn(plen, BignumInt);
718     for (j = 0; j < plen; j++)
719         n[j] = 0;
720     for (j = 1; j <= (int)p[0]; j++)
721         n[plen - j] = p[j];
722
723     /* Main computation */
724     internal_mod(n, plen, m, mlen, quotient, mshift);
725
726     /* Fixup result in case the modulus was shifted */
727     if (mshift) {
728         for (i = plen - mlen - 1; i < plen - 1; i++)
729             n[i] = (n[i] << mshift) | (n[i + 1] >> (BIGNUM_INT_BITS - mshift));
730         n[plen - 1] = n[plen - 1] << mshift;
731         internal_mod(n, plen, m, mlen, quotient, 0);
732         for (i = plen - 1; i >= plen - mlen; i--)
733             n[i] = (n[i] >> mshift) | (n[i - 1] << (BIGNUM_INT_BITS - mshift));
734     }
735
736     /* Copy result to buffer */
737     if (result) {
738         for (i = 1; i <= (int)result[0]; i++) {
739             int j = plen - i;
740             result[i] = j >= 0 ? n[j] : 0;
741         }
742     }
743
744     /* Free temporary arrays */
745     for (i = 0; i < mlen; i++)
746         m[i] = 0;
747     sfree(m);
748     for (i = 0; i < plen; i++)
749         n[i] = 0;
750     sfree(n);
751 }
752
753 /*
754  * Decrement a number.
755  */
756 void decbn(Bignum bn)
757 {
758     int i = 1;
759     while (i < (int)bn[0] && bn[i] == 0)
760         bn[i++] = BIGNUM_INT_MASK;
761     bn[i]--;
762 }
763
764 Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
765 {
766     Bignum result;
767     int w, i;
768
769     w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
770
771     result = newbn(w);
772     for (i = 1; i <= w; i++)
773         result[i] = 0;
774     for (i = nbytes; i--;) {
775         unsigned char byte = *data++;
776         result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);
777     }
778
779     while (result[0] > 1 && result[result[0]] == 0)
780         result[0]--;
781     return result;
782 }
783
784 /*
785  * Read an SSH-1-format bignum from a data buffer. Return the number
786  * of bytes consumed, or -1 if there wasn't enough data.
787  */
788 int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)
789 {
790     const unsigned char *p = data;
791     int i;
792     int w, b;
793
794     if (len < 2)
795         return -1;
796
797     w = 0;
798     for (i = 0; i < 2; i++)
799         w = (w << 8) + *p++;
800     b = (w + 7) / 8;                   /* bits -> bytes */
801
802     if (len < b+2)
803         return -1;
804
805     if (!result)                       /* just return length */
806         return b + 2;
807
808     *result = bignum_from_bytes(p, b);
809
810     return p + b - data;
811 }
812
813 /*
814  * Return the bit count of a bignum, for SSH-1 encoding.
815  */
816 int bignum_bitcount(Bignum bn)
817 {
818     int bitcount = bn[0] * BIGNUM_INT_BITS - 1;
819     while (bitcount >= 0
820            && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;
821     return bitcount + 1;
822 }
823
824 /*
825  * Return the byte length of a bignum when SSH-1 encoded.
826  */
827 int ssh1_bignum_length(Bignum bn)
828 {
829     return 2 + (bignum_bitcount(bn) + 7) / 8;
830 }
831
832 /*
833  * Return the byte length of a bignum when SSH-2 encoded.
834  */
835 int ssh2_bignum_length(Bignum bn)
836 {
837     return 4 + (bignum_bitcount(bn) + 8) / 8;
838 }
839
840 /*
841  * Return a byte from a bignum; 0 is least significant, etc.
842  */
843 int bignum_byte(Bignum bn, int i)
844 {
845     if (i >= (int)(BIGNUM_INT_BYTES * bn[0]))
846         return 0;                      /* beyond the end */
847     else
848         return (bn[i / BIGNUM_INT_BYTES + 1] >>
849                 ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;
850 }
851
852 /*
853  * Return a bit from a bignum; 0 is least significant, etc.
854  */
855 int bignum_bit(Bignum bn, int i)
856 {
857     if (i >= (int)(BIGNUM_INT_BITS * bn[0]))
858         return 0;                      /* beyond the end */
859     else
860         return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;
861 }
862
863 /*
864  * Set a bit in a bignum; 0 is least significant, etc.
865  */
866 void bignum_set_bit(Bignum bn, int bitnum, int value)
867 {
868     if (bitnum >= (int)(BIGNUM_INT_BITS * bn[0]))
869         abort();                       /* beyond the end */
870     else {
871         int v = bitnum / BIGNUM_INT_BITS + 1;
872         int mask = 1 << (bitnum % BIGNUM_INT_BITS);
873         if (value)
874             bn[v] |= mask;
875         else
876             bn[v] &= ~mask;
877     }
878 }
879
880 /*
881  * Write a SSH-1-format bignum into a buffer. It is assumed the
882  * buffer is big enough. Returns the number of bytes used.
883  */
884 int ssh1_write_bignum(void *data, Bignum bn)
885 {
886     unsigned char *p = data;
887     int len = ssh1_bignum_length(bn);
888     int i;
889     int bitc = bignum_bitcount(bn);
890
891     *p++ = (bitc >> 8) & 0xFF;
892     *p++ = (bitc) & 0xFF;
893     for (i = len - 2; i--;)
894         *p++ = bignum_byte(bn, i);
895     return len;
896 }
897
898 /*
899  * Compare two bignums. Returns like strcmp.
900  */
901 int bignum_cmp(Bignum a, Bignum b)
902 {
903     int amax = a[0], bmax = b[0];
904     int i = (amax > bmax ? amax : bmax);
905     while (i) {
906         BignumInt aval = (i > amax ? 0 : a[i]);
907         BignumInt bval = (i > bmax ? 0 : b[i]);
908         if (aval < bval)
909             return -1;
910         if (aval > bval)
911             return +1;
912         i--;
913     }
914     return 0;
915 }
916
917 /*
918  * Right-shift one bignum to form another.
919  */
920 Bignum bignum_rshift(Bignum a, int shift)
921 {
922     Bignum ret;
923     int i, shiftw, shiftb, shiftbb, bits;
924     BignumInt ai, ai1;
925
926     bits = bignum_bitcount(a) - shift;
927     ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
928
929     if (ret) {
930         shiftw = shift / BIGNUM_INT_BITS;
931         shiftb = shift % BIGNUM_INT_BITS;
932         shiftbb = BIGNUM_INT_BITS - shiftb;
933
934         ai1 = a[shiftw + 1];
935         for (i = 1; i <= (int)ret[0]; i++) {
936             ai = ai1;
937             ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);
938             ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;
939         }
940     }
941
942     return ret;
943 }
944
945 /*
946  * Non-modular multiplication and addition.
947  */
948 Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
949 {
950     int alen = a[0], blen = b[0];
951     int mlen = (alen > blen ? alen : blen);
952     int rlen, i, maxspot;
953     BignumInt *workspace;
954     Bignum ret;
955
956     /* mlen space for a, mlen space for b, 2*mlen for result */
957     workspace = snewn(mlen * 4, BignumInt);
958     for (i = 0; i < mlen; i++) {
959         workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);
960         workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);
961     }
962
963     internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
964                  workspace + 2 * mlen, mlen);
965
966     /* now just copy the result back */
967     rlen = alen + blen + 1;
968     if (addend && rlen <= (int)addend[0])
969         rlen = addend[0] + 1;
970     ret = newbn(rlen);
971     maxspot = 0;
972     for (i = 1; i <= (int)ret[0]; i++) {
973         ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
974         if (ret[i] != 0)
975             maxspot = i;
976     }
977     ret[0] = maxspot;
978
979     /* now add in the addend, if any */
980     if (addend) {
981         BignumDblInt carry = 0;
982         for (i = 1; i <= rlen; i++) {
983             carry += (i <= (int)ret[0] ? ret[i] : 0);
984             carry += (i <= (int)addend[0] ? addend[i] : 0);
985             ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
986             carry >>= BIGNUM_INT_BITS;
987             if (ret[i] != 0 && i > maxspot)
988                 maxspot = i;
989         }
990     }
991     ret[0] = maxspot;
992
993     sfree(workspace);
994     return ret;
995 }
996
997 /*
998  * Non-modular multiplication.
999  */
1000 Bignum bigmul(Bignum a, Bignum b)
1001 {
1002     return bigmuladd(a, b, NULL);
1003 }
1004
1005 /*
1006  * Create a bignum which is the bitmask covering another one. That
1007  * is, the smallest integer which is >= N and is also one less than
1008  * a power of two.
1009  */
1010 Bignum bignum_bitmask(Bignum n)
1011 {
1012     Bignum ret = copybn(n);
1013     int i;
1014     BignumInt j;
1015
1016     i = ret[0];
1017     while (n[i] == 0 && i > 0)
1018         i--;
1019     if (i <= 0)
1020         return ret;                    /* input was zero */
1021     j = 1;
1022     while (j < n[i])
1023         j = 2 * j + 1;
1024     ret[i] = j;
1025     while (--i > 0)
1026         ret[i] = BIGNUM_INT_MASK;
1027     return ret;
1028 }
1029
1030 /*
1031  * Convert a (max 32-bit) long into a bignum.
1032  */
1033 Bignum bignum_from_long(unsigned long nn)
1034 {
1035     Bignum ret;
1036     BignumDblInt n = nn;
1037
1038     ret = newbn(3);
1039     ret[1] = (BignumInt)(n & BIGNUM_INT_MASK);
1040     ret[2] = (BignumInt)((n >> BIGNUM_INT_BITS) & BIGNUM_INT_MASK);
1041     ret[3] = 0;
1042     ret[0] = (ret[2]  ? 2 : 1);
1043     return ret;
1044 }
1045
1046 /*
1047  * Add a long to a bignum.
1048  */
1049 Bignum bignum_add_long(Bignum number, unsigned long addendx)
1050 {
1051     Bignum ret = newbn(number[0] + 1);
1052     int i, maxspot = 0;
1053     BignumDblInt carry = 0, addend = addendx;
1054
1055     for (i = 1; i <= (int)ret[0]; i++) {
1056         carry += addend & BIGNUM_INT_MASK;
1057         carry += (i <= (int)number[0] ? number[i] : 0);
1058         addend >>= BIGNUM_INT_BITS;
1059         ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1060         carry >>= BIGNUM_INT_BITS;
1061         if (ret[i] != 0)
1062             maxspot = i;
1063     }
1064     ret[0] = maxspot;
1065     return ret;
1066 }
1067
1068 /*
1069  * Compute the residue of a bignum, modulo a (max 16-bit) short.
1070  */
1071 unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
1072 {
1073     BignumDblInt mod, r;
1074     int i;
1075
1076     r = 0;
1077     mod = modulus;
1078     for (i = number[0]; i > 0; i--)
1079         r = (r * (BIGNUM_TOP_BIT % mod) * 2 + number[i] % mod) % mod;
1080     return (unsigned short) r;
1081 }
1082
1083 #ifdef DEBUG
1084 void diagbn(char *prefix, Bignum md)
1085 {
1086     int i, nibbles, morenibbles;
1087     static const char hex[] = "0123456789ABCDEF";
1088
1089     debug(("%s0x", prefix ? prefix : ""));
1090
1091     nibbles = (3 + bignum_bitcount(md)) / 4;
1092     if (nibbles < 1)
1093         nibbles = 1;
1094     morenibbles = 4 * md[0] - nibbles;
1095     for (i = 0; i < morenibbles; i++)
1096         debug(("-"));
1097     for (i = nibbles; i--;)
1098         debug(("%c",
1099                hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
1100
1101     if (prefix)
1102         debug(("\n"));
1103 }
1104 #endif
1105
1106 /*
1107  * Simple division.
1108  */
1109 Bignum bigdiv(Bignum a, Bignum b)
1110 {
1111     Bignum q = newbn(a[0]);
1112     bigdivmod(a, b, NULL, q);
1113     return q;
1114 }
1115
1116 /*
1117  * Simple remainder.
1118  */
1119 Bignum bigmod(Bignum a, Bignum b)
1120 {
1121     Bignum r = newbn(b[0]);
1122     bigdivmod(a, b, r, NULL);
1123     return r;
1124 }
1125
1126 /*
1127  * Greatest common divisor.
1128  */
1129 Bignum biggcd(Bignum av, Bignum bv)
1130 {
1131     Bignum a = copybn(av);
1132     Bignum b = copybn(bv);
1133
1134     while (bignum_cmp(b, Zero) != 0) {
1135         Bignum t = newbn(b[0]);
1136         bigdivmod(a, b, t, NULL);
1137         while (t[0] > 1 && t[t[0]] == 0)
1138             t[0]--;
1139         freebn(a);
1140         a = b;
1141         b = t;
1142     }
1143
1144     freebn(b);
1145     return a;
1146 }
1147
1148 /*
1149  * Modular inverse, using Euclid's extended algorithm.
1150  */
1151 Bignum modinv(Bignum number, Bignum modulus)
1152 {
1153     Bignum a = copybn(modulus);
1154     Bignum b = copybn(number);
1155     Bignum xp = copybn(Zero);
1156     Bignum x = copybn(One);
1157     int sign = +1;
1158
1159     while (bignum_cmp(b, One) != 0) {
1160         Bignum t = newbn(b[0]);
1161         Bignum q = newbn(a[0]);
1162         bigdivmod(a, b, t, q);
1163         while (t[0] > 1 && t[t[0]] == 0)
1164             t[0]--;
1165         freebn(a);
1166         a = b;
1167         b = t;
1168         t = xp;
1169         xp = x;
1170         x = bigmuladd(q, xp, t);
1171         sign = -sign;
1172         freebn(t);
1173         freebn(q);
1174     }
1175
1176     freebn(b);
1177     freebn(a);
1178     freebn(xp);
1179
1180     /* now we know that sign * x == 1, and that x < modulus */
1181     if (sign < 0) {
1182         /* set a new x to be modulus - x */
1183         Bignum newx = newbn(modulus[0]);
1184         BignumInt carry = 0;
1185         int maxspot = 1;
1186         int i;
1187
1188         for (i = 1; i <= (int)newx[0]; i++) {
1189             BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);
1190             BignumInt bword = (i <= (int)x[0] ? x[i] : 0);
1191             newx[i] = aword - bword - carry;
1192             bword = ~bword;
1193             carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
1194             if (newx[i] != 0)
1195                 maxspot = i;
1196         }
1197         newx[0] = maxspot;
1198         freebn(x);
1199         x = newx;
1200     }
1201
1202     /* and return. */
1203     return x;
1204 }
1205
1206 /*
1207  * Render a bignum into decimal. Return a malloced string holding
1208  * the decimal representation.
1209  */
1210 char *bignum_decimal(Bignum x)
1211 {
1212     int ndigits, ndigit;
1213     int i, iszero;
1214     BignumDblInt carry;
1215     char *ret;
1216     BignumInt *workspace;
1217
1218     /*
1219      * First, estimate the number of digits. Since log(10)/log(2)
1220      * is just greater than 93/28 (the joys of continued fraction
1221      * approximations...) we know that for every 93 bits, we need
1222      * at most 28 digits. This will tell us how much to malloc.
1223      *
1224      * Formally: if x has i bits, that means x is strictly less
1225      * than 2^i. Since 2 is less than 10^(28/93), this is less than
1226      * 10^(28i/93). We need an integer power of ten, so we must
1227      * round up (rounding down might make it less than x again).
1228      * Therefore if we multiply the bit count by 28/93, rounding
1229      * up, we will have enough digits.
1230      *
1231      * i=0 (i.e., x=0) is an irritating special case.
1232      */
1233     i = bignum_bitcount(x);
1234     if (!i)
1235         ndigits = 1;                   /* x = 0 */
1236     else
1237         ndigits = (28 * i + 92) / 93;  /* multiply by 28/93 and round up */
1238     ndigits++;                         /* allow for trailing \0 */
1239     ret = snewn(ndigits, char);
1240
1241     /*
1242      * Now allocate some workspace to hold the binary form as we
1243      * repeatedly divide it by ten. Initialise this to the
1244      * big-endian form of the number.
1245      */
1246     workspace = snewn(x[0], BignumInt);
1247     for (i = 0; i < (int)x[0]; i++)
1248         workspace[i] = x[x[0] - i];
1249
1250     /*
1251      * Next, write the decimal number starting with the last digit.
1252      * We use ordinary short division, dividing 10 into the
1253      * workspace.
1254      */
1255     ndigit = ndigits - 1;
1256     ret[ndigit] = '\0';
1257     do {
1258         iszero = 1;
1259         carry = 0;
1260         for (i = 0; i < (int)x[0]; i++) {
1261             carry = (carry << BIGNUM_INT_BITS) + workspace[i];
1262             workspace[i] = (BignumInt) (carry / 10);
1263             if (workspace[i])
1264                 iszero = 0;
1265             carry %= 10;
1266         }
1267         ret[--ndigit] = (char) (carry + '0');
1268     } while (!iszero);
1269
1270     /*
1271      * There's a chance we've fallen short of the start of the
1272      * string. Correct if so.
1273      */
1274     if (ndigit > 0)
1275         memmove(ret, ret + ndigit, ndigits - ndigit);
1276
1277     /*
1278      * Done.
1279      */
1280     sfree(workspace);
1281     return ret;
1282 }