]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - sshbn.c
Add some appropriate bignum typedefs for generic 64-bit systems,
[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  * Compute c = a * b.
164  * Input is in the first len words of a and b.
165  * Result is returned in the first 2*len words of c.
166  */
167 static void internal_mul(BignumInt *a, BignumInt *b,
168                          BignumInt *c, int len)
169 {
170     int i, j;
171     BignumDblInt t;
172
173     for (j = 0; j < 2 * len; j++)
174         c[j] = 0;
175
176     for (i = len - 1; i >= 0; i--) {
177         t = 0;
178         for (j = len - 1; j >= 0; j--) {
179             t += MUL_WORD(a[i], (BignumDblInt) b[j]);
180             t += (BignumDblInt) c[i + j + 1];
181             c[i + j + 1] = (BignumInt) t;
182             t = t >> BIGNUM_INT_BITS;
183         }
184         c[i] = (BignumInt) t;
185     }
186 }
187
188 static void internal_add_shifted(BignumInt *number,
189                                  unsigned n, int shift)
190 {
191     int word = 1 + (shift / BIGNUM_INT_BITS);
192     int bshift = shift % BIGNUM_INT_BITS;
193     BignumDblInt addend;
194
195     addend = (BignumDblInt)n << bshift;
196
197     while (addend) {
198         addend += number[word];
199         number[word] = (BignumInt) addend & BIGNUM_INT_MASK;
200         addend >>= BIGNUM_INT_BITS;
201         word++;
202     }
203 }
204
205 /*
206  * Compute a = a % m.
207  * Input in first alen words of a and first mlen words of m.
208  * Output in first alen words of a
209  * (of which first alen-mlen words will be zero).
210  * The MSW of m MUST have its high bit set.
211  * Quotient is accumulated in the `quotient' array, which is a Bignum
212  * rather than the internal bigendian format. Quotient parts are shifted
213  * left by `qshift' before adding into quot.
214  */
215 static void internal_mod(BignumInt *a, int alen,
216                          BignumInt *m, int mlen,
217                          BignumInt *quot, int qshift)
218 {
219     BignumInt m0, m1;
220     unsigned int h;
221     int i, k;
222
223     m0 = m[0];
224     if (mlen > 1)
225         m1 = m[1];
226     else
227         m1 = 0;
228
229     for (i = 0; i <= alen - mlen; i++) {
230         BignumDblInt t;
231         unsigned int q, r, c, ai1;
232
233         if (i == 0) {
234             h = 0;
235         } else {
236             h = a[i - 1];
237             a[i - 1] = 0;
238         }
239
240         if (i == alen - 1)
241             ai1 = 0;
242         else
243             ai1 = a[i + 1];
244
245         /* Find q = h:a[i] / m0 */
246         if (h >= m0) {
247             /*
248              * Special case.
249              * 
250              * To illustrate it, suppose a BignumInt is 8 bits, and
251              * we are dividing (say) A1:23:45:67 by A1:B2:C3. Then
252              * our initial division will be 0xA123 / 0xA1, which
253              * will give a quotient of 0x100 and a divide overflow.
254              * However, the invariants in this division algorithm
255              * are not violated, since the full number A1:23:... is
256              * _less_ than the quotient prefix A1:B2:... and so the
257              * following correction loop would have sorted it out.
258              * 
259              * In this situation we set q to be the largest
260              * quotient we _can_ stomach (0xFF, of course).
261              */
262             q = BIGNUM_INT_MASK;
263         } else {
264             /* Macro doesn't want an array subscript expression passed
265              * into it (see definition), so use a temporary. */
266             BignumInt tmplo = a[i];
267             DIVMOD_WORD(q, r, h, tmplo, m0);
268
269             /* Refine our estimate of q by looking at
270              h:a[i]:a[i+1] / m0:m1 */
271             t = MUL_WORD(m1, q);
272             if (t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) {
273                 q--;
274                 t -= m1;
275                 r = (r + m0) & BIGNUM_INT_MASK;     /* overflow? */
276                 if (r >= (BignumDblInt) m0 &&
277                     t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) q--;
278             }
279         }
280
281         /* Subtract q * m from a[i...] */
282         c = 0;
283         for (k = mlen - 1; k >= 0; k--) {
284             t = MUL_WORD(q, m[k]);
285             t += c;
286             c = (unsigned)(t >> BIGNUM_INT_BITS);
287             if ((BignumInt) t > a[i + k])
288                 c++;
289             a[i + k] -= (BignumInt) t;
290         }
291
292         /* Add back m in case of borrow */
293         if (c != h) {
294             t = 0;
295             for (k = mlen - 1; k >= 0; k--) {
296                 t += m[k];
297                 t += a[i + k];
298                 a[i + k] = (BignumInt) t;
299                 t = t >> BIGNUM_INT_BITS;
300             }
301             q--;
302         }
303         if (quot)
304             internal_add_shifted(quot, q, qshift + BIGNUM_INT_BITS * (alen - mlen - i));
305     }
306 }
307
308 /*
309  * Compute (base ^ exp) % mod.
310  */
311 Bignum modpow(Bignum base_in, Bignum exp, Bignum mod)
312 {
313     BignumInt *a, *b, *n, *m;
314     int mshift;
315     int mlen, i, j;
316     Bignum base, result;
317
318     /*
319      * The most significant word of mod needs to be non-zero. It
320      * should already be, but let's make sure.
321      */
322     assert(mod[mod[0]] != 0);
323
324     /*
325      * Make sure the base is smaller than the modulus, by reducing
326      * it modulo the modulus if not.
327      */
328     base = bigmod(base_in, mod);
329
330     /* Allocate m of size mlen, copy mod to m */
331     /* We use big endian internally */
332     mlen = mod[0];
333     m = snewn(mlen, BignumInt);
334     for (j = 0; j < mlen; j++)
335         m[j] = mod[mod[0] - j];
336
337     /* Shift m left to make msb bit set */
338     for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
339         if ((m[0] << mshift) & BIGNUM_TOP_BIT)
340             break;
341     if (mshift) {
342         for (i = 0; i < mlen - 1; i++)
343             m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
344         m[mlen - 1] = m[mlen - 1] << mshift;
345     }
346
347     /* Allocate n of size mlen, copy base to n */
348     n = snewn(mlen, BignumInt);
349     i = mlen - base[0];
350     for (j = 0; j < i; j++)
351         n[j] = 0;
352     for (j = 0; j < (int)base[0]; j++)
353         n[i + j] = base[base[0] - j];
354
355     /* Allocate a and b of size 2*mlen. Set a = 1 */
356     a = snewn(2 * mlen, BignumInt);
357     b = snewn(2 * mlen, BignumInt);
358     for (i = 0; i < 2 * mlen; i++)
359         a[i] = 0;
360     a[2 * mlen - 1] = 1;
361
362     /* Skip leading zero bits of exp. */
363     i = 0;
364     j = BIGNUM_INT_BITS-1;
365     while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
366         j--;
367         if (j < 0) {
368             i++;
369             j = BIGNUM_INT_BITS-1;
370         }
371     }
372
373     /* Main computation */
374     while (i < (int)exp[0]) {
375         while (j >= 0) {
376             internal_mul(a + mlen, a + mlen, b, mlen);
377             internal_mod(b, mlen * 2, m, mlen, NULL, 0);
378             if ((exp[exp[0] - i] & (1 << j)) != 0) {
379                 internal_mul(b + mlen, n, a, mlen);
380                 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
381             } else {
382                 BignumInt *t;
383                 t = a;
384                 a = b;
385                 b = t;
386             }
387             j--;
388         }
389         i++;
390         j = BIGNUM_INT_BITS-1;
391     }
392
393     /* Fixup result in case the modulus was shifted */
394     if (mshift) {
395         for (i = mlen - 1; i < 2 * mlen - 1; i++)
396             a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
397         a[2 * mlen - 1] = a[2 * mlen - 1] << mshift;
398         internal_mod(a, mlen * 2, m, mlen, NULL, 0);
399         for (i = 2 * mlen - 1; i >= mlen; i--)
400             a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
401     }
402
403     /* Copy result to buffer */
404     result = newbn(mod[0]);
405     for (i = 0; i < mlen; i++)
406         result[result[0] - i] = a[i + mlen];
407     while (result[0] > 1 && result[result[0]] == 0)
408         result[0]--;
409
410     /* Free temporary arrays */
411     for (i = 0; i < 2 * mlen; i++)
412         a[i] = 0;
413     sfree(a);
414     for (i = 0; i < 2 * mlen; i++)
415         b[i] = 0;
416     sfree(b);
417     for (i = 0; i < mlen; i++)
418         m[i] = 0;
419     sfree(m);
420     for (i = 0; i < mlen; i++)
421         n[i] = 0;
422     sfree(n);
423
424     freebn(base);
425
426     return result;
427 }
428
429 /*
430  * Compute (p * q) % mod.
431  * The most significant word of mod MUST be non-zero.
432  * We assume that the result array is the same size as the mod array.
433  */
434 Bignum modmul(Bignum p, Bignum q, Bignum mod)
435 {
436     BignumInt *a, *n, *m, *o;
437     int mshift;
438     int pqlen, mlen, rlen, i, j;
439     Bignum result;
440
441     /* Allocate m of size mlen, copy mod to m */
442     /* We use big endian internally */
443     mlen = mod[0];
444     m = snewn(mlen, BignumInt);
445     for (j = 0; j < mlen; j++)
446         m[j] = mod[mod[0] - j];
447
448     /* Shift m left to make msb bit set */
449     for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
450         if ((m[0] << mshift) & BIGNUM_TOP_BIT)
451             break;
452     if (mshift) {
453         for (i = 0; i < mlen - 1; i++)
454             m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
455         m[mlen - 1] = m[mlen - 1] << mshift;
456     }
457
458     pqlen = (p[0] > q[0] ? p[0] : q[0]);
459
460     /* Allocate n of size pqlen, copy p to n */
461     n = snewn(pqlen, BignumInt);
462     i = pqlen - p[0];
463     for (j = 0; j < i; j++)
464         n[j] = 0;
465     for (j = 0; j < (int)p[0]; j++)
466         n[i + j] = p[p[0] - j];
467
468     /* Allocate o of size pqlen, copy q to o */
469     o = snewn(pqlen, BignumInt);
470     i = pqlen - q[0];
471     for (j = 0; j < i; j++)
472         o[j] = 0;
473     for (j = 0; j < (int)q[0]; j++)
474         o[i + j] = q[q[0] - j];
475
476     /* Allocate a of size 2*pqlen for result */
477     a = snewn(2 * pqlen, BignumInt);
478
479     /* Main computation */
480     internal_mul(n, o, a, pqlen);
481     internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
482
483     /* Fixup result in case the modulus was shifted */
484     if (mshift) {
485         for (i = 2 * pqlen - mlen - 1; i < 2 * pqlen - 1; i++)
486             a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
487         a[2 * pqlen - 1] = a[2 * pqlen - 1] << mshift;
488         internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
489         for (i = 2 * pqlen - 1; i >= 2 * pqlen - mlen; i--)
490             a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
491     }
492
493     /* Copy result to buffer */
494     rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
495     result = newbn(rlen);
496     for (i = 0; i < rlen; i++)
497         result[result[0] - i] = a[i + 2 * pqlen - rlen];
498     while (result[0] > 1 && result[result[0]] == 0)
499         result[0]--;
500
501     /* Free temporary arrays */
502     for (i = 0; i < 2 * pqlen; i++)
503         a[i] = 0;
504     sfree(a);
505     for (i = 0; i < mlen; i++)
506         m[i] = 0;
507     sfree(m);
508     for (i = 0; i < pqlen; i++)
509         n[i] = 0;
510     sfree(n);
511     for (i = 0; i < pqlen; i++)
512         o[i] = 0;
513     sfree(o);
514
515     return result;
516 }
517
518 /*
519  * Compute p % mod.
520  * The most significant word of mod MUST be non-zero.
521  * We assume that the result array is the same size as the mod array.
522  * We optionally write out a quotient if `quotient' is non-NULL.
523  * We can avoid writing out the result if `result' is NULL.
524  */
525 static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
526 {
527     BignumInt *n, *m;
528     int mshift;
529     int plen, mlen, i, j;
530
531     /* Allocate m of size mlen, copy mod to m */
532     /* We use big endian internally */
533     mlen = mod[0];
534     m = snewn(mlen, BignumInt);
535     for (j = 0; j < mlen; j++)
536         m[j] = mod[mod[0] - j];
537
538     /* Shift m left to make msb bit set */
539     for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
540         if ((m[0] << mshift) & BIGNUM_TOP_BIT)
541             break;
542     if (mshift) {
543         for (i = 0; i < mlen - 1; i++)
544             m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
545         m[mlen - 1] = m[mlen - 1] << mshift;
546     }
547
548     plen = p[0];
549     /* Ensure plen > mlen */
550     if (plen <= mlen)
551         plen = mlen + 1;
552
553     /* Allocate n of size plen, copy p to n */
554     n = snewn(plen, BignumInt);
555     for (j = 0; j < plen; j++)
556         n[j] = 0;
557     for (j = 1; j <= (int)p[0]; j++)
558         n[plen - j] = p[j];
559
560     /* Main computation */
561     internal_mod(n, plen, m, mlen, quotient, mshift);
562
563     /* Fixup result in case the modulus was shifted */
564     if (mshift) {
565         for (i = plen - mlen - 1; i < plen - 1; i++)
566             n[i] = (n[i] << mshift) | (n[i + 1] >> (BIGNUM_INT_BITS - mshift));
567         n[plen - 1] = n[plen - 1] << mshift;
568         internal_mod(n, plen, m, mlen, quotient, 0);
569         for (i = plen - 1; i >= plen - mlen; i--)
570             n[i] = (n[i] >> mshift) | (n[i - 1] << (BIGNUM_INT_BITS - mshift));
571     }
572
573     /* Copy result to buffer */
574     if (result) {
575         for (i = 1; i <= (int)result[0]; i++) {
576             int j = plen - i;
577             result[i] = j >= 0 ? n[j] : 0;
578         }
579     }
580
581     /* Free temporary arrays */
582     for (i = 0; i < mlen; i++)
583         m[i] = 0;
584     sfree(m);
585     for (i = 0; i < plen; i++)
586         n[i] = 0;
587     sfree(n);
588 }
589
590 /*
591  * Decrement a number.
592  */
593 void decbn(Bignum bn)
594 {
595     int i = 1;
596     while (i < (int)bn[0] && bn[i] == 0)
597         bn[i++] = BIGNUM_INT_MASK;
598     bn[i]--;
599 }
600
601 Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
602 {
603     Bignum result;
604     int w, i;
605
606     w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
607
608     result = newbn(w);
609     for (i = 1; i <= w; i++)
610         result[i] = 0;
611     for (i = nbytes; i--;) {
612         unsigned char byte = *data++;
613         result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);
614     }
615
616     while (result[0] > 1 && result[result[0]] == 0)
617         result[0]--;
618     return result;
619 }
620
621 /*
622  * Read an SSH-1-format bignum from a data buffer. Return the number
623  * of bytes consumed, or -1 if there wasn't enough data.
624  */
625 int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)
626 {
627     const unsigned char *p = data;
628     int i;
629     int w, b;
630
631     if (len < 2)
632         return -1;
633
634     w = 0;
635     for (i = 0; i < 2; i++)
636         w = (w << 8) + *p++;
637     b = (w + 7) / 8;                   /* bits -> bytes */
638
639     if (len < b+2)
640         return -1;
641
642     if (!result)                       /* just return length */
643         return b + 2;
644
645     *result = bignum_from_bytes(p, b);
646
647     return p + b - data;
648 }
649
650 /*
651  * Return the bit count of a bignum, for SSH-1 encoding.
652  */
653 int bignum_bitcount(Bignum bn)
654 {
655     int bitcount = bn[0] * BIGNUM_INT_BITS - 1;
656     while (bitcount >= 0
657            && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;
658     return bitcount + 1;
659 }
660
661 /*
662  * Return the byte length of a bignum when SSH-1 encoded.
663  */
664 int ssh1_bignum_length(Bignum bn)
665 {
666     return 2 + (bignum_bitcount(bn) + 7) / 8;
667 }
668
669 /*
670  * Return the byte length of a bignum when SSH-2 encoded.
671  */
672 int ssh2_bignum_length(Bignum bn)
673 {
674     return 4 + (bignum_bitcount(bn) + 8) / 8;
675 }
676
677 /*
678  * Return a byte from a bignum; 0 is least significant, etc.
679  */
680 int bignum_byte(Bignum bn, int i)
681 {
682     if (i >= (int)(BIGNUM_INT_BYTES * bn[0]))
683         return 0;                      /* beyond the end */
684     else
685         return (bn[i / BIGNUM_INT_BYTES + 1] >>
686                 ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;
687 }
688
689 /*
690  * Return a bit from a bignum; 0 is least significant, etc.
691  */
692 int bignum_bit(Bignum bn, int i)
693 {
694     if (i >= (int)(BIGNUM_INT_BITS * bn[0]))
695         return 0;                      /* beyond the end */
696     else
697         return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;
698 }
699
700 /*
701  * Set a bit in a bignum; 0 is least significant, etc.
702  */
703 void bignum_set_bit(Bignum bn, int bitnum, int value)
704 {
705     if (bitnum >= (int)(BIGNUM_INT_BITS * bn[0]))
706         abort();                       /* beyond the end */
707     else {
708         int v = bitnum / BIGNUM_INT_BITS + 1;
709         int mask = 1 << (bitnum % BIGNUM_INT_BITS);
710         if (value)
711             bn[v] |= mask;
712         else
713             bn[v] &= ~mask;
714     }
715 }
716
717 /*
718  * Write a SSH-1-format bignum into a buffer. It is assumed the
719  * buffer is big enough. Returns the number of bytes used.
720  */
721 int ssh1_write_bignum(void *data, Bignum bn)
722 {
723     unsigned char *p = data;
724     int len = ssh1_bignum_length(bn);
725     int i;
726     int bitc = bignum_bitcount(bn);
727
728     *p++ = (bitc >> 8) & 0xFF;
729     *p++ = (bitc) & 0xFF;
730     for (i = len - 2; i--;)
731         *p++ = bignum_byte(bn, i);
732     return len;
733 }
734
735 /*
736  * Compare two bignums. Returns like strcmp.
737  */
738 int bignum_cmp(Bignum a, Bignum b)
739 {
740     int amax = a[0], bmax = b[0];
741     int i = (amax > bmax ? amax : bmax);
742     while (i) {
743         BignumInt aval = (i > amax ? 0 : a[i]);
744         BignumInt bval = (i > bmax ? 0 : b[i]);
745         if (aval < bval)
746             return -1;
747         if (aval > bval)
748             return +1;
749         i--;
750     }
751     return 0;
752 }
753
754 /*
755  * Right-shift one bignum to form another.
756  */
757 Bignum bignum_rshift(Bignum a, int shift)
758 {
759     Bignum ret;
760     int i, shiftw, shiftb, shiftbb, bits;
761     BignumInt ai, ai1;
762
763     bits = bignum_bitcount(a) - shift;
764     ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
765
766     if (ret) {
767         shiftw = shift / BIGNUM_INT_BITS;
768         shiftb = shift % BIGNUM_INT_BITS;
769         shiftbb = BIGNUM_INT_BITS - shiftb;
770
771         ai1 = a[shiftw + 1];
772         for (i = 1; i <= (int)ret[0]; i++) {
773             ai = ai1;
774             ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);
775             ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;
776         }
777     }
778
779     return ret;
780 }
781
782 /*
783  * Non-modular multiplication and addition.
784  */
785 Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
786 {
787     int alen = a[0], blen = b[0];
788     int mlen = (alen > blen ? alen : blen);
789     int rlen, i, maxspot;
790     BignumInt *workspace;
791     Bignum ret;
792
793     /* mlen space for a, mlen space for b, 2*mlen for result */
794     workspace = snewn(mlen * 4, BignumInt);
795     for (i = 0; i < mlen; i++) {
796         workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);
797         workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);
798     }
799
800     internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
801                  workspace + 2 * mlen, mlen);
802
803     /* now just copy the result back */
804     rlen = alen + blen + 1;
805     if (addend && rlen <= (int)addend[0])
806         rlen = addend[0] + 1;
807     ret = newbn(rlen);
808     maxspot = 0;
809     for (i = 1; i <= (int)ret[0]; i++) {
810         ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
811         if (ret[i] != 0)
812             maxspot = i;
813     }
814     ret[0] = maxspot;
815
816     /* now add in the addend, if any */
817     if (addend) {
818         BignumDblInt carry = 0;
819         for (i = 1; i <= rlen; i++) {
820             carry += (i <= (int)ret[0] ? ret[i] : 0);
821             carry += (i <= (int)addend[0] ? addend[i] : 0);
822             ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
823             carry >>= BIGNUM_INT_BITS;
824             if (ret[i] != 0 && i > maxspot)
825                 maxspot = i;
826         }
827     }
828     ret[0] = maxspot;
829
830     sfree(workspace);
831     return ret;
832 }
833
834 /*
835  * Non-modular multiplication.
836  */
837 Bignum bigmul(Bignum a, Bignum b)
838 {
839     return bigmuladd(a, b, NULL);
840 }
841
842 /*
843  * Create a bignum which is the bitmask covering another one. That
844  * is, the smallest integer which is >= N and is also one less than
845  * a power of two.
846  */
847 Bignum bignum_bitmask(Bignum n)
848 {
849     Bignum ret = copybn(n);
850     int i;
851     BignumInt j;
852
853     i = ret[0];
854     while (n[i] == 0 && i > 0)
855         i--;
856     if (i <= 0)
857         return ret;                    /* input was zero */
858     j = 1;
859     while (j < n[i])
860         j = 2 * j + 1;
861     ret[i] = j;
862     while (--i > 0)
863         ret[i] = BIGNUM_INT_MASK;
864     return ret;
865 }
866
867 /*
868  * Convert a (max 32-bit) long into a bignum.
869  */
870 Bignum bignum_from_long(unsigned long nn)
871 {
872     Bignum ret;
873     BignumDblInt n = nn;
874
875     ret = newbn(3);
876     ret[1] = (BignumInt)(n & BIGNUM_INT_MASK);
877     ret[2] = (BignumInt)((n >> BIGNUM_INT_BITS) & BIGNUM_INT_MASK);
878     ret[3] = 0;
879     ret[0] = (ret[2]  ? 2 : 1);
880     return ret;
881 }
882
883 /*
884  * Add a long to a bignum.
885  */
886 Bignum bignum_add_long(Bignum number, unsigned long addendx)
887 {
888     Bignum ret = newbn(number[0] + 1);
889     int i, maxspot = 0;
890     BignumDblInt carry = 0, addend = addendx;
891
892     for (i = 1; i <= (int)ret[0]; i++) {
893         carry += addend & BIGNUM_INT_MASK;
894         carry += (i <= (int)number[0] ? number[i] : 0);
895         addend >>= BIGNUM_INT_BITS;
896         ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
897         carry >>= BIGNUM_INT_BITS;
898         if (ret[i] != 0)
899             maxspot = i;
900     }
901     ret[0] = maxspot;
902     return ret;
903 }
904
905 /*
906  * Compute the residue of a bignum, modulo a (max 16-bit) short.
907  */
908 unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
909 {
910     BignumDblInt mod, r;
911     int i;
912
913     r = 0;
914     mod = modulus;
915     for (i = number[0]; i > 0; i--)
916         r = (r * (BIGNUM_TOP_BIT % mod) * 2 + number[i] % mod) % mod;
917     return (unsigned short) r;
918 }
919
920 #ifdef DEBUG
921 void diagbn(char *prefix, Bignum md)
922 {
923     int i, nibbles, morenibbles;
924     static const char hex[] = "0123456789ABCDEF";
925
926     debug(("%s0x", prefix ? prefix : ""));
927
928     nibbles = (3 + bignum_bitcount(md)) / 4;
929     if (nibbles < 1)
930         nibbles = 1;
931     morenibbles = 4 * md[0] - nibbles;
932     for (i = 0; i < morenibbles; i++)
933         debug(("-"));
934     for (i = nibbles; i--;)
935         debug(("%c",
936                hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
937
938     if (prefix)
939         debug(("\n"));
940 }
941 #endif
942
943 /*
944  * Simple division.
945  */
946 Bignum bigdiv(Bignum a, Bignum b)
947 {
948     Bignum q = newbn(a[0]);
949     bigdivmod(a, b, NULL, q);
950     return q;
951 }
952
953 /*
954  * Simple remainder.
955  */
956 Bignum bigmod(Bignum a, Bignum b)
957 {
958     Bignum r = newbn(b[0]);
959     bigdivmod(a, b, r, NULL);
960     return r;
961 }
962
963 /*
964  * Greatest common divisor.
965  */
966 Bignum biggcd(Bignum av, Bignum bv)
967 {
968     Bignum a = copybn(av);
969     Bignum b = copybn(bv);
970
971     while (bignum_cmp(b, Zero) != 0) {
972         Bignum t = newbn(b[0]);
973         bigdivmod(a, b, t, NULL);
974         while (t[0] > 1 && t[t[0]] == 0)
975             t[0]--;
976         freebn(a);
977         a = b;
978         b = t;
979     }
980
981     freebn(b);
982     return a;
983 }
984
985 /*
986  * Modular inverse, using Euclid's extended algorithm.
987  */
988 Bignum modinv(Bignum number, Bignum modulus)
989 {
990     Bignum a = copybn(modulus);
991     Bignum b = copybn(number);
992     Bignum xp = copybn(Zero);
993     Bignum x = copybn(One);
994     int sign = +1;
995
996     while (bignum_cmp(b, One) != 0) {
997         Bignum t = newbn(b[0]);
998         Bignum q = newbn(a[0]);
999         bigdivmod(a, b, t, q);
1000         while (t[0] > 1 && t[t[0]] == 0)
1001             t[0]--;
1002         freebn(a);
1003         a = b;
1004         b = t;
1005         t = xp;
1006         xp = x;
1007         x = bigmuladd(q, xp, t);
1008         sign = -sign;
1009         freebn(t);
1010         freebn(q);
1011     }
1012
1013     freebn(b);
1014     freebn(a);
1015     freebn(xp);
1016
1017     /* now we know that sign * x == 1, and that x < modulus */
1018     if (sign < 0) {
1019         /* set a new x to be modulus - x */
1020         Bignum newx = newbn(modulus[0]);
1021         BignumInt carry = 0;
1022         int maxspot = 1;
1023         int i;
1024
1025         for (i = 1; i <= (int)newx[0]; i++) {
1026             BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);
1027             BignumInt bword = (i <= (int)x[0] ? x[i] : 0);
1028             newx[i] = aword - bword - carry;
1029             bword = ~bword;
1030             carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
1031             if (newx[i] != 0)
1032                 maxspot = i;
1033         }
1034         newx[0] = maxspot;
1035         freebn(x);
1036         x = newx;
1037     }
1038
1039     /* and return. */
1040     return x;
1041 }
1042
1043 /*
1044  * Render a bignum into decimal. Return a malloced string holding
1045  * the decimal representation.
1046  */
1047 char *bignum_decimal(Bignum x)
1048 {
1049     int ndigits, ndigit;
1050     int i, iszero;
1051     BignumDblInt carry;
1052     char *ret;
1053     BignumInt *workspace;
1054
1055     /*
1056      * First, estimate the number of digits. Since log(10)/log(2)
1057      * is just greater than 93/28 (the joys of continued fraction
1058      * approximations...) we know that for every 93 bits, we need
1059      * at most 28 digits. This will tell us how much to malloc.
1060      *
1061      * Formally: if x has i bits, that means x is strictly less
1062      * than 2^i. Since 2 is less than 10^(28/93), this is less than
1063      * 10^(28i/93). We need an integer power of ten, so we must
1064      * round up (rounding down might make it less than x again).
1065      * Therefore if we multiply the bit count by 28/93, rounding
1066      * up, we will have enough digits.
1067      *
1068      * i=0 (i.e., x=0) is an irritating special case.
1069      */
1070     i = bignum_bitcount(x);
1071     if (!i)
1072         ndigits = 1;                   /* x = 0 */
1073     else
1074         ndigits = (28 * i + 92) / 93;  /* multiply by 28/93 and round up */
1075     ndigits++;                         /* allow for trailing \0 */
1076     ret = snewn(ndigits, char);
1077
1078     /*
1079      * Now allocate some workspace to hold the binary form as we
1080      * repeatedly divide it by ten. Initialise this to the
1081      * big-endian form of the number.
1082      */
1083     workspace = snewn(x[0], BignumInt);
1084     for (i = 0; i < (int)x[0]; i++)
1085         workspace[i] = x[x[0] - i];
1086
1087     /*
1088      * Next, write the decimal number starting with the last digit.
1089      * We use ordinary short division, dividing 10 into the
1090      * workspace.
1091      */
1092     ndigit = ndigits - 1;
1093     ret[ndigit] = '\0';
1094     do {
1095         iszero = 1;
1096         carry = 0;
1097         for (i = 0; i < (int)x[0]; i++) {
1098             carry = (carry << BIGNUM_INT_BITS) + workspace[i];
1099             workspace[i] = (BignumInt) (carry / 10);
1100             if (workspace[i])
1101                 iszero = 0;
1102             carry %= 10;
1103         }
1104         ret[--ndigit] = (char) (carry + '0');
1105     } while (!iszero);
1106
1107     /*
1108      * There's a chance we've fallen short of the start of the
1109      * string. Correct if so.
1110      */
1111     if (ndigit > 0)
1112         memmove(ret, ret + ndigit, ndigits - ndigit);
1113
1114     /*
1115      * Done.
1116      */
1117     sfree(workspace);
1118     return ret;
1119 }