]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - sshbn.c
Remove the last lingering knowledge, outside sshbn.c, of the
[PuTTY.git] / sshbn.c
1 /*
2  * Bignum routines for RSA and DH and stuff.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8
9 #define BIGNUM_INTERNAL
10 typedef unsigned short *Bignum;
11
12 #include "ssh.h"
13
14 unsigned short bnZero[1] = { 0 };
15 unsigned short bnOne[2] = { 1, 1 };
16
17 /*
18  * The Bignum format is an array of `unsigned short'. The first
19  * element of the array counts the remaining elements. The
20  * remaining elements express the actual number, base 2^16, _least_
21  * significant digit first. (So it's trivial to extract the bit
22  * with value 2^n for any n.)
23  *
24  * All Bignums in this module are positive. Negative numbers must
25  * be dealt with outside it.
26  *
27  * INVARIANT: the most significant word of any Bignum must be
28  * nonzero.
29  */
30
31 Bignum Zero = bnZero, One = bnOne;
32
33 static Bignum newbn(int length) {
34     Bignum b = smalloc((length+1)*sizeof(unsigned short));
35     if (!b)
36         abort();                       /* FIXME */
37     memset(b, 0, (length+1)*sizeof(*b));
38     b[0] = length;
39     return b;
40 }
41
42 void bn_restore_invariant(Bignum b) {
43     while (b[0] > 1 && b[b[0]] == 0) b[0]--;
44 }
45
46 Bignum copybn(Bignum orig) {
47     Bignum b = smalloc((orig[0]+1)*sizeof(unsigned short));
48     if (!b)
49         abort();                       /* FIXME */
50     memcpy(b, orig, (orig[0]+1)*sizeof(*b));
51     return b;
52 }
53
54 void freebn(Bignum b) {
55     /*
56      * Burn the evidence, just in case.
57      */
58     memset(b, 0, sizeof(b[0]) * (b[0] + 1));
59     sfree(b);
60 }
61
62 Bignum bn_power_2(int n) {
63     Bignum ret = newbn((n+15)/16);
64     bignum_set_bit(ret, n, 1);
65     return ret;
66 }
67
68 /*
69  * Compute c = a * b.
70  * Input is in the first len words of a and b.
71  * Result is returned in the first 2*len words of c.
72  */
73 static void internal_mul(unsigned short *a, unsigned short *b,
74                          unsigned short *c, int len)
75 {
76     int i, j;
77     unsigned long ai, t;
78
79     for (j = 0; j < 2*len; j++)
80         c[j] = 0;
81
82     for (i = len - 1; i >= 0; i--) {
83         ai = a[i];
84         t = 0;
85         for (j = len - 1; j >= 0; j--) {
86             t += ai * (unsigned long) b[j];
87             t += (unsigned long) c[i+j+1];
88             c[i+j+1] = (unsigned short)t;
89             t = t >> 16;
90         }
91         c[i] = (unsigned short)t;
92     }
93 }
94
95 static void internal_add_shifted(unsigned short *number,
96                                 unsigned n, int shift) {
97     int word = 1 + (shift / 16);
98     int bshift = shift % 16;
99     unsigned long addend;
100
101     addend = n << bshift;
102
103     while (addend) {
104         addend += number[word];
105         number[word] = (unsigned short) addend & 0xFFFF;
106         addend >>= 16;
107         word++;
108     }
109 }
110
111 /*
112  * Compute a = a % m.
113  * Input in first alen words of a and first mlen words of m.
114  * Output in first alen words of a
115  * (of which first alen-mlen words will be zero).
116  * The MSW of m MUST have its high bit set.
117  * Quotient is accumulated in the `quotient' array, which is a Bignum
118  * rather than the internal bigendian format. Quotient parts are shifted
119  * left by `qshift' before adding into quot.
120  */
121 static void internal_mod(unsigned short *a, int alen,
122                          unsigned short *m, int mlen,
123                          unsigned short *quot, int qshift)
124 {
125     unsigned short m0, m1;
126     unsigned int h;
127     int i, k;
128
129     m0 = m[0];
130     if (mlen > 1)
131         m1 = m[1];
132     else
133         m1 = 0;
134
135     for (i = 0; i <= alen-mlen; i++) {
136         unsigned long t;
137         unsigned int q, r, c, ai1;
138
139         if (i == 0) {
140             h = 0;
141         } else {
142             h = a[i-1];
143             a[i-1] = 0;
144         }
145
146         if (i == alen-1)
147             ai1 = 0;
148         else
149             ai1 = a[i+1];
150
151         /* Find q = h:a[i] / m0 */
152         t = ((unsigned long) h << 16) + a[i];
153         q = t / m0;
154         r = t % m0;
155
156         /* Refine our estimate of q by looking at
157          h:a[i]:a[i+1] / m0:m1 */
158         t = (long) m1 * (long) q;
159         if (t > ((unsigned long) r << 16) + ai1) {
160             q--;
161             t -= m1;
162             r = (r + m0) & 0xffff; /* overflow? */
163             if (r >= (unsigned long)m0 &&
164                 t > ((unsigned long) r << 16) + ai1)
165                 q--;
166         }
167
168         /* Subtract q * m from a[i...] */
169         c = 0;
170         for (k = mlen - 1; k >= 0; k--) {
171             t = (long) q * (long) m[k];
172             t += c;
173             c = t >> 16;
174             if ((unsigned short) t > a[i+k]) c++;
175             a[i+k] -= (unsigned short) t;
176         }
177
178         /* Add back m in case of borrow */
179         if (c != h) {
180             t = 0;
181             for (k = mlen - 1; k >= 0; k--) {
182                 t += m[k];
183                 t += a[i+k];
184                 a[i+k] = (unsigned short)t;
185                 t = t >> 16;
186             }
187             q--;
188         }
189         if (quot)
190             internal_add_shifted(quot, q, qshift + 16 * (alen-mlen-i));
191     }
192 }
193
194 /*
195  * Compute (base ^ exp) % mod.
196  * The base MUST be smaller than the modulus.
197  * The most significant word of mod MUST be non-zero.
198  * We assume that the result array is the same size as the mod array.
199  */
200 Bignum modpow(Bignum base, Bignum exp, Bignum mod)
201 {
202     unsigned short *a, *b, *n, *m;
203     int mshift;
204     int mlen, i, j;
205     Bignum result;
206
207     /* Allocate m of size mlen, copy mod to m */
208     /* We use big endian internally */
209     mlen = mod[0];
210     m = smalloc(mlen * sizeof(unsigned short));
211     for (j = 0; j < mlen; j++) m[j] = mod[mod[0] - j];
212
213     /* Shift m left to make msb bit set */
214     for (mshift = 0; mshift < 15; mshift++)
215         if ((m[0] << mshift) & 0x8000) break;
216     if (mshift) {
217         for (i = 0; i < mlen - 1; i++)
218             m[i] = (m[i] << mshift) | (m[i+1] >> (16-mshift));
219         m[mlen-1] = m[mlen-1] << mshift;
220     }
221
222     /* Allocate n of size mlen, copy base to n */
223     n = smalloc(mlen * sizeof(unsigned short));
224     i = mlen - base[0];
225     for (j = 0; j < i; j++) n[j] = 0;
226     for (j = 0; j < base[0]; j++) n[i+j] = base[base[0] - j];
227
228     /* Allocate a and b of size 2*mlen. Set a = 1 */
229     a = smalloc(2 * mlen * sizeof(unsigned short));
230     b = smalloc(2 * mlen * sizeof(unsigned short));
231     for (i = 0; i < 2*mlen; i++) a[i] = 0;
232     a[2*mlen-1] = 1;
233
234     /* Skip leading zero bits of exp. */
235     i = 0; j = 15;
236     while (i < exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
237         j--;
238         if (j < 0) { i++; j = 15; }
239     }
240
241     /* Main computation */
242     while (i < exp[0]) {
243         while (j >= 0) {
244             internal_mul(a + mlen, a + mlen, b, mlen);
245             internal_mod(b, mlen*2, m, mlen, NULL, 0);
246             if ((exp[exp[0] - i] & (1 << j)) != 0) {
247                 internal_mul(b + mlen, n, a, mlen);
248                 internal_mod(a, mlen*2, m, mlen, NULL, 0);
249             } else {
250                 unsigned short *t;
251                 t = a;  a = b;  b = t;
252             }
253             j--;
254         }
255         i++; j = 15;
256     }
257
258     /* Fixup result in case the modulus was shifted */
259     if (mshift) {
260         for (i = mlen - 1; i < 2*mlen - 1; i++)
261             a[i] = (a[i] << mshift) | (a[i+1] >> (16-mshift));
262         a[2*mlen-1] = a[2*mlen-1] << mshift;
263         internal_mod(a, mlen*2, m, mlen, NULL, 0);
264         for (i = 2*mlen - 1; i >= mlen; i--)
265             a[i] = (a[i] >> mshift) | (a[i-1] << (16-mshift));
266     }
267
268     /* Copy result to buffer */
269     result = newbn(mod[0]);
270     for (i = 0; i < mlen; i++)
271         result[result[0] - i] = a[i+mlen];
272     while (result[0] > 1 && result[result[0]] == 0) result[0]--;
273
274     /* Free temporary arrays */
275     for (i = 0; i < 2*mlen; i++) a[i] = 0; sfree(a);
276     for (i = 0; i < 2*mlen; i++) b[i] = 0; sfree(b);
277     for (i = 0; i < mlen; i++) m[i] = 0; sfree(m);
278     for (i = 0; i < mlen; i++) n[i] = 0; sfree(n);
279
280     return result;
281 }
282
283 /*
284  * Compute (p * q) % mod.
285  * The most significant word of mod MUST be non-zero.
286  * We assume that the result array is the same size as the mod array.
287  */
288 Bignum modmul(Bignum p, Bignum q, Bignum mod)
289 {
290     unsigned short *a, *n, *m, *o;
291     int mshift;
292     int pqlen, mlen, i, j;
293     Bignum result;
294
295     /* Allocate m of size mlen, copy mod to m */
296     /* We use big endian internally */
297     mlen = mod[0];
298     m = smalloc(mlen * sizeof(unsigned short));
299     for (j = 0; j < mlen; j++) m[j] = mod[mod[0] - j];
300
301     /* Shift m left to make msb bit set */
302     for (mshift = 0; mshift < 15; mshift++)
303         if ((m[0] << mshift) & 0x8000) break;
304     if (mshift) {
305         for (i = 0; i < mlen - 1; i++)
306             m[i] = (m[i] << mshift) | (m[i+1] >> (16-mshift));
307         m[mlen-1] = m[mlen-1] << mshift;
308     }
309
310     pqlen = (p[0] > q[0] ? p[0] : q[0]);
311
312     /* Allocate n of size pqlen, copy p to n */
313     n = smalloc(pqlen * sizeof(unsigned short));
314     i = pqlen - p[0];
315     for (j = 0; j < i; j++) n[j] = 0;
316     for (j = 0; j < p[0]; j++) n[i+j] = p[p[0] - j];
317
318     /* Allocate o of size pqlen, copy q to o */
319     o = smalloc(pqlen * sizeof(unsigned short));
320     i = pqlen - q[0];
321     for (j = 0; j < i; j++) o[j] = 0;
322     for (j = 0; j < q[0]; j++) o[i+j] = q[q[0] - j];
323
324     /* Allocate a of size 2*pqlen for result */
325     a = smalloc(2 * pqlen * sizeof(unsigned short));
326
327     /* Main computation */
328     internal_mul(n, o, a, pqlen);
329     internal_mod(a, pqlen*2, m, mlen, NULL, 0);
330
331     /* Fixup result in case the modulus was shifted */
332     if (mshift) {
333         for (i = 2*pqlen - mlen - 1; i < 2*pqlen - 1; i++)
334             a[i] = (a[i] << mshift) | (a[i+1] >> (16-mshift));
335         a[2*pqlen-1] = a[2*pqlen-1] << mshift;
336         internal_mod(a, pqlen*2, m, mlen, NULL, 0);
337         for (i = 2*pqlen - 1; i >= 2*pqlen - mlen; i--)
338             a[i] = (a[i] >> mshift) | (a[i-1] << (16-mshift));
339     }
340
341     /* Copy result to buffer */
342     result = newbn(mod[0]);
343     for (i = 0; i < mlen; i++)
344         result[result[0] - i] = a[i+2*pqlen-mlen];
345     while (result[0] > 1 && result[result[0]] == 0) result[0]--;
346
347     /* Free temporary arrays */
348     for (i = 0; i < 2*pqlen; i++) a[i] = 0; sfree(a);
349     for (i = 0; i < mlen; i++) m[i] = 0; sfree(m);
350     for (i = 0; i < pqlen; i++) n[i] = 0; sfree(n);
351     for (i = 0; i < pqlen; i++) o[i] = 0; sfree(o);
352
353     return result;
354 }
355
356 /*
357  * Compute p % mod.
358  * The most significant word of mod MUST be non-zero.
359  * We assume that the result array is the same size as the mod array.
360  * We optionally write out a quotient.
361  */
362 void bigmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
363 {
364     unsigned short *n, *m;
365     int mshift;
366     int plen, mlen, i, j;
367
368     /* Allocate m of size mlen, copy mod to m */
369     /* We use big endian internally */
370     mlen = mod[0];
371     m = smalloc(mlen * sizeof(unsigned short));
372     for (j = 0; j < mlen; j++) m[j] = mod[mod[0] - j];
373
374     /* Shift m left to make msb bit set */
375     for (mshift = 0; mshift < 15; mshift++)
376         if ((m[0] << mshift) & 0x8000) break;
377     if (mshift) {
378         for (i = 0; i < mlen - 1; i++)
379             m[i] = (m[i] << mshift) | (m[i+1] >> (16-mshift));
380         m[mlen-1] = m[mlen-1] << mshift;
381     }
382
383     plen = p[0];
384     /* Ensure plen > mlen */
385     if (plen <= mlen) plen = mlen+1;
386
387     /* Allocate n of size plen, copy p to n */
388     n = smalloc(plen * sizeof(unsigned short));
389     for (j = 0; j < plen; j++) n[j] = 0;
390     for (j = 1; j <= p[0]; j++) n[plen-j] = p[j];
391
392     /* Main computation */
393     internal_mod(n, plen, m, mlen, quotient, mshift);
394
395     /* Fixup result in case the modulus was shifted */
396     if (mshift) {
397         for (i = plen - mlen - 1; i < plen - 1; i++)
398             n[i] = (n[i] << mshift) | (n[i+1] >> (16-mshift));
399         n[plen-1] = n[plen-1] << mshift;
400         internal_mod(n, plen, m, mlen, quotient, 0);
401         for (i = plen - 1; i >= plen - mlen; i--)
402             n[i] = (n[i] >> mshift) | (n[i-1] << (16-mshift));
403     }
404
405     /* Copy result to buffer */
406     for (i = 1; i <= result[0]; i++) {
407         int j = plen-i;
408         result[i] = j>=0 ? n[j] : 0;
409     }
410
411     /* Free temporary arrays */
412     for (i = 0; i < mlen; i++) m[i] = 0; sfree(m);
413     for (i = 0; i < plen; i++) n[i] = 0; sfree(n);
414 }
415
416 /*
417  * Decrement a number.
418  */
419 void decbn(Bignum bn) {
420     int i = 1;
421     while (i < bn[0] && bn[i] == 0)
422         bn[i++] = 0xFFFF;
423     bn[i]--;
424 }
425
426 Bignum bignum_from_bytes(unsigned char *data, int nbytes) {
427     Bignum result;
428     int w, i;
429
430     w = (nbytes+1)/2;                  /* bytes -> words */
431
432     result = newbn(w);
433     for (i=1; i<=w; i++)
434         result[i] = 0;
435     for (i=nbytes; i-- ;) {
436         unsigned char byte = *data++;
437         if (i & 1)
438             result[1+i/2] |= byte<<8;
439         else
440             result[1+i/2] |= byte;
441     }
442
443     while (result[0] > 1 && result[result[0]] == 0) result[0]--;
444     return result;
445 }
446
447 /*
448  * Read an ssh1-format bignum from a data buffer. Return the number
449  * of bytes consumed.
450  */
451 int ssh1_read_bignum(unsigned char *data, Bignum *result) {
452     unsigned char *p = data;
453     int i;
454     int w, b;
455
456     w = 0;
457     for (i=0; i<2; i++)
458         w = (w << 8) + *p++;
459     b = (w+7)/8;                       /* bits -> bytes */
460
461     if (!result)                       /* just return length */
462         return b + 2;
463
464     *result = bignum_from_bytes(p, b);
465
466     return p + b - data;
467 }
468
469 /*
470  * Return the bit count of a bignum, for ssh1 encoding.
471  */
472 int ssh1_bignum_bitcount(Bignum bn) {
473     int bitcount = bn[0] * 16 - 1;
474     while (bitcount >= 0 && (bn[bitcount/16+1] >> (bitcount % 16)) == 0)
475         bitcount--;
476     return bitcount + 1;
477 }
478
479 /*
480  * Return the byte length of a bignum when ssh1 encoded.
481  */
482 int ssh1_bignum_length(Bignum bn) {
483     return 2 + (ssh1_bignum_bitcount(bn)+7)/8;
484 }
485
486 /*
487  * Return a byte from a bignum; 0 is least significant, etc.
488  */
489 int bignum_byte(Bignum bn, int i) {
490     if (i >= 2*bn[0])
491         return 0;                      /* beyond the end */
492     else if (i & 1)
493         return (bn[i/2+1] >> 8) & 0xFF;
494     else
495         return (bn[i/2+1]     ) & 0xFF;
496 }
497
498 /*
499  * Return a bit from a bignum; 0 is least significant, etc.
500  */
501 int bignum_bit(Bignum bn, int i) {
502     if (i >= 16*bn[0])
503         return 0;                      /* beyond the end */
504     else
505         return (bn[i/16+1] >> (i%16)) & 1;
506 }
507
508 /*
509  * Set a bit in a bignum; 0 is least significant, etc.
510  */
511 void bignum_set_bit(Bignum bn, int bitnum, int value) {
512     if (bitnum >= 16*bn[0])
513         abort();                       /* beyond the end */
514     else {
515         int v = bitnum/16+1;
516         int mask = 1 << (bitnum%16);
517         if (value)
518             bn[v] |= mask;
519         else
520             bn[v] &= ~mask;
521     }
522 }
523
524 /*
525  * Write a ssh1-format bignum into a buffer. It is assumed the
526  * buffer is big enough. Returns the number of bytes used.
527  */
528 int ssh1_write_bignum(void *data, Bignum bn) {
529     unsigned char *p = data;
530     int len = ssh1_bignum_length(bn);
531     int i;
532     int bitc = ssh1_bignum_bitcount(bn);
533
534     *p++ = (bitc >> 8) & 0xFF;
535     *p++ = (bitc     ) & 0xFF;
536     for (i = len-2; i-- ;)
537         *p++ = bignum_byte(bn, i);
538     return len;
539 }
540
541 /*
542  * Compare two bignums. Returns like strcmp.
543  */
544 int bignum_cmp(Bignum a, Bignum b) {
545     int amax = a[0], bmax = b[0];
546     int i = (amax > bmax ? amax : bmax);
547     while (i) {
548         unsigned short aval = (i > amax ? 0 : a[i]);
549         unsigned short bval = (i > bmax ? 0 : b[i]);
550         if (aval < bval) return -1;
551         if (aval > bval) return +1;
552         i--;
553     }
554     return 0;
555 }
556
557 /*
558  * Right-shift one bignum to form another.
559  */
560 Bignum bignum_rshift(Bignum a, int shift) {
561     Bignum ret;
562     int i, shiftw, shiftb, shiftbb, bits;
563     unsigned short ai, ai1;
564
565     bits = ssh1_bignum_bitcount(a) - shift;
566     ret = newbn((bits+15)/16);
567
568     if (ret) {
569         shiftw = shift / 16;
570         shiftb = shift % 16;
571         shiftbb = 16 - shiftb;
572
573         ai1 = a[shiftw+1];
574         for (i = 1; i <= ret[0]; i++) {
575             ai = ai1;
576             ai1 = (i+shiftw+1 <= a[0] ? a[i+shiftw+1] : 0);
577             ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & 0xFFFF;
578         }
579     }
580
581     return ret;
582 }
583
584 /*
585  * Non-modular multiplication and addition.
586  */
587 Bignum bigmuladd(Bignum a, Bignum b, Bignum addend) {
588     int alen = a[0], blen = b[0];
589     int mlen = (alen > blen ? alen : blen);
590     int rlen, i, maxspot;
591     unsigned short *workspace;
592     Bignum ret;
593
594     /* mlen space for a, mlen space for b, 2*mlen for result */
595     workspace = smalloc(mlen * 4 * sizeof(unsigned short));
596     for (i = 0; i < mlen; i++) {
597         workspace[0*mlen + i] = (mlen-i <= a[0] ? a[mlen-i] : 0);
598         workspace[1*mlen + i] = (mlen-i <= b[0] ? b[mlen-i] : 0);
599     }
600
601     internal_mul(workspace+0*mlen, workspace+1*mlen, workspace+2*mlen, mlen);
602
603     /* now just copy the result back */
604     rlen = alen + blen + 1;
605     if (addend && rlen <= addend[0])
606         rlen = addend[0] + 1;
607     ret = newbn(rlen);
608     maxspot = 0;
609     for (i = 1; i <= ret[0]; i++) {
610         ret[i] = (i <= 2*mlen ? workspace[4*mlen - i] : 0);
611         if (ret[i] != 0)
612             maxspot = i;
613     }
614     ret[0] = maxspot;
615
616     /* now add in the addend, if any */
617     if (addend) {
618         unsigned long carry = 0;
619         for (i = 1; i <= rlen; i++) {
620             carry += (i <= ret[0] ? ret[i] : 0);
621             carry += (i <= addend[0] ? addend[i] : 0);
622             ret[i] = (unsigned short) carry & 0xFFFF;
623             carry >>= 16;
624             if (ret[i] != 0 && i > maxspot)
625                 maxspot = i;
626         }
627     }
628     ret[0] = maxspot;
629
630     return ret;
631 }
632
633 /*
634  * Non-modular multiplication.
635  */
636 Bignum bigmul(Bignum a, Bignum b) {
637     return bigmuladd(a, b, NULL);
638 }
639
640 /*
641  * Create a bignum which is the bitmask covering another one. That
642  * is, the smallest integer which is >= N and is also one less than
643  * a power of two.
644  */
645 Bignum bignum_bitmask(Bignum n) {
646     Bignum ret = copybn(n);
647     int i;
648     unsigned short j;
649
650     i = ret[0];
651     while (n[i] == 0 && i > 0)
652         i--;
653     if (i <= 0)
654         return ret;                    /* input was zero */
655     j = 1;
656     while (j < n[i])
657         j = 2*j+1;
658     ret[i] = j;
659     while (--i > 0)
660         ret[i] = 0xFFFF;
661     return ret;
662 }
663
664 /*
665  * Convert a (max 16-bit) short into a bignum.
666  */
667 Bignum bignum_from_short(unsigned short n) {
668     Bignum ret;
669
670     ret = newbn(2);
671     ret[1] = n & 0xFFFF;
672     ret[2] = (n >> 16) & 0xFFFF;
673     ret[0] = (ret[2] ? 2 : 1);
674     return ret;        
675 }
676
677 /*
678  * Add a long to a bignum.
679  */
680 Bignum bignum_add_long(Bignum number, unsigned long addend) {
681     Bignum ret = newbn(number[0]+1);
682     int i, maxspot = 0;
683     unsigned long carry = 0;
684
685     for (i = 1; i <= ret[0]; i++) {
686         carry += addend & 0xFFFF;
687         carry += (i <= number[0] ? number[i] : 0);
688         addend >>= 16;
689         ret[i] = (unsigned short) carry & 0xFFFF;
690         carry >>= 16;
691         if (ret[i] != 0)
692             maxspot = i;
693     }
694     ret[0] = maxspot;
695     return ret;
696 }
697
698 /*
699  * Compute the residue of a bignum, modulo a (max 16-bit) short.
700  */
701 unsigned short bignum_mod_short(Bignum number, unsigned short modulus) {
702     unsigned long mod, r;
703     int i;
704
705     r = 0;
706     mod = modulus;
707     for (i = number[0]; i > 0; i--)
708         r = (r * 65536 + number[i]) % mod;
709     return (unsigned short) r;
710 }
711
712 void diagbn(char *prefix, Bignum md) {
713     int i, nibbles, morenibbles;
714     static const char hex[] = "0123456789ABCDEF";
715
716     printf("%s0x", prefix ? prefix : "");
717
718     nibbles = (3 + ssh1_bignum_bitcount(md))/4; if (nibbles<1) nibbles=1;
719     morenibbles = 4*md[0] - nibbles;
720     for (i=0; i<morenibbles; i++) putchar('-');
721     for (i=nibbles; i-- ;)
722         putchar(hex[(bignum_byte(md, i/2) >> (4*(i%2))) & 0xF]);
723
724     if (prefix) putchar('\n');
725 }
726
727 /*
728  * Greatest common divisor.
729  */
730 Bignum biggcd(Bignum av, Bignum bv) {
731     Bignum a = copybn(av);
732     Bignum b = copybn(bv);
733
734     diagbn("a = ", a);
735     diagbn("b = ", b);
736     while (bignum_cmp(b, Zero) != 0) {
737         Bignum t = newbn(b[0]);
738         bigmod(a, b, t, NULL);
739         diagbn("t = ", t);
740         while (t[0] > 1 && t[t[0]] == 0) t[0]--;
741         freebn(a);
742         a = b;
743         b = t;
744     }
745
746     freebn(b);
747     return a;
748 }
749
750 /*
751  * Modular inverse, using Euclid's extended algorithm.
752  */
753 Bignum modinv(Bignum number, Bignum modulus) {
754     Bignum a = copybn(modulus);
755     Bignum b = copybn(number);
756     Bignum xp = copybn(Zero);
757     Bignum x = copybn(One);
758     int sign = +1;
759
760     while (bignum_cmp(b, One) != 0) {
761         Bignum t = newbn(b[0]);
762         Bignum q = newbn(a[0]);
763         bigmod(a, b, t, q);
764         while (t[0] > 1 && t[t[0]] == 0) t[0]--;
765         freebn(a);
766         a = b;
767         b = t;
768         t = xp;
769         xp = x;
770         x = bigmuladd(q, xp, t);
771         sign = -sign;
772         freebn(t);
773     }
774
775     freebn(b);
776     freebn(a);
777     freebn(xp);
778
779     /* now we know that sign * x == 1, and that x < modulus */
780     if (sign < 0) {
781         /* set a new x to be modulus - x */
782         Bignum newx = newbn(modulus[0]);
783         unsigned short carry = 0;
784         int maxspot = 1;
785         int i;
786
787         for (i = 1; i <= newx[0]; i++) {
788             unsigned short aword = (i <= modulus[0] ? modulus[i] : 0);
789             unsigned short bword = (i <= x[0] ? x[i] : 0);
790             newx[i] = aword - bword - carry;
791             bword = ~bword;
792             carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
793             if (newx[i] != 0)
794                 maxspot = i;
795         }
796         newx[0] = maxspot;
797         freebn(x);
798         x = newx;
799     }
800
801     /* and return. */
802     return x;
803 }
804
805 /*
806  * Render a bignum into decimal. Return a malloced string holding
807  * the decimal representation.
808  */
809 char *bignum_decimal(Bignum x) {
810     int ndigits, ndigit;
811     int i, iszero;
812     unsigned long carry;
813     char *ret;
814     unsigned short *workspace;
815
816     /*
817      * First, estimate the number of digits. Since log(10)/log(2)
818      * is just greater than 93/28 (the joys of continued fraction
819      * approximations...) we know that for every 93 bits, we need
820      * at most 28 digits. This will tell us how much to malloc.
821      *
822      * Formally: if x has i bits, that means x is strictly less
823      * than 2^i. Since 2 is less than 10^(28/93), this is less than
824      * 10^(28i/93). We need an integer power of ten, so we must
825      * round up (rounding down might make it less than x again).
826      * Therefore if we multiply the bit count by 28/93, rounding
827      * up, we will have enough digits.
828      */
829     i = ssh1_bignum_bitcount(x);
830     ndigits = (28*i + 92)/93;          /* multiply by 28/93 and round up */
831     ndigits++;                         /* allow for trailing \0 */
832     ret = smalloc(ndigits);
833
834     /*
835      * Now allocate some workspace to hold the binary form as we
836      * repeatedly divide it by ten. Initialise this to the
837      * big-endian form of the number.
838      */
839     workspace = smalloc(sizeof(unsigned short) * x[0]);
840     for (i = 0; i < x[0]; i++)
841         workspace[i] = x[x[0] - i];
842
843     /*
844      * Next, write the decimal number starting with the last digit.
845      * We use ordinary short division, dividing 10 into the
846      * workspace.
847      */
848     ndigit = ndigits-1;
849     ret[ndigit] = '\0';
850     do {
851         iszero = 1;
852         carry = 0;
853         for (i = 0; i < x[0]; i++) {
854             carry = (carry << 16) + workspace[i];
855             workspace[i] = (unsigned short) (carry / 10);
856             if (workspace[i])
857                 iszero = 0;
858             carry %= 10;
859         }
860         ret[--ndigit] = (char)(carry + '0');
861     } while (!iszero);
862
863     /*
864      * There's a chance we've fallen short of the start of the
865      * string. Correct if so.
866      */
867     if (ndigit > 0)
868         memmove(ret, ret+ndigit, ndigits-ndigit);
869
870     /*
871      * Done.
872      */
873     return ret;
874 }