2 * Bignum routines for RSA and DH and stuff.
16 * * Do not call the DIVMOD_WORD macro with expressions such as array
17 * subscripts, as some implementations object to this (see below).
18 * * Note that none of the division methods below will cope if the
19 * quotient won't fit into BIGNUM_INT_BITS. Callers should be careful
21 * If this condition occurs, in the case of the x86 DIV instruction,
22 * an overflow exception will occur, which (according to a correspondent)
23 * will manifest on Windows as something like
24 * 0xC0000095: Integer overflow
25 * The C variant won't give the right answer, either.
28 #if defined __GNUC__ && defined __i386__
29 typedef unsigned long BignumInt;
30 typedef unsigned long long BignumDblInt;
31 #define BIGNUM_INT_MASK 0xFFFFFFFFUL
32 #define BIGNUM_TOP_BIT 0x80000000UL
33 #define BIGNUM_INT_BITS 32
34 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
35 #define DIVMOD_WORD(q, r, hi, lo, w) \
37 "=d" (r), "=a" (q) : \
38 "r" (w), "d" (hi), "a" (lo))
39 #elif defined _MSC_VER && defined _M_IX86
40 typedef unsigned __int32 BignumInt;
41 typedef unsigned __int64 BignumDblInt;
42 #define BIGNUM_INT_MASK 0xFFFFFFFFUL
43 #define BIGNUM_TOP_BIT 0x80000000UL
44 #define BIGNUM_INT_BITS 32
45 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
46 /* Note: MASM interprets array subscripts in the macro arguments as
47 * assembler syntax, which gives the wrong answer. Don't supply them.
48 * <http://msdn2.microsoft.com/en-us/library/bf1dw62z.aspx> */
49 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
57 /* 64-bit architectures can do 32x32->64 chunks at a time */
58 typedef unsigned int BignumInt;
59 typedef unsigned long BignumDblInt;
60 #define BIGNUM_INT_MASK 0xFFFFFFFFU
61 #define BIGNUM_TOP_BIT 0x80000000U
62 #define BIGNUM_INT_BITS 32
63 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
64 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
65 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
70 /* 64-bit architectures in which unsigned long is 32 bits, not 64 */
71 typedef unsigned long BignumInt;
72 typedef unsigned long long BignumDblInt;
73 #define BIGNUM_INT_MASK 0xFFFFFFFFUL
74 #define BIGNUM_TOP_BIT 0x80000000UL
75 #define BIGNUM_INT_BITS 32
76 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
77 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
78 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
83 /* Fallback for all other cases */
84 typedef unsigned short BignumInt;
85 typedef unsigned long BignumDblInt;
86 #define BIGNUM_INT_MASK 0xFFFFU
87 #define BIGNUM_TOP_BIT 0x8000U
88 #define BIGNUM_INT_BITS 16
89 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
90 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
91 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
97 #define BIGNUM_INT_BYTES (BIGNUM_INT_BITS / 8)
99 #define BIGNUM_INTERNAL
100 typedef BignumInt *Bignum;
104 BignumInt bnZero[1] = { 0 };
105 BignumInt bnOne[2] = { 1, 1 };
106 BignumInt bnTen[2] = { 1, 10 };
109 * The Bignum format is an array of `BignumInt'. The first
110 * element of the array counts the remaining elements. The
111 * remaining elements express the actual number, base 2^BIGNUM_INT_BITS, _least_
112 * significant digit first. (So it's trivial to extract the bit
113 * with value 2^n for any n.)
115 * All Bignums in this module are positive. Negative numbers must
116 * be dealt with outside it.
118 * INVARIANT: the most significant word of any Bignum must be
122 Bignum Zero = bnZero, One = bnOne, Ten = bnTen;
124 static Bignum newbn(int length)
128 assert(length >= 0 && length < INT_MAX / BIGNUM_INT_BITS);
130 b = snewn(length + 1, BignumInt);
133 memset(b, 0, (length + 1) * sizeof(*b));
138 void bn_restore_invariant(Bignum b)
140 while (b[0] > 1 && b[b[0]] == 0)
144 Bignum copybn(Bignum orig)
146 Bignum b = snewn(orig[0] + 1, BignumInt);
149 memcpy(b, orig, (orig[0] + 1) * sizeof(*b));
153 void freebn(Bignum b)
156 * Burn the evidence, just in case.
158 smemclr(b, sizeof(b[0]) * (b[0] + 1));
162 Bignum bn_power_2(int n)
168 ret = newbn(n / BIGNUM_INT_BITS + 1);
169 bignum_set_bit(ret, n, 1);
174 * Internal addition. Sets c = a - b, where 'a', 'b' and 'c' are all
175 * big-endian arrays of 'len' BignumInts. Returns a BignumInt carried
178 static BignumInt internal_add(const BignumInt *a, const BignumInt *b,
179 BignumInt *c, int len)
182 BignumDblInt carry = 0;
184 for (i = len-1; i >= 0; i--) {
185 carry += (BignumDblInt)a[i] + b[i];
186 c[i] = (BignumInt)carry;
187 carry >>= BIGNUM_INT_BITS;
190 return (BignumInt)carry;
194 * Internal subtraction. Sets c = a - b, where 'a', 'b' and 'c' are
195 * all big-endian arrays of 'len' BignumInts. Any borrow from the top
198 static void internal_sub(const BignumInt *a, const BignumInt *b,
199 BignumInt *c, int len)
202 BignumDblInt carry = 1;
204 for (i = len-1; i >= 0; i--) {
205 carry += (BignumDblInt)a[i] + (b[i] ^ BIGNUM_INT_MASK);
206 c[i] = (BignumInt)carry;
207 carry >>= BIGNUM_INT_BITS;
213 * Input is in the first len words of a and b.
214 * Result is returned in the first 2*len words of c.
216 * 'scratch' must point to an array of BignumInt of size at least
217 * mul_compute_scratch(len). (This covers the needs of internal_mul
218 * and all its recursive calls to itself.)
220 #define KARATSUBA_THRESHOLD 50
221 static int mul_compute_scratch(int len)
224 while (len > KARATSUBA_THRESHOLD) {
225 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
226 int midlen = botlen + 1;
232 static void internal_mul(const BignumInt *a, const BignumInt *b,
233 BignumInt *c, int len, BignumInt *scratch)
235 if (len > KARATSUBA_THRESHOLD) {
239 * Karatsuba divide-and-conquer algorithm. Cut each input in
240 * half, so that it's expressed as two big 'digits' in a giant
246 * Then the product is of course
248 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
250 * and we compute the three coefficients by recursively
251 * calling ourself to do half-length multiplications.
253 * The clever bit that makes this worth doing is that we only
254 * need _one_ half-length multiplication for the central
255 * coefficient rather than the two that it obviouly looks
256 * like, because we can use a single multiplication to compute
258 * (a_1 + a_0) (b_1 + b_0) = a_1 b_1 + a_1 b_0 + a_0 b_1 + a_0 b_0
260 * and then we subtract the other two coefficients (a_1 b_1
261 * and a_0 b_0) which we were computing anyway.
263 * Hence we get to multiply two numbers of length N in about
264 * three times as much work as it takes to multiply numbers of
265 * length N/2, which is obviously better than the four times
266 * as much work it would take if we just did a long
267 * conventional multiply.
270 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
271 int midlen = botlen + 1;
278 * The coefficients a_1 b_1 and a_0 b_0 just avoid overlapping
279 * in the output array, so we can compute them immediately in
284 printf("a1,a0 = 0x");
285 for (i = 0; i < len; i++) {
286 if (i == toplen) printf(", 0x");
287 printf("%0*x", BIGNUM_INT_BITS/4, a[i]);
290 printf("b1,b0 = 0x");
291 for (i = 0; i < len; i++) {
292 if (i == toplen) printf(", 0x");
293 printf("%0*x", BIGNUM_INT_BITS/4, b[i]);
299 internal_mul(a, b, c, toplen, scratch);
302 for (i = 0; i < 2*toplen; i++) {
303 printf("%0*x", BIGNUM_INT_BITS/4, c[i]);
309 internal_mul(a + toplen, b + toplen, c + 2*toplen, botlen, scratch);
312 for (i = 0; i < 2*botlen; i++) {
313 printf("%0*x", BIGNUM_INT_BITS/4, c[2*toplen+i]);
318 /* Zero padding. midlen exceeds toplen by at most 2, so just
319 * zero the first two words of each input and the rest will be
321 scratch[0] = scratch[1] = scratch[midlen] = scratch[midlen+1] = 0;
323 for (i = 0; i < toplen; i++) {
324 scratch[midlen - toplen + i] = a[i]; /* a_1 */
325 scratch[2*midlen - toplen + i] = b[i]; /* b_1 */
328 /* compute a_1 + a_0 */
329 scratch[0] = internal_add(scratch+1, a+toplen, scratch+1, botlen);
331 printf("a1plusa0 = 0x");
332 for (i = 0; i < midlen; i++) {
333 printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);
337 /* compute b_1 + b_0 */
338 scratch[midlen] = internal_add(scratch+midlen+1, b+toplen,
339 scratch+midlen+1, botlen);
341 printf("b1plusb0 = 0x");
342 for (i = 0; i < midlen; i++) {
343 printf("%0*x", BIGNUM_INT_BITS/4, scratch[midlen+i]);
349 * Now we can do the third multiplication.
351 internal_mul(scratch, scratch + midlen, scratch + 2*midlen, midlen,
354 printf("a1plusa0timesb1plusb0 = 0x");
355 for (i = 0; i < 2*midlen; i++) {
356 printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);
362 * Now we can reuse the first half of 'scratch' to compute the
363 * sum of the outer two coefficients, to subtract from that
364 * product to obtain the middle one.
366 scratch[0] = scratch[1] = scratch[2] = scratch[3] = 0;
367 for (i = 0; i < 2*toplen; i++)
368 scratch[2*midlen - 2*toplen + i] = c[i];
369 scratch[1] = internal_add(scratch+2, c + 2*toplen,
370 scratch+2, 2*botlen);
372 printf("a1b1plusa0b0 = 0x");
373 for (i = 0; i < 2*midlen; i++) {
374 printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);
379 internal_sub(scratch + 2*midlen, scratch,
380 scratch + 2*midlen, 2*midlen);
382 printf("a1b0plusa0b1 = 0x");
383 for (i = 0; i < 2*midlen; i++) {
384 printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);
390 * And now all we need to do is to add that middle coefficient
391 * back into the output. We may have to propagate a carry
392 * further up the output, but we can be sure it won't
393 * propagate right the way off the top.
395 carry = internal_add(c + 2*len - botlen - 2*midlen,
397 c + 2*len - botlen - 2*midlen, 2*midlen);
398 i = 2*len - botlen - 2*midlen - 1;
402 c[i] = (BignumInt)carry;
403 carry >>= BIGNUM_INT_BITS;
408 for (i = 0; i < 2*len; i++) {
409 printf("%0*x", BIGNUM_INT_BITS/4, c[i]);
418 const BignumInt *ap, *bp;
422 * Multiply in the ordinary O(N^2) way.
425 for (i = 0; i < 2 * len; i++)
428 for (cps = c + 2*len, ap = a + len; ap-- > a; cps--) {
430 for (cp = cps, bp = b + len; cp--, bp-- > b ;) {
431 t = (MUL_WORD(*ap, *bp) + carry) + *cp;
433 carry = (BignumInt)(t >> BIGNUM_INT_BITS);
441 * Variant form of internal_mul used for the initial step of
442 * Montgomery reduction. Only bothers outputting 'len' words
443 * (everything above that is thrown away).
445 static void internal_mul_low(const BignumInt *a, const BignumInt *b,
446 BignumInt *c, int len, BignumInt *scratch)
448 if (len > KARATSUBA_THRESHOLD) {
452 * Karatsuba-aware version of internal_mul_low. As before, we
453 * express each input value as a shifted combination of two
459 * Then the full product is, as before,
461 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
463 * Provided we choose D on the large side (so that a_0 and b_0
464 * are _at least_ as long as a_1 and b_1), we don't need the
465 * topmost term at all, and we only need half of the middle
466 * term. So there's no point in doing the proper Karatsuba
467 * optimisation which computes the middle term using the top
468 * one, because we'd take as long computing the top one as
469 * just computing the middle one directly.
471 * So instead, we do a much more obvious thing: we call the
472 * fully optimised internal_mul to compute a_0 b_0, and we
473 * recursively call ourself to compute the _bottom halves_ of
474 * a_1 b_0 and a_0 b_1, each of which we add into the result
475 * in the obvious way.
477 * In other words, there's no actual Karatsuba _optimisation_
478 * in this function; the only benefit in doing it this way is
479 * that we call internal_mul proper for a large part of the
480 * work, and _that_ can optimise its operation.
483 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
486 * Scratch space for the various bits and pieces we're going
487 * to be adding together: we need botlen*2 words for a_0 b_0
488 * (though we may end up throwing away its topmost word), and
489 * toplen words for each of a_1 b_0 and a_0 b_1. That adds up
494 internal_mul(a + toplen, b + toplen, scratch + 2*toplen, botlen,
498 internal_mul_low(a, b + len - toplen, scratch + toplen, toplen,
502 internal_mul_low(a + len - toplen, b, scratch, toplen,
505 /* Copy the bottom half of the big coefficient into place */
506 for (i = 0; i < botlen; i++)
507 c[toplen + i] = scratch[2*toplen + botlen + i];
509 /* Add the two small coefficients, throwing away the returned carry */
510 internal_add(scratch, scratch + toplen, scratch, toplen);
512 /* And add that to the large coefficient, leaving the result in c. */
513 internal_add(scratch, scratch + 2*toplen + botlen - toplen,
520 const BignumInt *ap, *bp;
524 * Multiply in the ordinary O(N^2) way.
527 for (i = 0; i < len; i++)
530 for (cps = c + len, ap = a + len; ap-- > a; cps--) {
532 for (cp = cps, bp = b + len; bp--, cp-- > c ;) {
533 t = (MUL_WORD(*ap, *bp) + carry) + *cp;
535 carry = (BignumInt)(t >> BIGNUM_INT_BITS);
542 * Montgomery reduction. Expects x to be a big-endian array of 2*len
543 * BignumInts whose value satisfies 0 <= x < rn (where r = 2^(len *
544 * BIGNUM_INT_BITS) is the Montgomery base). Returns in the same array
545 * a value x' which is congruent to xr^{-1} mod n, and satisfies 0 <=
548 * 'n' and 'mninv' should be big-endian arrays of 'len' BignumInts
549 * each, containing respectively n and the multiplicative inverse of
552 * 'tmp' is an array of BignumInt used as scratch space, of length at
553 * least 3*len + mul_compute_scratch(len).
555 static void monty_reduce(BignumInt *x, const BignumInt *n,
556 const BignumInt *mninv, BignumInt *tmp, int len)
562 * Multiply x by (-n)^{-1} mod r. This gives us a value m such
563 * that mn is congruent to -x mod r. Hence, mn+x is an exact
564 * multiple of r, and is also (obviously) congruent to x mod n.
566 internal_mul_low(x + len, mninv, tmp, len, tmp + 3*len);
569 * Compute t = (mn+x)/r in ordinary, non-modular, integer
570 * arithmetic. By construction this is exact, and is congruent mod
571 * n to x * r^{-1}, i.e. the answer we want.
573 * The following multiply leaves that answer in the _most_
574 * significant half of the 'x' array, so then we must shift it
577 internal_mul(tmp, n, tmp+len, len, tmp + 3*len);
578 carry = internal_add(x, tmp+len, x, 2*len);
579 for (i = 0; i < len; i++)
580 x[len + i] = x[i], x[i] = 0;
583 * Reduce t mod n. This doesn't require a full-on division by n,
584 * but merely a test and single optional subtraction, since we can
585 * show that 0 <= t < 2n.
588 * + we computed m mod r, so 0 <= m < r.
589 * + so 0 <= mn < rn, obviously
590 * + hence we only need 0 <= x < rn to guarantee that 0 <= mn+x < 2rn
591 * + yielding 0 <= (mn+x)/r < 2n as required.
594 for (i = 0; i < len; i++)
595 if (x[len + i] != n[i])
598 if (carry || i >= len || x[len + i] > n[i])
599 internal_sub(x+len, n, x+len, len);
602 static void internal_add_shifted(BignumInt *number,
603 unsigned n, int shift)
605 int word = 1 + (shift / BIGNUM_INT_BITS);
606 int bshift = shift % BIGNUM_INT_BITS;
609 addend = (BignumDblInt)n << bshift;
612 assert(word <= number[0]);
613 addend += number[word];
614 number[word] = (BignumInt) addend & BIGNUM_INT_MASK;
615 addend >>= BIGNUM_INT_BITS;
622 * Input in first alen words of a and first mlen words of m.
623 * Output in first alen words of a
624 * (of which first alen-mlen words will be zero).
625 * The MSW of m MUST have its high bit set.
626 * Quotient is accumulated in the `quotient' array, which is a Bignum
627 * rather than the internal bigendian format. Quotient parts are shifted
628 * left by `qshift' before adding into quot.
630 static void internal_mod(BignumInt *a, int alen,
631 BignumInt *m, int mlen,
632 BignumInt *quot, int qshift)
639 assert(m0 >> (BIGNUM_INT_BITS-1) == 1);
645 for (i = 0; i <= alen - mlen; i++) {
647 unsigned int q, r, c, ai1;
661 /* Find q = h:a[i] / m0 */
666 * To illustrate it, suppose a BignumInt is 8 bits, and
667 * we are dividing (say) A1:23:45:67 by A1:B2:C3. Then
668 * our initial division will be 0xA123 / 0xA1, which
669 * will give a quotient of 0x100 and a divide overflow.
670 * However, the invariants in this division algorithm
671 * are not violated, since the full number A1:23:... is
672 * _less_ than the quotient prefix A1:B2:... and so the
673 * following correction loop would have sorted it out.
675 * In this situation we set q to be the largest
676 * quotient we _can_ stomach (0xFF, of course).
680 /* Macro doesn't want an array subscript expression passed
681 * into it (see definition), so use a temporary. */
682 BignumInt tmplo = a[i];
683 DIVMOD_WORD(q, r, h, tmplo, m0);
685 /* Refine our estimate of q by looking at
686 h:a[i]:a[i+1] / m0:m1 */
688 if (t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) {
691 r = (r + m0) & BIGNUM_INT_MASK; /* overflow? */
692 if (r >= (BignumDblInt) m0 &&
693 t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) q--;
697 /* Subtract q * m from a[i...] */
699 for (k = mlen - 1; k >= 0; k--) {
700 t = MUL_WORD(q, m[k]);
702 c = (unsigned)(t >> BIGNUM_INT_BITS);
703 if ((BignumInt) t > a[i + k])
705 a[i + k] -= (BignumInt) t;
708 /* Add back m in case of borrow */
711 for (k = mlen - 1; k >= 0; k--) {
714 a[i + k] = (BignumInt) t;
715 t = t >> BIGNUM_INT_BITS;
720 internal_add_shifted(quot, q, qshift + BIGNUM_INT_BITS * (alen - mlen - i));
725 * Compute (base ^ exp) % mod, the pedestrian way.
727 Bignum modpow_simple(Bignum base_in, Bignum exp, Bignum mod)
729 BignumInt *a, *b, *n, *m, *scratch;
731 int mlen, scratchlen, i, j;
735 * The most significant word of mod needs to be non-zero. It
736 * should already be, but let's make sure.
738 assert(mod[mod[0]] != 0);
741 * Make sure the base is smaller than the modulus, by reducing
742 * it modulo the modulus if not.
744 base = bigmod(base_in, mod);
746 /* Allocate m of size mlen, copy mod to m */
747 /* We use big endian internally */
749 m = snewn(mlen, BignumInt);
750 for (j = 0; j < mlen; j++)
751 m[j] = mod[mod[0] - j];
753 /* Shift m left to make msb bit set */
754 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
755 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
758 for (i = 0; i < mlen - 1; i++)
759 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
760 m[mlen - 1] = m[mlen - 1] << mshift;
763 /* Allocate n of size mlen, copy base to n */
764 n = snewn(mlen, BignumInt);
766 for (j = 0; j < i; j++)
768 for (j = 0; j < (int)base[0]; j++)
769 n[i + j] = base[base[0] - j];
771 /* Allocate a and b of size 2*mlen. Set a = 1 */
772 a = snewn(2 * mlen, BignumInt);
773 b = snewn(2 * mlen, BignumInt);
774 for (i = 0; i < 2 * mlen; i++)
778 /* Scratch space for multiplies */
779 scratchlen = mul_compute_scratch(mlen);
780 scratch = snewn(scratchlen, BignumInt);
782 /* Skip leading zero bits of exp. */
784 j = BIGNUM_INT_BITS-1;
785 while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
789 j = BIGNUM_INT_BITS-1;
793 /* Main computation */
794 while (i < (int)exp[0]) {
796 internal_mul(a + mlen, a + mlen, b, mlen, scratch);
797 internal_mod(b, mlen * 2, m, mlen, NULL, 0);
798 if ((exp[exp[0] - i] & (1 << j)) != 0) {
799 internal_mul(b + mlen, n, a, mlen, scratch);
800 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
810 j = BIGNUM_INT_BITS-1;
813 /* Fixup result in case the modulus was shifted */
815 for (i = mlen - 1; i < 2 * mlen - 1; i++)
816 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
817 a[2 * mlen - 1] = a[2 * mlen - 1] << mshift;
818 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
819 for (i = 2 * mlen - 1; i >= mlen; i--)
820 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
823 /* Copy result to buffer */
824 result = newbn(mod[0]);
825 for (i = 0; i < mlen; i++)
826 result[result[0] - i] = a[i + mlen];
827 while (result[0] > 1 && result[result[0]] == 0)
830 /* Free temporary arrays */
831 smemclr(a, 2 * mlen * sizeof(*a));
833 smemclr(scratch, scratchlen * sizeof(*scratch));
835 smemclr(b, 2 * mlen * sizeof(*b));
837 smemclr(m, mlen * sizeof(*m));
839 smemclr(n, mlen * sizeof(*n));
848 * Compute (base ^ exp) % mod. Uses the Montgomery multiplication
849 * technique where possible, falling back to modpow_simple otherwise.
851 Bignum modpow(Bignum base_in, Bignum exp, Bignum mod)
853 BignumInt *a, *b, *x, *n, *mninv, *scratch;
854 int len, scratchlen, i, j;
855 Bignum base, base2, r, rn, inv, result;
858 * The most significant word of mod needs to be non-zero. It
859 * should already be, but let's make sure.
861 assert(mod[mod[0]] != 0);
864 * mod had better be odd, or we can't do Montgomery multiplication
865 * using a power of two at all.
868 return modpow_simple(base_in, exp, mod);
871 * Make sure the base is smaller than the modulus, by reducing
872 * it modulo the modulus if not.
874 base = bigmod(base_in, mod);
877 * Compute the inverse of n mod r, for monty_reduce. (In fact we
878 * want the inverse of _minus_ n mod r, but we'll sort that out
882 r = bn_power_2(BIGNUM_INT_BITS * len);
883 inv = modinv(mod, r);
884 assert(inv); /* cannot fail, since mod is odd and r is a power of 2 */
887 * Multiply the base by r mod n, to get it into Montgomery
890 base2 = modmul(base, r, mod);
894 rn = bigmod(r, mod); /* r mod n, i.e. Montgomerified 1 */
896 freebn(r); /* won't need this any more */
899 * Set up internal arrays of the right lengths, in big-endian
900 * format, containing the base, the modulus, and the modulus's
903 n = snewn(len, BignumInt);
904 for (j = 0; j < len; j++)
905 n[len - 1 - j] = mod[j + 1];
907 mninv = snewn(len, BignumInt);
908 for (j = 0; j < len; j++)
909 mninv[len - 1 - j] = (j < (int)inv[0] ? inv[j + 1] : 0);
910 freebn(inv); /* we don't need this copy of it any more */
911 /* Now negate mninv mod r, so it's the inverse of -n rather than +n. */
912 x = snewn(len, BignumInt);
913 for (j = 0; j < len; j++)
915 internal_sub(x, mninv, mninv, len);
917 /* x = snewn(len, BignumInt); */ /* already done above */
918 for (j = 0; j < len; j++)
919 x[len - 1 - j] = (j < (int)base[0] ? base[j + 1] : 0);
920 freebn(base); /* we don't need this copy of it any more */
922 a = snewn(2*len, BignumInt);
923 b = snewn(2*len, BignumInt);
924 for (j = 0; j < len; j++)
925 a[2*len - 1 - j] = (j < (int)rn[0] ? rn[j + 1] : 0);
928 /* Scratch space for multiplies */
929 scratchlen = 3*len + mul_compute_scratch(len);
930 scratch = snewn(scratchlen, BignumInt);
932 /* Skip leading zero bits of exp. */
934 j = BIGNUM_INT_BITS-1;
935 while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
939 j = BIGNUM_INT_BITS-1;
943 /* Main computation */
944 while (i < (int)exp[0]) {
946 internal_mul(a + len, a + len, b, len, scratch);
947 monty_reduce(b, n, mninv, scratch, len);
948 if ((exp[exp[0] - i] & (1 << j)) != 0) {
949 internal_mul(b + len, x, a, len, scratch);
950 monty_reduce(a, n, mninv, scratch, len);
960 j = BIGNUM_INT_BITS-1;
964 * Final monty_reduce to get back from the adjusted Montgomery
967 monty_reduce(a, n, mninv, scratch, len);
969 /* Copy result to buffer */
970 result = newbn(mod[0]);
971 for (i = 0; i < len; i++)
972 result[result[0] - i] = a[i + len];
973 while (result[0] > 1 && result[result[0]] == 0)
976 /* Free temporary arrays */
977 smemclr(scratch, scratchlen * sizeof(*scratch));
979 smemclr(a, 2 * len * sizeof(*a));
981 smemclr(b, 2 * len * sizeof(*b));
983 smemclr(mninv, len * sizeof(*mninv));
985 smemclr(n, len * sizeof(*n));
987 smemclr(x, len * sizeof(*x));
994 * Compute (p * q) % mod.
995 * The most significant word of mod MUST be non-zero.
996 * We assume that the result array is the same size as the mod array.
998 Bignum modmul(Bignum p, Bignum q, Bignum mod)
1000 BignumInt *a, *n, *m, *o, *scratch;
1001 int mshift, scratchlen;
1002 int pqlen, mlen, rlen, i, j;
1006 * The most significant word of mod needs to be non-zero. It
1007 * should already be, but let's make sure.
1009 assert(mod[mod[0]] != 0);
1011 /* Allocate m of size mlen, copy mod to m */
1012 /* We use big endian internally */
1014 m = snewn(mlen, BignumInt);
1015 for (j = 0; j < mlen; j++)
1016 m[j] = mod[mod[0] - j];
1018 /* Shift m left to make msb bit set */
1019 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
1020 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
1023 for (i = 0; i < mlen - 1; i++)
1024 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
1025 m[mlen - 1] = m[mlen - 1] << mshift;
1028 pqlen = (p[0] > q[0] ? p[0] : q[0]);
1031 * Make sure that we're allowing enough space. The shifting below
1032 * will underflow the vectors we allocate if pqlen is too small.
1034 if (2*pqlen <= mlen)
1037 /* Allocate n of size pqlen, copy p to n */
1038 n = snewn(pqlen, BignumInt);
1040 for (j = 0; j < i; j++)
1042 for (j = 0; j < (int)p[0]; j++)
1043 n[i + j] = p[p[0] - j];
1045 /* Allocate o of size pqlen, copy q to o */
1046 o = snewn(pqlen, BignumInt);
1048 for (j = 0; j < i; j++)
1050 for (j = 0; j < (int)q[0]; j++)
1051 o[i + j] = q[q[0] - j];
1053 /* Allocate a of size 2*pqlen for result */
1054 a = snewn(2 * pqlen, BignumInt);
1056 /* Scratch space for multiplies */
1057 scratchlen = mul_compute_scratch(pqlen);
1058 scratch = snewn(scratchlen, BignumInt);
1060 /* Main computation */
1061 internal_mul(n, o, a, pqlen, scratch);
1062 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
1064 /* Fixup result in case the modulus was shifted */
1066 for (i = 2 * pqlen - mlen - 1; i < 2 * pqlen - 1; i++)
1067 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
1068 a[2 * pqlen - 1] = a[2 * pqlen - 1] << mshift;
1069 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
1070 for (i = 2 * pqlen - 1; i >= 2 * pqlen - mlen; i--)
1071 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
1074 /* Copy result to buffer */
1075 rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
1076 result = newbn(rlen);
1077 for (i = 0; i < rlen; i++)
1078 result[result[0] - i] = a[i + 2 * pqlen - rlen];
1079 while (result[0] > 1 && result[result[0]] == 0)
1082 /* Free temporary arrays */
1083 smemclr(scratch, scratchlen * sizeof(*scratch));
1085 smemclr(a, 2 * pqlen * sizeof(*a));
1087 smemclr(m, mlen * sizeof(*m));
1089 smemclr(n, pqlen * sizeof(*n));
1091 smemclr(o, pqlen * sizeof(*o));
1097 Bignum modsub(const Bignum a, const Bignum b, const Bignum n)
1101 if (bignum_cmp(a, n) >= 0) a1 = bigmod(a, n);
1103 if (bignum_cmp(b, n) >= 0) b1 = bigmod(b, n);
1106 if (bignum_cmp(a1, b1) >= 0) /* a >= b */
1108 ret = bigsub(a1, b1);
1112 /* Handle going round the corner of the modulus without having
1113 * negative support in Bignum */
1114 Bignum tmp = bigsub(n, b1);
1116 ret = bigadd(tmp, a1);
1123 if (a != a1) freebn(a1);
1124 if (b != b1) freebn(b1);
1131 * The most significant word of mod MUST be non-zero.
1132 * We assume that the result array is the same size as the mod array.
1133 * We optionally write out a quotient if `quotient' is non-NULL.
1134 * We can avoid writing out the result if `result' is NULL.
1136 static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
1140 int plen, mlen, i, j;
1143 * The most significant word of mod needs to be non-zero. It
1144 * should already be, but let's make sure.
1146 assert(mod[mod[0]] != 0);
1148 /* Allocate m of size mlen, copy mod to m */
1149 /* We use big endian internally */
1151 m = snewn(mlen, BignumInt);
1152 for (j = 0; j < mlen; j++)
1153 m[j] = mod[mod[0] - j];
1155 /* Shift m left to make msb bit set */
1156 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
1157 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
1160 for (i = 0; i < mlen - 1; i++)
1161 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
1162 m[mlen - 1] = m[mlen - 1] << mshift;
1166 /* Ensure plen > mlen */
1170 /* Allocate n of size plen, copy p to n */
1171 n = snewn(plen, BignumInt);
1172 for (j = 0; j < plen; j++)
1174 for (j = 1; j <= (int)p[0]; j++)
1177 /* Main computation */
1178 internal_mod(n, plen, m, mlen, quotient, mshift);
1180 /* Fixup result in case the modulus was shifted */
1182 for (i = plen - mlen - 1; i < plen - 1; i++)
1183 n[i] = (n[i] << mshift) | (n[i + 1] >> (BIGNUM_INT_BITS - mshift));
1184 n[plen - 1] = n[plen - 1] << mshift;
1185 internal_mod(n, plen, m, mlen, quotient, 0);
1186 for (i = plen - 1; i >= plen - mlen; i--)
1187 n[i] = (n[i] >> mshift) | (n[i - 1] << (BIGNUM_INT_BITS - mshift));
1190 /* Copy result to buffer */
1192 for (i = 1; i <= (int)result[0]; i++) {
1194 result[i] = j >= 0 ? n[j] : 0;
1198 /* Free temporary arrays */
1199 smemclr(m, mlen * sizeof(*m));
1201 smemclr(n, plen * sizeof(*n));
1206 * Decrement a number.
1208 void decbn(Bignum bn)
1211 while (i < (int)bn[0] && bn[i] == 0)
1212 bn[i++] = BIGNUM_INT_MASK;
1216 Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
1221 assert(nbytes >= 0 && nbytes < INT_MAX/8);
1223 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
1226 for (i = 1; i <= w; i++)
1228 for (i = nbytes; i--;) {
1229 unsigned char byte = *data++;
1230 result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);
1233 while (result[0] > 1 && result[result[0]] == 0)
1238 Bignum bignum_from_bytes_le(const unsigned char *data, int nbytes)
1243 assert(nbytes >= 0 && nbytes < INT_MAX/8);
1245 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
1248 for (i = 1; i <= w; i++)
1250 for (i = 0; i < nbytes; ++i) {
1251 unsigned char byte = *data++;
1252 result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);
1255 while (result[0] > 1 && result[result[0]] == 0)
1260 Bignum bignum_from_decimal(const char *decimal)
1262 Bignum result = copybn(Zero);
1267 if (!isdigit((unsigned char)*decimal)) {
1272 tmp = bigmul(result, Ten);
1273 tmp2 = bignum_from_long(*decimal - '0');
1274 result = bigadd(tmp, tmp2);
1284 Bignum bignum_random_in_range(const Bignum lower, const Bignum upper)
1287 unsigned char *bytes;
1288 int upper_len = bignum_bitcount(upper);
1289 int upper_bytes = upper_len / 8;
1290 int upper_bits = upper_len % 8;
1291 if (upper_bits) ++upper_bytes;
1293 bytes = snewn(upper_bytes, unsigned char);
1297 if (ret) freebn(ret);
1299 for (i = 0; i < upper_bytes; ++i)
1301 bytes[i] = (unsigned char)random_byte();
1303 /* Mask the top to reduce failure rate to 50/50 */
1306 bytes[i - 1] &= 0xFF >> (8 - upper_bits);
1309 ret = bignum_from_bytes(bytes, upper_bytes);
1310 } while (bignum_cmp(ret, lower) < 0 || bignum_cmp(ret, upper) > 0);
1311 smemclr(bytes, upper_bytes);
1318 * Read an SSH-1-format bignum from a data buffer. Return the number
1319 * of bytes consumed, or -1 if there wasn't enough data.
1321 int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)
1323 const unsigned char *p = data;
1331 for (i = 0; i < 2; i++)
1332 w = (w << 8) + *p++;
1333 b = (w + 7) / 8; /* bits -> bytes */
1338 if (!result) /* just return length */
1341 *result = bignum_from_bytes(p, b);
1343 return p + b - data;
1347 * Return the bit count of a bignum, for SSH-1 encoding.
1349 int bignum_bitcount(Bignum bn)
1351 int bitcount = bn[0] * BIGNUM_INT_BITS - 1;
1352 while (bitcount >= 0
1353 && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;
1354 return bitcount + 1;
1358 * Return the byte length of a bignum when SSH-1 encoded.
1360 int ssh1_bignum_length(Bignum bn)
1362 return 2 + (bignum_bitcount(bn) + 7) / 8;
1366 * Return the byte length of a bignum when SSH-2 encoded.
1368 int ssh2_bignum_length(Bignum bn)
1370 return 4 + (bignum_bitcount(bn) + 8) / 8;
1374 * Return a byte from a bignum; 0 is least significant, etc.
1376 int bignum_byte(Bignum bn, int i)
1378 if (i < 0 || i >= (int)(BIGNUM_INT_BYTES * bn[0]))
1379 return 0; /* beyond the end */
1381 return (bn[i / BIGNUM_INT_BYTES + 1] >>
1382 ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;
1386 * Return a bit from a bignum; 0 is least significant, etc.
1388 int bignum_bit(Bignum bn, int i)
1390 if (i < 0 || i >= (int)(BIGNUM_INT_BITS * bn[0]))
1391 return 0; /* beyond the end */
1393 return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;
1397 * Set a bit in a bignum; 0 is least significant, etc.
1399 void bignum_set_bit(Bignum bn, int bitnum, int value)
1401 if (bitnum < 0 || bitnum >= (int)(BIGNUM_INT_BITS * bn[0]))
1402 abort(); /* beyond the end */
1404 int v = bitnum / BIGNUM_INT_BITS + 1;
1405 int mask = 1 << (bitnum % BIGNUM_INT_BITS);
1414 * Write a SSH-1-format bignum into a buffer. It is assumed the
1415 * buffer is big enough. Returns the number of bytes used.
1417 int ssh1_write_bignum(void *data, Bignum bn)
1419 unsigned char *p = data;
1420 int len = ssh1_bignum_length(bn);
1422 int bitc = bignum_bitcount(bn);
1424 *p++ = (bitc >> 8) & 0xFF;
1425 *p++ = (bitc) & 0xFF;
1426 for (i = len - 2; i--;)
1427 *p++ = bignum_byte(bn, i);
1432 * Compare two bignums. Returns like strcmp.
1434 int bignum_cmp(Bignum a, Bignum b)
1436 int amax = a[0], bmax = b[0];
1439 /* Annoyingly we have two representations of zero */
1440 if (amax == 1 && a[amax] == 0)
1442 if (bmax == 1 && b[bmax] == 0)
1445 assert(amax == 0 || a[amax] != 0);
1446 assert(bmax == 0 || b[bmax] != 0);
1448 i = (amax > bmax ? amax : bmax);
1450 BignumInt aval = (i > amax ? 0 : a[i]);
1451 BignumInt bval = (i > bmax ? 0 : b[i]);
1462 * Right-shift one bignum to form another.
1464 Bignum bignum_rshift(Bignum a, int shift)
1467 int i, shiftw, shiftb, shiftbb, bits;
1472 bits = bignum_bitcount(a) - shift;
1473 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
1476 shiftw = shift / BIGNUM_INT_BITS;
1477 shiftb = shift % BIGNUM_INT_BITS;
1478 shiftbb = BIGNUM_INT_BITS - shiftb;
1480 ai1 = a[shiftw + 1];
1481 for (i = 1; i <= (int)ret[0]; i++) {
1483 ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);
1484 ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;
1492 * Left-shift one bignum to form another.
1494 Bignum bignum_lshift(Bignum a, int shift)
1497 int bits, shiftWords, shiftBits;
1501 bits = bignum_bitcount(a) + shift;
1502 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
1503 if (!ret) return NULL;
1505 shiftWords = shift / BIGNUM_INT_BITS;
1506 shiftBits = shift % BIGNUM_INT_BITS;
1510 memcpy(&ret[1 + shiftWords], &a[1], sizeof(BignumInt) * a[0]);
1515 BignumInt carry = 0;
1517 /* Remember that Bignum[0] is length, so add 1 */
1518 for (i = shiftWords + 1; i < ((int)a[0]) + shiftWords + 1; ++i)
1520 BignumInt from = a[i - shiftWords];
1521 ret[i] = (from << shiftBits) | carry;
1522 carry = from >> (BIGNUM_INT_BITS - shiftBits);
1524 if (carry) ret[i] = carry;
1531 * Non-modular multiplication and addition.
1533 Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
1535 int alen = a[0], blen = b[0];
1536 int mlen = (alen > blen ? alen : blen);
1537 int rlen, i, maxspot;
1539 BignumInt *workspace;
1542 /* mlen space for a, mlen space for b, 2*mlen for result,
1543 * plus scratch space for multiplication */
1544 wslen = mlen * 4 + mul_compute_scratch(mlen);
1545 workspace = snewn(wslen, BignumInt);
1546 for (i = 0; i < mlen; i++) {
1547 workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);
1548 workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);
1551 internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
1552 workspace + 2 * mlen, mlen, workspace + 4 * mlen);
1554 /* now just copy the result back */
1555 rlen = alen + blen + 1;
1556 if (addend && rlen <= (int)addend[0])
1557 rlen = addend[0] + 1;
1560 for (i = 1; i <= (int)ret[0]; i++) {
1561 ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
1567 /* now add in the addend, if any */
1569 BignumDblInt carry = 0;
1570 for (i = 1; i <= rlen; i++) {
1571 carry += (i <= (int)ret[0] ? ret[i] : 0);
1572 carry += (i <= (int)addend[0] ? addend[i] : 0);
1573 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1574 carry >>= BIGNUM_INT_BITS;
1575 if (ret[i] != 0 && i > maxspot)
1581 smemclr(workspace, wslen * sizeof(*workspace));
1587 * Non-modular multiplication.
1589 Bignum bigmul(Bignum a, Bignum b)
1591 return bigmuladd(a, b, NULL);
1597 Bignum bigadd(Bignum a, Bignum b)
1599 int alen = a[0], blen = b[0];
1600 int rlen = (alen > blen ? alen : blen) + 1;
1609 for (i = 1; i <= rlen; i++) {
1610 carry += (i <= (int)a[0] ? a[i] : 0);
1611 carry += (i <= (int)b[0] ? b[i] : 0);
1612 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1613 carry >>= BIGNUM_INT_BITS;
1614 if (ret[i] != 0 && i > maxspot)
1623 * Subtraction. Returns a-b, or NULL if the result would come out
1624 * negative (recall that this entire bignum module only handles
1625 * positive numbers).
1627 Bignum bigsub(Bignum a, Bignum b)
1629 int alen = a[0], blen = b[0];
1630 int rlen = (alen > blen ? alen : blen);
1639 for (i = 1; i <= rlen; i++) {
1640 carry += (i <= (int)a[0] ? a[i] : 0);
1641 carry += (i <= (int)b[0] ? b[i] ^ BIGNUM_INT_MASK : BIGNUM_INT_MASK);
1642 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1643 carry >>= BIGNUM_INT_BITS;
1644 if (ret[i] != 0 && i > maxspot)
1658 * Create a bignum which is the bitmask covering another one. That
1659 * is, the smallest integer which is >= N and is also one less than
1662 Bignum bignum_bitmask(Bignum n)
1664 Bignum ret = copybn(n);
1669 while (n[i] == 0 && i > 0)
1672 return ret; /* input was zero */
1678 ret[i] = BIGNUM_INT_MASK;
1683 * Convert a (max 32-bit) long into a bignum.
1685 Bignum bignum_from_long(unsigned long nn)
1688 BignumDblInt n = nn;
1691 ret[1] = (BignumInt)(n & BIGNUM_INT_MASK);
1692 ret[2] = (BignumInt)((n >> BIGNUM_INT_BITS) & BIGNUM_INT_MASK);
1694 ret[0] = (ret[2] ? 2 : 1);
1699 * Add a long to a bignum.
1701 Bignum bignum_add_long(Bignum number, unsigned long addendx)
1703 Bignum ret = newbn(number[0] + 1);
1705 BignumDblInt carry = 0, addend = addendx;
1707 for (i = 1; i <= (int)ret[0]; i++) {
1708 carry += addend & BIGNUM_INT_MASK;
1709 carry += (i <= (int)number[0] ? number[i] : 0);
1710 addend >>= BIGNUM_INT_BITS;
1711 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1712 carry >>= BIGNUM_INT_BITS;
1721 * Compute the residue of a bignum, modulo a (max 16-bit) short.
1723 unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
1725 BignumDblInt mod, r;
1730 for (i = number[0]; i > 0; i--)
1731 r = (r * (BIGNUM_TOP_BIT % mod) * 2 + number[i] % mod) % mod;
1732 return (unsigned short) r;
1736 void diagbn(char *prefix, Bignum md)
1738 int i, nibbles, morenibbles;
1739 static const char hex[] = "0123456789ABCDEF";
1741 debug(("%s0x", prefix ? prefix : ""));
1743 nibbles = (3 + bignum_bitcount(md)) / 4;
1746 morenibbles = 4 * md[0] - nibbles;
1747 for (i = 0; i < morenibbles; i++)
1749 for (i = nibbles; i--;)
1751 hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
1761 Bignum bigdiv(Bignum a, Bignum b)
1763 Bignum q = newbn(a[0]);
1764 bigdivmod(a, b, NULL, q);
1765 while (q[0] > 1 && q[q[0]] == 0)
1773 Bignum bigmod(Bignum a, Bignum b)
1775 Bignum r = newbn(b[0]);
1776 bigdivmod(a, b, r, NULL);
1777 while (r[0] > 1 && r[r[0]] == 0)
1783 * Greatest common divisor.
1785 Bignum biggcd(Bignum av, Bignum bv)
1787 Bignum a = copybn(av);
1788 Bignum b = copybn(bv);
1790 while (bignum_cmp(b, Zero) != 0) {
1791 Bignum t = newbn(b[0]);
1792 bigdivmod(a, b, t, NULL);
1793 while (t[0] > 1 && t[t[0]] == 0)
1805 * Modular inverse, using Euclid's extended algorithm.
1807 Bignum modinv(Bignum number, Bignum modulus)
1809 Bignum a = copybn(modulus);
1810 Bignum b = copybn(number);
1811 Bignum xp = copybn(Zero);
1812 Bignum x = copybn(One);
1815 assert(number[number[0]] != 0);
1816 assert(modulus[modulus[0]] != 0);
1818 while (bignum_cmp(b, One) != 0) {
1821 if (bignum_cmp(b, Zero) == 0) {
1823 * Found a common factor between the inputs, so we cannot
1824 * return a modular inverse at all.
1835 bigdivmod(a, b, t, q);
1836 while (t[0] > 1 && t[t[0]] == 0)
1838 while (q[0] > 1 && q[q[0]] == 0)
1845 x = bigmuladd(q, xp, t);
1855 /* now we know that sign * x == 1, and that x < modulus */
1857 /* set a new x to be modulus - x */
1858 Bignum newx = newbn(modulus[0]);
1859 BignumInt carry = 0;
1863 for (i = 1; i <= (int)newx[0]; i++) {
1864 BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);
1865 BignumInt bword = (i <= (int)x[0] ? x[i] : 0);
1866 newx[i] = aword - bword - carry;
1868 carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
1882 * Render a bignum into decimal. Return a malloced string holding
1883 * the decimal representation.
1885 char *bignum_decimal(Bignum x)
1887 int ndigits, ndigit;
1891 BignumInt *workspace;
1894 * First, estimate the number of digits. Since log(10)/log(2)
1895 * is just greater than 93/28 (the joys of continued fraction
1896 * approximations...) we know that for every 93 bits, we need
1897 * at most 28 digits. This will tell us how much to malloc.
1899 * Formally: if x has i bits, that means x is strictly less
1900 * than 2^i. Since 2 is less than 10^(28/93), this is less than
1901 * 10^(28i/93). We need an integer power of ten, so we must
1902 * round up (rounding down might make it less than x again).
1903 * Therefore if we multiply the bit count by 28/93, rounding
1904 * up, we will have enough digits.
1906 * i=0 (i.e., x=0) is an irritating special case.
1908 i = bignum_bitcount(x);
1910 ndigits = 1; /* x = 0 */
1912 ndigits = (28 * i + 92) / 93; /* multiply by 28/93 and round up */
1913 ndigits++; /* allow for trailing \0 */
1914 ret = snewn(ndigits, char);
1917 * Now allocate some workspace to hold the binary form as we
1918 * repeatedly divide it by ten. Initialise this to the
1919 * big-endian form of the number.
1921 workspace = snewn(x[0], BignumInt);
1922 for (i = 0; i < (int)x[0]; i++)
1923 workspace[i] = x[x[0] - i];
1926 * Next, write the decimal number starting with the last digit.
1927 * We use ordinary short division, dividing 10 into the
1930 ndigit = ndigits - 1;
1935 for (i = 0; i < (int)x[0]; i++) {
1936 carry = (carry << BIGNUM_INT_BITS) + workspace[i];
1937 workspace[i] = (BignumInt) (carry / 10);
1942 ret[--ndigit] = (char) (carry + '0');
1946 * There's a chance we've fallen short of the start of the
1947 * string. Correct if so.
1950 memmove(ret, ret + ndigit, ndigits - ndigit);
1955 smemclr(workspace, x[0] * sizeof(*workspace));
1967 * gcc -Wall -g -O0 -DTESTBN -o testbn sshbn.c misc.c conf.c tree234.c unix/uxmisc.c -I. -I unix -I charset
1969 * Then feed to this program's standard input the output of
1970 * testdata/bignum.py .
1973 void modalfatalbox(const char *p, ...)
1976 fprintf(stderr, "FATAL ERROR: ");
1978 vfprintf(stderr, p, ap);
1980 fputc('\n', stderr);
1984 #define fromxdigit(c) ( (c)>'9' ? ((c)&0xDF) - 'A' + 10 : (c) - '0' )
1986 int main(int argc, char **argv)
1990 int passes = 0, fails = 0;
1992 while ((buf = fgetline(stdin)) != NULL) {
1993 int maxlen = strlen(buf);
1994 unsigned char *data = snewn(maxlen, unsigned char);
1995 unsigned char *ptrs[5], *q;
2004 while (*bufp && !isspace((unsigned char)*bufp))
2013 while (*bufp && !isxdigit((unsigned char)*bufp))
2020 while (*bufp && isxdigit((unsigned char)*bufp))
2024 if (ptrnum >= lenof(ptrs))
2028 for (i = -((end - start) & 1); i < end-start; i += 2) {
2029 unsigned char val = (i < 0 ? 0 : fromxdigit(start[i]));
2030 val = val * 16 + fromxdigit(start[i+1]);
2037 if (!strcmp(buf, "mul")) {
2041 printf("%d: mul with %d parameters, expected 3\n", line, ptrnum);
2044 a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
2045 b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
2046 c = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
2049 if (bignum_cmp(c, p) == 0) {
2052 char *as = bignum_decimal(a);
2053 char *bs = bignum_decimal(b);
2054 char *cs = bignum_decimal(c);
2055 char *ps = bignum_decimal(p);
2057 printf("%d: fail: %s * %s gave %s expected %s\n",
2058 line, as, bs, ps, cs);
2070 } else if (!strcmp(buf, "modmul")) {
2071 Bignum a, b, m, c, p;
2074 printf("%d: modmul with %d parameters, expected 4\n",
2078 a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
2079 b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
2080 m = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
2081 c = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);
2082 p = modmul(a, b, m);
2084 if (bignum_cmp(c, p) == 0) {
2087 char *as = bignum_decimal(a);
2088 char *bs = bignum_decimal(b);
2089 char *ms = bignum_decimal(m);
2090 char *cs = bignum_decimal(c);
2091 char *ps = bignum_decimal(p);
2093 printf("%d: fail: %s * %s mod %s gave %s expected %s\n",
2094 line, as, bs, ms, ps, cs);
2108 } else if (!strcmp(buf, "pow")) {
2109 Bignum base, expt, modulus, expected, answer;
2112 printf("%d: mul with %d parameters, expected 4\n", line, ptrnum);
2116 base = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
2117 expt = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
2118 modulus = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
2119 expected = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);
2120 answer = modpow(base, expt, modulus);
2122 if (bignum_cmp(expected, answer) == 0) {
2125 char *as = bignum_decimal(base);
2126 char *bs = bignum_decimal(expt);
2127 char *cs = bignum_decimal(modulus);
2128 char *ds = bignum_decimal(answer);
2129 char *ps = bignum_decimal(expected);
2131 printf("%d: fail: %s ^ %s mod %s gave %s expected %s\n",
2132 line, as, bs, cs, ds, ps);
2147 printf("%d: unrecognised test keyword: '%s'\n", line, buf);
2155 printf("passed %d failed %d total %d\n", passes, fails, passes+fails);