2 * Bignum routines for RSA and DH and stuff.
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
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.
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) \
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 { \
55 typedef unsigned short BignumInt;
56 typedef unsigned long BignumDblInt;
57 #define BIGNUM_INT_MASK 0xFFFFU
58 #define BIGNUM_TOP_BIT 0x8000U
59 #define BIGNUM_INT_BITS 16
60 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
61 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
62 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
68 #define BIGNUM_INT_BYTES (BIGNUM_INT_BITS / 8)
70 #define BIGNUM_INTERNAL
71 typedef BignumInt *Bignum;
75 BignumInt bnZero[1] = { 0 };
76 BignumInt bnOne[2] = { 1, 1 };
79 * The Bignum format is an array of `BignumInt'. The first
80 * element of the array counts the remaining elements. The
81 * remaining elements express the actual number, base 2^BIGNUM_INT_BITS, _least_
82 * significant digit first. (So it's trivial to extract the bit
83 * with value 2^n for any n.)
85 * All Bignums in this module are positive. Negative numbers must
86 * be dealt with outside it.
88 * INVARIANT: the most significant word of any Bignum must be
92 Bignum Zero = bnZero, One = bnOne;
94 static Bignum newbn(int length)
96 Bignum b = snewn(length + 1, BignumInt);
99 memset(b, 0, (length + 1) * sizeof(*b));
104 void bn_restore_invariant(Bignum b)
106 while (b[0] > 1 && b[b[0]] == 0)
110 Bignum copybn(Bignum orig)
112 Bignum b = snewn(orig[0] + 1, BignumInt);
115 memcpy(b, orig, (orig[0] + 1) * sizeof(*b));
119 void freebn(Bignum b)
122 * Burn the evidence, just in case.
124 memset(b, 0, sizeof(b[0]) * (b[0] + 1));
128 Bignum bn_power_2(int n)
130 Bignum ret = newbn(n / BIGNUM_INT_BITS + 1);
131 bignum_set_bit(ret, n, 1);
137 * Input is in the first len words of a and b.
138 * Result is returned in the first 2*len words of c.
140 static void internal_mul(BignumInt *a, BignumInt *b,
141 BignumInt *c, int len)
146 for (j = 0; j < 2 * len; j++)
149 for (i = len - 1; i >= 0; i--) {
151 for (j = len - 1; j >= 0; j--) {
152 t += MUL_WORD(a[i], (BignumDblInt) b[j]);
153 t += (BignumDblInt) c[i + j + 1];
154 c[i + j + 1] = (BignumInt) t;
155 t = t >> BIGNUM_INT_BITS;
157 c[i] = (BignumInt) t;
161 static void internal_add_shifted(BignumInt *number,
162 unsigned n, int shift)
164 int word = 1 + (shift / BIGNUM_INT_BITS);
165 int bshift = shift % BIGNUM_INT_BITS;
168 addend = (BignumDblInt)n << bshift;
171 addend += number[word];
172 number[word] = (BignumInt) addend & BIGNUM_INT_MASK;
173 addend >>= BIGNUM_INT_BITS;
180 * Input in first alen words of a and first mlen words of m.
181 * Output in first alen words of a
182 * (of which first alen-mlen words will be zero).
183 * The MSW of m MUST have its high bit set.
184 * Quotient is accumulated in the `quotient' array, which is a Bignum
185 * rather than the internal bigendian format. Quotient parts are shifted
186 * left by `qshift' before adding into quot.
188 static void internal_mod(BignumInt *a, int alen,
189 BignumInt *m, int mlen,
190 BignumInt *quot, int qshift)
202 for (i = 0; i <= alen - mlen; i++) {
204 unsigned int q, r, c, ai1;
218 /* Find q = h:a[i] / m0 */
223 * To illustrate it, suppose a BignumInt is 8 bits, and
224 * we are dividing (say) A1:23:45:67 by A1:B2:C3. Then
225 * our initial division will be 0xA123 / 0xA1, which
226 * will give a quotient of 0x100 and a divide overflow.
227 * However, the invariants in this division algorithm
228 * are not violated, since the full number A1:23:... is
229 * _less_ than the quotient prefix A1:B2:... and so the
230 * following correction loop would have sorted it out.
232 * In this situation we set q to be the largest
233 * quotient we _can_ stomach (0xFF, of course).
237 /* Macro doesn't want an array subscript expression passed
238 * into it (see definition), so use a temporary. */
239 BignumInt tmplo = a[i];
240 DIVMOD_WORD(q, r, h, tmplo, m0);
242 /* Refine our estimate of q by looking at
243 h:a[i]:a[i+1] / m0:m1 */
245 if (t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) {
248 r = (r + m0) & BIGNUM_INT_MASK; /* overflow? */
249 if (r >= (BignumDblInt) m0 &&
250 t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) q--;
254 /* Subtract q * m from a[i...] */
256 for (k = mlen - 1; k >= 0; k--) {
257 t = MUL_WORD(q, m[k]);
259 c = (unsigned)(t >> BIGNUM_INT_BITS);
260 if ((BignumInt) t > a[i + k])
262 a[i + k] -= (BignumInt) t;
265 /* Add back m in case of borrow */
268 for (k = mlen - 1; k >= 0; k--) {
271 a[i + k] = (BignumInt) t;
272 t = t >> BIGNUM_INT_BITS;
277 internal_add_shifted(quot, q, qshift + BIGNUM_INT_BITS * (alen - mlen - i));
282 * Compute (base ^ exp) % mod.
284 Bignum modpow(Bignum base_in, Bignum exp, Bignum mod)
286 BignumInt *a, *b, *n, *m;
292 * The most significant word of mod needs to be non-zero. It
293 * should already be, but let's make sure.
295 assert(mod[mod[0]] != 0);
298 * Make sure the base is smaller than the modulus, by reducing
299 * it modulo the modulus if not.
301 base = bigmod(base_in, mod);
303 /* Allocate m of size mlen, copy mod to m */
304 /* We use big endian internally */
306 m = snewn(mlen, BignumInt);
307 for (j = 0; j < mlen; j++)
308 m[j] = mod[mod[0] - j];
310 /* Shift m left to make msb bit set */
311 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
312 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
315 for (i = 0; i < mlen - 1; i++)
316 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
317 m[mlen - 1] = m[mlen - 1] << mshift;
320 /* Allocate n of size mlen, copy base to n */
321 n = snewn(mlen, BignumInt);
323 for (j = 0; j < i; j++)
325 for (j = 0; j < (int)base[0]; j++)
326 n[i + j] = base[base[0] - j];
328 /* Allocate a and b of size 2*mlen. Set a = 1 */
329 a = snewn(2 * mlen, BignumInt);
330 b = snewn(2 * mlen, BignumInt);
331 for (i = 0; i < 2 * mlen; i++)
335 /* Skip leading zero bits of exp. */
337 j = BIGNUM_INT_BITS-1;
338 while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
342 j = BIGNUM_INT_BITS-1;
346 /* Main computation */
347 while (i < (int)exp[0]) {
349 internal_mul(a + mlen, a + mlen, b, mlen);
350 internal_mod(b, mlen * 2, m, mlen, NULL, 0);
351 if ((exp[exp[0] - i] & (1 << j)) != 0) {
352 internal_mul(b + mlen, n, a, mlen);
353 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
363 j = BIGNUM_INT_BITS-1;
366 /* Fixup result in case the modulus was shifted */
368 for (i = mlen - 1; i < 2 * mlen - 1; i++)
369 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
370 a[2 * mlen - 1] = a[2 * mlen - 1] << mshift;
371 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
372 for (i = 2 * mlen - 1; i >= mlen; i--)
373 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
376 /* Copy result to buffer */
377 result = newbn(mod[0]);
378 for (i = 0; i < mlen; i++)
379 result[result[0] - i] = a[i + mlen];
380 while (result[0] > 1 && result[result[0]] == 0)
383 /* Free temporary arrays */
384 for (i = 0; i < 2 * mlen; i++)
387 for (i = 0; i < 2 * mlen; i++)
390 for (i = 0; i < mlen; i++)
393 for (i = 0; i < mlen; i++)
403 * Compute (p * q) % mod.
404 * The most significant word of mod MUST be non-zero.
405 * We assume that the result array is the same size as the mod array.
407 Bignum modmul(Bignum p, Bignum q, Bignum mod)
409 BignumInt *a, *n, *m, *o;
411 int pqlen, mlen, rlen, i, j;
414 /* Allocate m of size mlen, copy mod to m */
415 /* We use big endian internally */
417 m = snewn(mlen, BignumInt);
418 for (j = 0; j < mlen; j++)
419 m[j] = mod[mod[0] - j];
421 /* Shift m left to make msb bit set */
422 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
423 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
426 for (i = 0; i < mlen - 1; i++)
427 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
428 m[mlen - 1] = m[mlen - 1] << mshift;
431 pqlen = (p[0] > q[0] ? p[0] : q[0]);
433 /* Allocate n of size pqlen, copy p to n */
434 n = snewn(pqlen, BignumInt);
436 for (j = 0; j < i; j++)
438 for (j = 0; j < (int)p[0]; j++)
439 n[i + j] = p[p[0] - j];
441 /* Allocate o of size pqlen, copy q to o */
442 o = snewn(pqlen, BignumInt);
444 for (j = 0; j < i; j++)
446 for (j = 0; j < (int)q[0]; j++)
447 o[i + j] = q[q[0] - j];
449 /* Allocate a of size 2*pqlen for result */
450 a = snewn(2 * pqlen, BignumInt);
452 /* Main computation */
453 internal_mul(n, o, a, pqlen);
454 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
456 /* Fixup result in case the modulus was shifted */
458 for (i = 2 * pqlen - mlen - 1; i < 2 * pqlen - 1; i++)
459 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
460 a[2 * pqlen - 1] = a[2 * pqlen - 1] << mshift;
461 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
462 for (i = 2 * pqlen - 1; i >= 2 * pqlen - mlen; i--)
463 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
466 /* Copy result to buffer */
467 rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
468 result = newbn(rlen);
469 for (i = 0; i < rlen; i++)
470 result[result[0] - i] = a[i + 2 * pqlen - rlen];
471 while (result[0] > 1 && result[result[0]] == 0)
474 /* Free temporary arrays */
475 for (i = 0; i < 2 * pqlen; i++)
478 for (i = 0; i < mlen; i++)
481 for (i = 0; i < pqlen; i++)
484 for (i = 0; i < pqlen; i++)
493 * The most significant word of mod MUST be non-zero.
494 * We assume that the result array is the same size as the mod array.
495 * We optionally write out a quotient if `quotient' is non-NULL.
496 * We can avoid writing out the result if `result' is NULL.
498 static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
502 int plen, mlen, i, j;
504 /* Allocate m of size mlen, copy mod to m */
505 /* We use big endian internally */
507 m = snewn(mlen, BignumInt);
508 for (j = 0; j < mlen; j++)
509 m[j] = mod[mod[0] - j];
511 /* Shift m left to make msb bit set */
512 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
513 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
516 for (i = 0; i < mlen - 1; i++)
517 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
518 m[mlen - 1] = m[mlen - 1] << mshift;
522 /* Ensure plen > mlen */
526 /* Allocate n of size plen, copy p to n */
527 n = snewn(plen, BignumInt);
528 for (j = 0; j < plen; j++)
530 for (j = 1; j <= (int)p[0]; j++)
533 /* Main computation */
534 internal_mod(n, plen, m, mlen, quotient, mshift);
536 /* Fixup result in case the modulus was shifted */
538 for (i = plen - mlen - 1; i < plen - 1; i++)
539 n[i] = (n[i] << mshift) | (n[i + 1] >> (BIGNUM_INT_BITS - mshift));
540 n[plen - 1] = n[plen - 1] << mshift;
541 internal_mod(n, plen, m, mlen, quotient, 0);
542 for (i = plen - 1; i >= plen - mlen; i--)
543 n[i] = (n[i] >> mshift) | (n[i - 1] << (BIGNUM_INT_BITS - mshift));
546 /* Copy result to buffer */
548 for (i = 1; i <= (int)result[0]; i++) {
550 result[i] = j >= 0 ? n[j] : 0;
554 /* Free temporary arrays */
555 for (i = 0; i < mlen; i++)
558 for (i = 0; i < plen; i++)
564 * Decrement a number.
566 void decbn(Bignum bn)
569 while (i < (int)bn[0] && bn[i] == 0)
570 bn[i++] = BIGNUM_INT_MASK;
574 Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
579 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
582 for (i = 1; i <= w; i++)
584 for (i = nbytes; i--;) {
585 unsigned char byte = *data++;
586 result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);
589 while (result[0] > 1 && result[result[0]] == 0)
595 * Read an SSH-1-format bignum from a data buffer. Return the number
596 * of bytes consumed, or -1 if there wasn't enough data.
598 int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)
600 const unsigned char *p = data;
608 for (i = 0; i < 2; i++)
610 b = (w + 7) / 8; /* bits -> bytes */
615 if (!result) /* just return length */
618 *result = bignum_from_bytes(p, b);
624 * Return the bit count of a bignum, for SSH-1 encoding.
626 int bignum_bitcount(Bignum bn)
628 int bitcount = bn[0] * BIGNUM_INT_BITS - 1;
630 && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;
635 * Return the byte length of a bignum when SSH-1 encoded.
637 int ssh1_bignum_length(Bignum bn)
639 return 2 + (bignum_bitcount(bn) + 7) / 8;
643 * Return the byte length of a bignum when SSH-2 encoded.
645 int ssh2_bignum_length(Bignum bn)
647 return 4 + (bignum_bitcount(bn) + 8) / 8;
651 * Return a byte from a bignum; 0 is least significant, etc.
653 int bignum_byte(Bignum bn, int i)
655 if (i >= (int)(BIGNUM_INT_BYTES * bn[0]))
656 return 0; /* beyond the end */
658 return (bn[i / BIGNUM_INT_BYTES + 1] >>
659 ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;
663 * Return a bit from a bignum; 0 is least significant, etc.
665 int bignum_bit(Bignum bn, int i)
667 if (i >= (int)(BIGNUM_INT_BITS * bn[0]))
668 return 0; /* beyond the end */
670 return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;
674 * Set a bit in a bignum; 0 is least significant, etc.
676 void bignum_set_bit(Bignum bn, int bitnum, int value)
678 if (bitnum >= (int)(BIGNUM_INT_BITS * bn[0]))
679 abort(); /* beyond the end */
681 int v = bitnum / BIGNUM_INT_BITS + 1;
682 int mask = 1 << (bitnum % BIGNUM_INT_BITS);
691 * Write a SSH-1-format bignum into a buffer. It is assumed the
692 * buffer is big enough. Returns the number of bytes used.
694 int ssh1_write_bignum(void *data, Bignum bn)
696 unsigned char *p = data;
697 int len = ssh1_bignum_length(bn);
699 int bitc = bignum_bitcount(bn);
701 *p++ = (bitc >> 8) & 0xFF;
702 *p++ = (bitc) & 0xFF;
703 for (i = len - 2; i--;)
704 *p++ = bignum_byte(bn, i);
709 * Compare two bignums. Returns like strcmp.
711 int bignum_cmp(Bignum a, Bignum b)
713 int amax = a[0], bmax = b[0];
714 int i = (amax > bmax ? amax : bmax);
716 BignumInt aval = (i > amax ? 0 : a[i]);
717 BignumInt bval = (i > bmax ? 0 : b[i]);
728 * Right-shift one bignum to form another.
730 Bignum bignum_rshift(Bignum a, int shift)
733 int i, shiftw, shiftb, shiftbb, bits;
736 bits = bignum_bitcount(a) - shift;
737 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
740 shiftw = shift / BIGNUM_INT_BITS;
741 shiftb = shift % BIGNUM_INT_BITS;
742 shiftbb = BIGNUM_INT_BITS - shiftb;
745 for (i = 1; i <= (int)ret[0]; i++) {
747 ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);
748 ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;
756 * Non-modular multiplication and addition.
758 Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
760 int alen = a[0], blen = b[0];
761 int mlen = (alen > blen ? alen : blen);
762 int rlen, i, maxspot;
763 BignumInt *workspace;
766 /* mlen space for a, mlen space for b, 2*mlen for result */
767 workspace = snewn(mlen * 4, BignumInt);
768 for (i = 0; i < mlen; i++) {
769 workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);
770 workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);
773 internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
774 workspace + 2 * mlen, mlen);
776 /* now just copy the result back */
777 rlen = alen + blen + 1;
778 if (addend && rlen <= (int)addend[0])
779 rlen = addend[0] + 1;
782 for (i = 1; i <= (int)ret[0]; i++) {
783 ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
789 /* now add in the addend, if any */
791 BignumDblInt carry = 0;
792 for (i = 1; i <= rlen; i++) {
793 carry += (i <= (int)ret[0] ? ret[i] : 0);
794 carry += (i <= (int)addend[0] ? addend[i] : 0);
795 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
796 carry >>= BIGNUM_INT_BITS;
797 if (ret[i] != 0 && i > maxspot)
808 * Non-modular multiplication.
810 Bignum bigmul(Bignum a, Bignum b)
812 return bigmuladd(a, b, NULL);
816 * Create a bignum which is the bitmask covering another one. That
817 * is, the smallest integer which is >= N and is also one less than
820 Bignum bignum_bitmask(Bignum n)
822 Bignum ret = copybn(n);
827 while (n[i] == 0 && i > 0)
830 return ret; /* input was zero */
836 ret[i] = BIGNUM_INT_MASK;
841 * Convert a (max 32-bit) long into a bignum.
843 Bignum bignum_from_long(unsigned long nn)
849 ret[1] = (BignumInt)(n & BIGNUM_INT_MASK);
850 ret[2] = (BignumInt)((n >> BIGNUM_INT_BITS) & BIGNUM_INT_MASK);
852 ret[0] = (ret[2] ? 2 : 1);
857 * Add a long to a bignum.
859 Bignum bignum_add_long(Bignum number, unsigned long addendx)
861 Bignum ret = newbn(number[0] + 1);
863 BignumDblInt carry = 0, addend = addendx;
865 for (i = 1; i <= (int)ret[0]; i++) {
866 carry += addend & BIGNUM_INT_MASK;
867 carry += (i <= (int)number[0] ? number[i] : 0);
868 addend >>= BIGNUM_INT_BITS;
869 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
870 carry >>= BIGNUM_INT_BITS;
879 * Compute the residue of a bignum, modulo a (max 16-bit) short.
881 unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
888 for (i = number[0]; i > 0; i--)
889 r = (r * (BIGNUM_TOP_BIT % mod) * 2 + number[i] % mod) % mod;
890 return (unsigned short) r;
894 void diagbn(char *prefix, Bignum md)
896 int i, nibbles, morenibbles;
897 static const char hex[] = "0123456789ABCDEF";
899 debug(("%s0x", prefix ? prefix : ""));
901 nibbles = (3 + bignum_bitcount(md)) / 4;
904 morenibbles = 4 * md[0] - nibbles;
905 for (i = 0; i < morenibbles; i++)
907 for (i = nibbles; i--;)
909 hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
919 Bignum bigdiv(Bignum a, Bignum b)
921 Bignum q = newbn(a[0]);
922 bigdivmod(a, b, NULL, q);
929 Bignum bigmod(Bignum a, Bignum b)
931 Bignum r = newbn(b[0]);
932 bigdivmod(a, b, r, NULL);
937 * Greatest common divisor.
939 Bignum biggcd(Bignum av, Bignum bv)
941 Bignum a = copybn(av);
942 Bignum b = copybn(bv);
944 while (bignum_cmp(b, Zero) != 0) {
945 Bignum t = newbn(b[0]);
946 bigdivmod(a, b, t, NULL);
947 while (t[0] > 1 && t[t[0]] == 0)
959 * Modular inverse, using Euclid's extended algorithm.
961 Bignum modinv(Bignum number, Bignum modulus)
963 Bignum a = copybn(modulus);
964 Bignum b = copybn(number);
965 Bignum xp = copybn(Zero);
966 Bignum x = copybn(One);
969 while (bignum_cmp(b, One) != 0) {
970 Bignum t = newbn(b[0]);
971 Bignum q = newbn(a[0]);
972 bigdivmod(a, b, t, q);
973 while (t[0] > 1 && t[t[0]] == 0)
980 x = bigmuladd(q, xp, t);
990 /* now we know that sign * x == 1, and that x < modulus */
992 /* set a new x to be modulus - x */
993 Bignum newx = newbn(modulus[0]);
998 for (i = 1; i <= (int)newx[0]; i++) {
999 BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);
1000 BignumInt bword = (i <= (int)x[0] ? x[i] : 0);
1001 newx[i] = aword - bword - carry;
1003 carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
1017 * Render a bignum into decimal. Return a malloced string holding
1018 * the decimal representation.
1020 char *bignum_decimal(Bignum x)
1022 int ndigits, ndigit;
1026 BignumInt *workspace;
1029 * First, estimate the number of digits. Since log(10)/log(2)
1030 * is just greater than 93/28 (the joys of continued fraction
1031 * approximations...) we know that for every 93 bits, we need
1032 * at most 28 digits. This will tell us how much to malloc.
1034 * Formally: if x has i bits, that means x is strictly less
1035 * than 2^i. Since 2 is less than 10^(28/93), this is less than
1036 * 10^(28i/93). We need an integer power of ten, so we must
1037 * round up (rounding down might make it less than x again).
1038 * Therefore if we multiply the bit count by 28/93, rounding
1039 * up, we will have enough digits.
1041 * i=0 (i.e., x=0) is an irritating special case.
1043 i = bignum_bitcount(x);
1045 ndigits = 1; /* x = 0 */
1047 ndigits = (28 * i + 92) / 93; /* multiply by 28/93 and round up */
1048 ndigits++; /* allow for trailing \0 */
1049 ret = snewn(ndigits, char);
1052 * Now allocate some workspace to hold the binary form as we
1053 * repeatedly divide it by ten. Initialise this to the
1054 * big-endian form of the number.
1056 workspace = snewn(x[0], BignumInt);
1057 for (i = 0; i < (int)x[0]; i++)
1058 workspace[i] = x[x[0] - i];
1061 * Next, write the decimal number starting with the last digit.
1062 * We use ordinary short division, dividing 10 into the
1065 ndigit = ndigits - 1;
1070 for (i = 0; i < (int)x[0]; i++) {
1071 carry = (carry << BIGNUM_INT_BITS) + workspace[i];
1072 workspace[i] = (BignumInt) (carry / 10);
1077 ret[--ndigit] = (char) (carry + '0');
1081 * There's a chance we've fallen short of the start of the
1082 * string. Correct if so.
1085 memmove(ret, ret + ndigit, ndigits - ndigit);