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 /* 64-bit architectures can do 32x32->64 chunks at a time */
56 typedef unsigned int BignumInt;
57 typedef unsigned long BignumDblInt;
58 #define BIGNUM_INT_MASK 0xFFFFFFFFU
59 #define BIGNUM_TOP_BIT 0x80000000U
60 #define BIGNUM_INT_BITS 32
61 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
62 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
63 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
68 /* 64-bit architectures in which unsigned long is 32 bits, not 64 */
69 typedef unsigned long BignumInt;
70 typedef unsigned long long BignumDblInt;
71 #define BIGNUM_INT_MASK 0xFFFFFFFFUL
72 #define BIGNUM_TOP_BIT 0x80000000UL
73 #define BIGNUM_INT_BITS 32
74 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
75 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
76 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
81 /* Fallback for all other cases */
82 typedef unsigned short BignumInt;
83 typedef unsigned long BignumDblInt;
84 #define BIGNUM_INT_MASK 0xFFFFU
85 #define BIGNUM_TOP_BIT 0x8000U
86 #define BIGNUM_INT_BITS 16
87 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
88 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
89 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
95 #define BIGNUM_INT_BYTES (BIGNUM_INT_BITS / 8)
97 #define BIGNUM_INTERNAL
98 typedef BignumInt *Bignum;
102 BignumInt bnZero[1] = { 0 };
103 BignumInt bnOne[2] = { 1, 1 };
106 * The Bignum format is an array of `BignumInt'. The first
107 * element of the array counts the remaining elements. The
108 * remaining elements express the actual number, base 2^BIGNUM_INT_BITS, _least_
109 * significant digit first. (So it's trivial to extract the bit
110 * with value 2^n for any n.)
112 * All Bignums in this module are positive. Negative numbers must
113 * be dealt with outside it.
115 * INVARIANT: the most significant word of any Bignum must be
119 Bignum Zero = bnZero, One = bnOne;
121 static Bignum newbn(int length)
123 Bignum b = snewn(length + 1, BignumInt);
126 memset(b, 0, (length + 1) * sizeof(*b));
131 void bn_restore_invariant(Bignum b)
133 while (b[0] > 1 && b[b[0]] == 0)
137 Bignum copybn(Bignum orig)
139 Bignum b = snewn(orig[0] + 1, BignumInt);
142 memcpy(b, orig, (orig[0] + 1) * sizeof(*b));
146 void freebn(Bignum b)
149 * Burn the evidence, just in case.
151 memset(b, 0, sizeof(b[0]) * (b[0] + 1));
155 Bignum bn_power_2(int n)
157 Bignum ret = newbn(n / BIGNUM_INT_BITS + 1);
158 bignum_set_bit(ret, n, 1);
163 * Internal addition. Sets c = a - b, where 'a', 'b' and 'c' are all
164 * big-endian arrays of 'len' BignumInts. Returns a BignumInt carried
167 static BignumInt internal_add(const BignumInt *a, const BignumInt *b,
168 BignumInt *c, int len)
171 BignumDblInt carry = 0;
173 for (i = len-1; i >= 0; i--) {
174 carry += (BignumDblInt)a[i] + b[i];
175 c[i] = (BignumInt)carry;
176 carry >>= BIGNUM_INT_BITS;
179 return (BignumInt)carry;
183 * Internal subtraction. Sets c = a - b, where 'a', 'b' and 'c' are
184 * all big-endian arrays of 'len' BignumInts. Any borrow from the top
187 static void internal_sub(const BignumInt *a, const BignumInt *b,
188 BignumInt *c, int len)
191 BignumDblInt carry = 1;
193 for (i = len-1; i >= 0; i--) {
194 carry += (BignumDblInt)a[i] + (b[i] ^ BIGNUM_INT_MASK);
195 c[i] = (BignumInt)carry;
196 carry >>= BIGNUM_INT_BITS;
202 * Input is in the first len words of a and b.
203 * Result is returned in the first 2*len words of c.
205 * 'scratch' must point to an array of BignumInt of size at least
206 * mul_compute_scratch(len). (This covers the needs of internal_mul
207 * and all its recursive calls to itself.)
209 #define KARATSUBA_THRESHOLD 50
210 static int mul_compute_scratch(int len)
213 while (len > KARATSUBA_THRESHOLD) {
214 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
215 int midlen = botlen + 1;
221 static void internal_mul(const BignumInt *a, const BignumInt *b,
222 BignumInt *c, int len, BignumInt *scratch)
227 if (len > KARATSUBA_THRESHOLD) {
230 * Karatsuba divide-and-conquer algorithm. Cut each input in
231 * half, so that it's expressed as two big 'digits' in a giant
237 * Then the product is of course
239 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
241 * and we compute the three coefficients by recursively
242 * calling ourself to do half-length multiplications.
244 * The clever bit that makes this worth doing is that we only
245 * need _one_ half-length multiplication for the central
246 * coefficient rather than the two that it obviouly looks
247 * like, because we can use a single multiplication to compute
249 * (a_1 + a_0) (b_1 + b_0) = a_1 b_1 + a_1 b_0 + a_0 b_1 + a_0 b_0
251 * and then we subtract the other two coefficients (a_1 b_1
252 * and a_0 b_0) which we were computing anyway.
254 * Hence we get to multiply two numbers of length N in about
255 * three times as much work as it takes to multiply numbers of
256 * length N/2, which is obviously better than the four times
257 * as much work it would take if we just did a long
258 * conventional multiply.
261 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
262 int midlen = botlen + 1;
269 * The coefficients a_1 b_1 and a_0 b_0 just avoid overlapping
270 * in the output array, so we can compute them immediately in
275 printf("a1,a0 = 0x");
276 for (i = 0; i < len; i++) {
277 if (i == toplen) printf(", 0x");
278 printf("%0*x", BIGNUM_INT_BITS/4, a[i]);
281 printf("b1,b0 = 0x");
282 for (i = 0; i < len; i++) {
283 if (i == toplen) printf(", 0x");
284 printf("%0*x", BIGNUM_INT_BITS/4, b[i]);
290 internal_mul(a, b, c, toplen, scratch);
293 for (i = 0; i < 2*toplen; i++) {
294 printf("%0*x", BIGNUM_INT_BITS/4, c[i]);
300 internal_mul(a + toplen, b + toplen, c + 2*toplen, botlen, scratch);
303 for (i = 0; i < 2*botlen; i++) {
304 printf("%0*x", BIGNUM_INT_BITS/4, c[2*toplen+i]);
309 /* Zero padding. midlen exceeds toplen by at most 2, so just
310 * zero the first two words of each input and the rest will be
312 scratch[0] = scratch[1] = scratch[midlen] = scratch[midlen+1] = 0;
314 for (j = 0; j < toplen; j++) {
315 scratch[midlen - toplen + j] = a[j]; /* a_1 */
316 scratch[2*midlen - toplen + j] = b[j]; /* b_1 */
319 /* compute a_1 + a_0 */
320 scratch[0] = internal_add(scratch+1, a+toplen, scratch+1, botlen);
322 printf("a1plusa0 = 0x");
323 for (i = 0; i < midlen; i++) {
324 printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);
328 /* compute b_1 + b_0 */
329 scratch[midlen] = internal_add(scratch+midlen+1, b+toplen,
330 scratch+midlen+1, botlen);
332 printf("b1plusb0 = 0x");
333 for (i = 0; i < midlen; i++) {
334 printf("%0*x", BIGNUM_INT_BITS/4, scratch[midlen+i]);
340 * Now we can do the third multiplication.
342 internal_mul(scratch, scratch + midlen, scratch + 2*midlen, midlen,
345 printf("a1plusa0timesb1plusb0 = 0x");
346 for (i = 0; i < 2*midlen; i++) {
347 printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);
353 * Now we can reuse the first half of 'scratch' to compute the
354 * sum of the outer two coefficients, to subtract from that
355 * product to obtain the middle one.
357 scratch[0] = scratch[1] = scratch[2] = scratch[3] = 0;
358 for (j = 0; j < 2*toplen; j++)
359 scratch[2*midlen - 2*toplen + j] = c[j];
360 scratch[1] = internal_add(scratch+2, c + 2*toplen,
361 scratch+2, 2*botlen);
363 printf("a1b1plusa0b0 = 0x");
364 for (i = 0; i < 2*midlen; i++) {
365 printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);
370 internal_sub(scratch + 2*midlen, scratch,
371 scratch + 2*midlen, 2*midlen);
373 printf("a1b0plusa0b1 = 0x");
374 for (i = 0; i < 2*midlen; i++) {
375 printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);
381 * And now all we need to do is to add that middle coefficient
382 * back into the output. We may have to propagate a carry
383 * further up the output, but we can be sure it won't
384 * propagate right the way off the top.
386 carry = internal_add(c + 2*len - botlen - 2*midlen,
388 c + 2*len - botlen - 2*midlen, 2*midlen);
389 j = 2*len - botlen - 2*midlen - 1;
393 c[j] = (BignumInt)carry;
394 carry >>= BIGNUM_INT_BITS;
399 for (i = 0; i < 2*len; i++) {
400 printf("%0*x", BIGNUM_INT_BITS/4, c[i]);
408 * Multiply in the ordinary O(N^2) way.
411 for (j = 0; j < 2 * len; j++)
414 for (i = len - 1; i >= 0; i--) {
416 for (j = len - 1; j >= 0; j--) {
417 t += MUL_WORD(a[i], (BignumDblInt) b[j]);
418 t += (BignumDblInt) c[i + j + 1];
419 c[i + j + 1] = (BignumInt) t;
420 t = t >> BIGNUM_INT_BITS;
422 c[i] = (BignumInt) t;
428 * Variant form of internal_mul used for the initial step of
429 * Montgomery reduction. Only bothers outputting 'len' words
430 * (everything above that is thrown away).
432 static void internal_mul_low(const BignumInt *a, const BignumInt *b,
433 BignumInt *c, int len, BignumInt *scratch)
438 if (len > KARATSUBA_THRESHOLD) {
441 * Karatsuba-aware version of internal_mul_low. As before, we
442 * express each input value as a shifted combination of two
448 * Then the full product is, as before,
450 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
452 * Provided we choose D on the large side (so that a_0 and b_0
453 * are _at least_ as long as a_1 and b_1), we don't need the
454 * topmost term at all, and we only need half of the middle
455 * term. So there's no point in doing the proper Karatsuba
456 * optimisation which computes the middle term using the top
457 * one, because we'd take as long computing the top one as
458 * just computing the middle one directly.
460 * So instead, we do a much more obvious thing: we call the
461 * fully optimised internal_mul to compute a_0 b_0, and we
462 * recursively call ourself to compute the _bottom halves_ of
463 * a_1 b_0 and a_0 b_1, each of which we add into the result
464 * in the obvious way.
466 * In other words, there's no actual Karatsuba _optimisation_
467 * in this function; the only benefit in doing it this way is
468 * that we call internal_mul proper for a large part of the
469 * work, and _that_ can optimise its operation.
472 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
475 * Scratch space for the various bits and pieces we're going
476 * to be adding together: we need botlen*2 words for a_0 b_0
477 * (though we may end up throwing away its topmost word), and
478 * toplen words for each of a_1 b_0 and a_0 b_1. That adds up
483 internal_mul(a + toplen, b + toplen, scratch + 2*toplen, botlen,
487 internal_mul_low(a, b + len - toplen, scratch + toplen, toplen,
491 internal_mul_low(a + len - toplen, b, scratch, toplen,
494 /* Copy the bottom half of the big coefficient into place */
495 for (j = 0; j < botlen; j++)
496 c[toplen + j] = scratch[2*toplen + botlen + j];
498 /* Add the two small coefficients, throwing away the returned carry */
499 internal_add(scratch, scratch + toplen, scratch, toplen);
501 /* And add that to the large coefficient, leaving the result in c. */
502 internal_add(scratch, scratch + 2*toplen + botlen - toplen,
507 for (j = 0; j < len; j++)
510 for (i = len - 1; i >= 0; i--) {
512 for (j = len - 1; j >= len - i - 1; j--) {
513 t += MUL_WORD(a[i], (BignumDblInt) b[j]);
514 t += (BignumDblInt) c[i + j + 1 - len];
515 c[i + j + 1 - len] = (BignumInt) t;
516 t = t >> BIGNUM_INT_BITS;
524 * Montgomery reduction. Expects x to be a big-endian array of 2*len
525 * BignumInts whose value satisfies 0 <= x < rn (where r = 2^(len *
526 * BIGNUM_INT_BITS) is the Montgomery base). Returns in the same array
527 * a value x' which is congruent to xr^{-1} mod n, and satisfies 0 <=
530 * 'n' and 'mninv' should be big-endian arrays of 'len' BignumInts
531 * each, containing respectively n and the multiplicative inverse of
534 * 'tmp' is an array of BignumInt used as scratch space, of length at
535 * least 3*len + mul_compute_scratch(len).
537 static void monty_reduce(BignumInt *x, const BignumInt *n,
538 const BignumInt *mninv, BignumInt *tmp, int len)
544 * Multiply x by (-n)^{-1} mod r. This gives us a value m such
545 * that mn is congruent to -x mod r. Hence, mn+x is an exact
546 * multiple of r, and is also (obviously) congruent to x mod n.
548 internal_mul_low(x + len, mninv, tmp, len, tmp + 3*len);
551 * Compute t = (mn+x)/r in ordinary, non-modular, integer
552 * arithmetic. By construction this is exact, and is congruent mod
553 * n to x * r^{-1}, i.e. the answer we want.
555 * The following multiply leaves that answer in the _most_
556 * significant half of the 'x' array, so then we must shift it
559 internal_mul(tmp, n, tmp+len, len, tmp + 3*len);
560 carry = internal_add(x, tmp+len, x, 2*len);
561 for (i = 0; i < len; i++)
562 x[len + i] = x[i], x[i] = 0;
565 * Reduce t mod n. This doesn't require a full-on division by n,
566 * but merely a test and single optional subtraction, since we can
567 * show that 0 <= t < 2n.
570 * + we computed m mod r, so 0 <= m < r.
571 * + so 0 <= mn < rn, obviously
572 * + hence we only need 0 <= x < rn to guarantee that 0 <= mn+x < 2rn
573 * + yielding 0 <= (mn+x)/r < 2n as required.
576 for (i = 0; i < len; i++)
577 if (x[len + i] != n[i])
580 if (carry || i >= len || x[len + i] > n[i])
581 internal_sub(x+len, n, x+len, len);
584 static void internal_add_shifted(BignumInt *number,
585 unsigned n, int shift)
587 int word = 1 + (shift / BIGNUM_INT_BITS);
588 int bshift = shift % BIGNUM_INT_BITS;
591 addend = (BignumDblInt)n << bshift;
594 addend += number[word];
595 number[word] = (BignumInt) addend & BIGNUM_INT_MASK;
596 addend >>= BIGNUM_INT_BITS;
603 * Input in first alen words of a and first mlen words of m.
604 * Output in first alen words of a
605 * (of which first alen-mlen words will be zero).
606 * The MSW of m MUST have its high bit set.
607 * Quotient is accumulated in the `quotient' array, which is a Bignum
608 * rather than the internal bigendian format. Quotient parts are shifted
609 * left by `qshift' before adding into quot.
611 static void internal_mod(BignumInt *a, int alen,
612 BignumInt *m, int mlen,
613 BignumInt *quot, int qshift)
625 for (i = 0; i <= alen - mlen; i++) {
627 unsigned int q, r, c, ai1;
641 /* Find q = h:a[i] / m0 */
646 * To illustrate it, suppose a BignumInt is 8 bits, and
647 * we are dividing (say) A1:23:45:67 by A1:B2:C3. Then
648 * our initial division will be 0xA123 / 0xA1, which
649 * will give a quotient of 0x100 and a divide overflow.
650 * However, the invariants in this division algorithm
651 * are not violated, since the full number A1:23:... is
652 * _less_ than the quotient prefix A1:B2:... and so the
653 * following correction loop would have sorted it out.
655 * In this situation we set q to be the largest
656 * quotient we _can_ stomach (0xFF, of course).
660 /* Macro doesn't want an array subscript expression passed
661 * into it (see definition), so use a temporary. */
662 BignumInt tmplo = a[i];
663 DIVMOD_WORD(q, r, h, tmplo, m0);
665 /* Refine our estimate of q by looking at
666 h:a[i]:a[i+1] / m0:m1 */
668 if (t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) {
671 r = (r + m0) & BIGNUM_INT_MASK; /* overflow? */
672 if (r >= (BignumDblInt) m0 &&
673 t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) q--;
677 /* Subtract q * m from a[i...] */
679 for (k = mlen - 1; k >= 0; k--) {
680 t = MUL_WORD(q, m[k]);
682 c = (unsigned)(t >> BIGNUM_INT_BITS);
683 if ((BignumInt) t > a[i + k])
685 a[i + k] -= (BignumInt) t;
688 /* Add back m in case of borrow */
691 for (k = mlen - 1; k >= 0; k--) {
694 a[i + k] = (BignumInt) t;
695 t = t >> BIGNUM_INT_BITS;
700 internal_add_shifted(quot, q, qshift + BIGNUM_INT_BITS * (alen - mlen - i));
705 * Compute (base ^ exp) % mod, the pedestrian way.
707 Bignum modpow_simple(Bignum base_in, Bignum exp, Bignum mod)
709 BignumInt *a, *b, *n, *m, *scratch;
711 int mlen, scratchlen, i, j;
715 * The most significant word of mod needs to be non-zero. It
716 * should already be, but let's make sure.
718 assert(mod[mod[0]] != 0);
721 * Make sure the base is smaller than the modulus, by reducing
722 * it modulo the modulus if not.
724 base = bigmod(base_in, mod);
726 /* Allocate m of size mlen, copy mod to m */
727 /* We use big endian internally */
729 m = snewn(mlen, BignumInt);
730 for (j = 0; j < mlen; j++)
731 m[j] = mod[mod[0] - j];
733 /* Shift m left to make msb bit set */
734 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
735 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
738 for (i = 0; i < mlen - 1; i++)
739 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
740 m[mlen - 1] = m[mlen - 1] << mshift;
743 /* Allocate n of size mlen, copy base to n */
744 n = snewn(mlen, BignumInt);
746 for (j = 0; j < i; j++)
748 for (j = 0; j < (int)base[0]; j++)
749 n[i + j] = base[base[0] - j];
751 /* Allocate a and b of size 2*mlen. Set a = 1 */
752 a = snewn(2 * mlen, BignumInt);
753 b = snewn(2 * mlen, BignumInt);
754 for (i = 0; i < 2 * mlen; i++)
758 /* Scratch space for multiplies */
759 scratchlen = mul_compute_scratch(mlen);
760 scratch = snewn(scratchlen, BignumInt);
762 /* Skip leading zero bits of exp. */
764 j = BIGNUM_INT_BITS-1;
765 while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
769 j = BIGNUM_INT_BITS-1;
773 /* Main computation */
774 while (i < (int)exp[0]) {
776 internal_mul(a + mlen, a + mlen, b, mlen, scratch);
777 internal_mod(b, mlen * 2, m, mlen, NULL, 0);
778 if ((exp[exp[0] - i] & (1 << j)) != 0) {
779 internal_mul(b + mlen, n, a, mlen, scratch);
780 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
790 j = BIGNUM_INT_BITS-1;
793 /* Fixup result in case the modulus was shifted */
795 for (i = mlen - 1; i < 2 * mlen - 1; i++)
796 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
797 a[2 * mlen - 1] = a[2 * mlen - 1] << mshift;
798 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
799 for (i = 2 * mlen - 1; i >= mlen; i--)
800 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
803 /* Copy result to buffer */
804 result = newbn(mod[0]);
805 for (i = 0; i < mlen; i++)
806 result[result[0] - i] = a[i + mlen];
807 while (result[0] > 1 && result[result[0]] == 0)
810 /* Free temporary arrays */
811 for (i = 0; i < 2 * mlen; i++)
814 for (i = 0; i < scratchlen; i++)
817 for (i = 0; i < 2 * mlen; i++)
820 for (i = 0; i < mlen; i++)
823 for (i = 0; i < mlen; i++)
833 * Compute (base ^ exp) % mod. Uses the Montgomery multiplication
834 * technique where possible, falling back to modpow_simple otherwise.
836 Bignum modpow(Bignum base_in, Bignum exp, Bignum mod)
838 BignumInt *a, *b, *x, *n, *mninv, *scratch;
839 int len, scratchlen, i, j;
840 Bignum base, base2, r, rn, inv, result;
843 * The most significant word of mod needs to be non-zero. It
844 * should already be, but let's make sure.
846 assert(mod[mod[0]] != 0);
849 * mod had better be odd, or we can't do Montgomery multiplication
850 * using a power of two at all.
853 return modpow_simple(base_in, exp, mod);
856 * Make sure the base is smaller than the modulus, by reducing
857 * it modulo the modulus if not.
859 base = bigmod(base_in, mod);
862 * Compute the inverse of n mod r, for monty_reduce. (In fact we
863 * want the inverse of _minus_ n mod r, but we'll sort that out
867 r = bn_power_2(BIGNUM_INT_BITS * len);
868 inv = modinv(mod, r);
871 * Multiply the base by r mod n, to get it into Montgomery
874 base2 = modmul(base, r, mod);
878 rn = bigmod(r, mod); /* r mod n, i.e. Montgomerified 1 */
880 freebn(r); /* won't need this any more */
883 * Set up internal arrays of the right lengths, in big-endian
884 * format, containing the base, the modulus, and the modulus's
887 n = snewn(len, BignumInt);
888 for (j = 0; j < len; j++)
889 n[len - 1 - j] = mod[j + 1];
891 mninv = snewn(len, BignumInt);
892 for (j = 0; j < len; j++)
893 mninv[len - 1 - j] = (j < inv[0] ? inv[j + 1] : 0);
894 freebn(inv); /* we don't need this copy of it any more */
895 /* Now negate mninv mod r, so it's the inverse of -n rather than +n. */
896 x = snewn(len, BignumInt);
897 for (j = 0; j < len; j++)
899 internal_sub(x, mninv, mninv, len);
901 /* x = snewn(len, BignumInt); */ /* already done above */
902 for (j = 0; j < len; j++)
903 x[len - 1 - j] = (j < base[0] ? base[j + 1] : 0);
904 freebn(base); /* we don't need this copy of it any more */
906 a = snewn(2*len, BignumInt);
907 b = snewn(2*len, BignumInt);
908 for (j = 0; j < len; j++)
909 a[2*len - 1 - j] = (j < rn[0] ? rn[j + 1] : 0);
912 /* Scratch space for multiplies */
913 scratchlen = 3*len + mul_compute_scratch(len);
914 scratch = snewn(scratchlen, BignumInt);
916 /* Skip leading zero bits of exp. */
918 j = BIGNUM_INT_BITS-1;
919 while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
923 j = BIGNUM_INT_BITS-1;
927 /* Main computation */
928 while (i < (int)exp[0]) {
930 internal_mul(a + len, a + len, b, len, scratch);
931 monty_reduce(b, n, mninv, scratch, len);
932 if ((exp[exp[0] - i] & (1 << j)) != 0) {
933 internal_mul(b + len, x, a, len, scratch);
934 monty_reduce(a, n, mninv, scratch, len);
944 j = BIGNUM_INT_BITS-1;
948 * Final monty_reduce to get back from the adjusted Montgomery
951 monty_reduce(a, n, mninv, scratch, len);
953 /* Copy result to buffer */
954 result = newbn(mod[0]);
955 for (i = 0; i < len; i++)
956 result[result[0] - i] = a[i + len];
957 while (result[0] > 1 && result[result[0]] == 0)
960 /* Free temporary arrays */
961 for (i = 0; i < scratchlen; i++)
964 for (i = 0; i < 2 * len; i++)
967 for (i = 0; i < 2 * len; i++)
970 for (i = 0; i < len; i++)
973 for (i = 0; i < len; i++)
976 for (i = 0; i < len; i++)
984 * Compute (p * q) % mod.
985 * The most significant word of mod MUST be non-zero.
986 * We assume that the result array is the same size as the mod array.
988 Bignum modmul(Bignum p, Bignum q, Bignum mod)
990 BignumInt *a, *n, *m, *o, *scratch;
991 int mshift, scratchlen;
992 int pqlen, mlen, rlen, i, j;
995 /* Allocate m of size mlen, copy mod to m */
996 /* We use big endian internally */
998 m = snewn(mlen, BignumInt);
999 for (j = 0; j < mlen; j++)
1000 m[j] = mod[mod[0] - j];
1002 /* Shift m left to make msb bit set */
1003 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
1004 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
1007 for (i = 0; i < mlen - 1; i++)
1008 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
1009 m[mlen - 1] = m[mlen - 1] << mshift;
1012 pqlen = (p[0] > q[0] ? p[0] : q[0]);
1014 /* Allocate n of size pqlen, copy p to n */
1015 n = snewn(pqlen, BignumInt);
1017 for (j = 0; j < i; j++)
1019 for (j = 0; j < (int)p[0]; j++)
1020 n[i + j] = p[p[0] - j];
1022 /* Allocate o of size pqlen, copy q to o */
1023 o = snewn(pqlen, BignumInt);
1025 for (j = 0; j < i; j++)
1027 for (j = 0; j < (int)q[0]; j++)
1028 o[i + j] = q[q[0] - j];
1030 /* Allocate a of size 2*pqlen for result */
1031 a = snewn(2 * pqlen, BignumInt);
1033 /* Scratch space for multiplies */
1034 scratchlen = mul_compute_scratch(pqlen);
1035 scratch = snewn(scratchlen, BignumInt);
1037 /* Main computation */
1038 internal_mul(n, o, a, pqlen, scratch);
1039 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
1041 /* Fixup result in case the modulus was shifted */
1043 for (i = 2 * pqlen - mlen - 1; i < 2 * pqlen - 1; i++)
1044 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
1045 a[2 * pqlen - 1] = a[2 * pqlen - 1] << mshift;
1046 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
1047 for (i = 2 * pqlen - 1; i >= 2 * pqlen - mlen; i--)
1048 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
1051 /* Copy result to buffer */
1052 rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
1053 result = newbn(rlen);
1054 for (i = 0; i < rlen; i++)
1055 result[result[0] - i] = a[i + 2 * pqlen - rlen];
1056 while (result[0] > 1 && result[result[0]] == 0)
1059 /* Free temporary arrays */
1060 for (i = 0; i < scratchlen; i++)
1063 for (i = 0; i < 2 * pqlen; i++)
1066 for (i = 0; i < mlen; i++)
1069 for (i = 0; i < pqlen; i++)
1072 for (i = 0; i < pqlen; i++)
1081 * The most significant word of mod MUST be non-zero.
1082 * We assume that the result array is the same size as the mod array.
1083 * We optionally write out a quotient if `quotient' is non-NULL.
1084 * We can avoid writing out the result if `result' is NULL.
1086 static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
1090 int plen, mlen, i, j;
1092 /* Allocate m of size mlen, copy mod to m */
1093 /* We use big endian internally */
1095 m = snewn(mlen, BignumInt);
1096 for (j = 0; j < mlen; j++)
1097 m[j] = mod[mod[0] - j];
1099 /* Shift m left to make msb bit set */
1100 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
1101 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
1104 for (i = 0; i < mlen - 1; i++)
1105 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
1106 m[mlen - 1] = m[mlen - 1] << mshift;
1110 /* Ensure plen > mlen */
1114 /* Allocate n of size plen, copy p to n */
1115 n = snewn(plen, BignumInt);
1116 for (j = 0; j < plen; j++)
1118 for (j = 1; j <= (int)p[0]; j++)
1121 /* Main computation */
1122 internal_mod(n, plen, m, mlen, quotient, mshift);
1124 /* Fixup result in case the modulus was shifted */
1126 for (i = plen - mlen - 1; i < plen - 1; i++)
1127 n[i] = (n[i] << mshift) | (n[i + 1] >> (BIGNUM_INT_BITS - mshift));
1128 n[plen - 1] = n[plen - 1] << mshift;
1129 internal_mod(n, plen, m, mlen, quotient, 0);
1130 for (i = plen - 1; i >= plen - mlen; i--)
1131 n[i] = (n[i] >> mshift) | (n[i - 1] << (BIGNUM_INT_BITS - mshift));
1134 /* Copy result to buffer */
1136 for (i = 1; i <= (int)result[0]; i++) {
1138 result[i] = j >= 0 ? n[j] : 0;
1142 /* Free temporary arrays */
1143 for (i = 0; i < mlen; i++)
1146 for (i = 0; i < plen; i++)
1152 * Decrement a number.
1154 void decbn(Bignum bn)
1157 while (i < (int)bn[0] && bn[i] == 0)
1158 bn[i++] = BIGNUM_INT_MASK;
1162 Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
1167 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
1170 for (i = 1; i <= w; i++)
1172 for (i = nbytes; i--;) {
1173 unsigned char byte = *data++;
1174 result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);
1177 while (result[0] > 1 && result[result[0]] == 0)
1183 * Read an SSH-1-format bignum from a data buffer. Return the number
1184 * of bytes consumed, or -1 if there wasn't enough data.
1186 int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)
1188 const unsigned char *p = data;
1196 for (i = 0; i < 2; i++)
1197 w = (w << 8) + *p++;
1198 b = (w + 7) / 8; /* bits -> bytes */
1203 if (!result) /* just return length */
1206 *result = bignum_from_bytes(p, b);
1208 return p + b - data;
1212 * Return the bit count of a bignum, for SSH-1 encoding.
1214 int bignum_bitcount(Bignum bn)
1216 int bitcount = bn[0] * BIGNUM_INT_BITS - 1;
1217 while (bitcount >= 0
1218 && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;
1219 return bitcount + 1;
1223 * Return the byte length of a bignum when SSH-1 encoded.
1225 int ssh1_bignum_length(Bignum bn)
1227 return 2 + (bignum_bitcount(bn) + 7) / 8;
1231 * Return the byte length of a bignum when SSH-2 encoded.
1233 int ssh2_bignum_length(Bignum bn)
1235 return 4 + (bignum_bitcount(bn) + 8) / 8;
1239 * Return a byte from a bignum; 0 is least significant, etc.
1241 int bignum_byte(Bignum bn, int i)
1243 if (i >= (int)(BIGNUM_INT_BYTES * bn[0]))
1244 return 0; /* beyond the end */
1246 return (bn[i / BIGNUM_INT_BYTES + 1] >>
1247 ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;
1251 * Return a bit from a bignum; 0 is least significant, etc.
1253 int bignum_bit(Bignum bn, int i)
1255 if (i >= (int)(BIGNUM_INT_BITS * bn[0]))
1256 return 0; /* beyond the end */
1258 return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;
1262 * Set a bit in a bignum; 0 is least significant, etc.
1264 void bignum_set_bit(Bignum bn, int bitnum, int value)
1266 if (bitnum >= (int)(BIGNUM_INT_BITS * bn[0]))
1267 abort(); /* beyond the end */
1269 int v = bitnum / BIGNUM_INT_BITS + 1;
1270 int mask = 1 << (bitnum % BIGNUM_INT_BITS);
1279 * Write a SSH-1-format bignum into a buffer. It is assumed the
1280 * buffer is big enough. Returns the number of bytes used.
1282 int ssh1_write_bignum(void *data, Bignum bn)
1284 unsigned char *p = data;
1285 int len = ssh1_bignum_length(bn);
1287 int bitc = bignum_bitcount(bn);
1289 *p++ = (bitc >> 8) & 0xFF;
1290 *p++ = (bitc) & 0xFF;
1291 for (i = len - 2; i--;)
1292 *p++ = bignum_byte(bn, i);
1297 * Compare two bignums. Returns like strcmp.
1299 int bignum_cmp(Bignum a, Bignum b)
1301 int amax = a[0], bmax = b[0];
1302 int i = (amax > bmax ? amax : bmax);
1304 BignumInt aval = (i > amax ? 0 : a[i]);
1305 BignumInt bval = (i > bmax ? 0 : b[i]);
1316 * Right-shift one bignum to form another.
1318 Bignum bignum_rshift(Bignum a, int shift)
1321 int i, shiftw, shiftb, shiftbb, bits;
1324 bits = bignum_bitcount(a) - shift;
1325 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
1328 shiftw = shift / BIGNUM_INT_BITS;
1329 shiftb = shift % BIGNUM_INT_BITS;
1330 shiftbb = BIGNUM_INT_BITS - shiftb;
1332 ai1 = a[shiftw + 1];
1333 for (i = 1; i <= (int)ret[0]; i++) {
1335 ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);
1336 ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;
1344 * Non-modular multiplication and addition.
1346 Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
1348 int alen = a[0], blen = b[0];
1349 int mlen = (alen > blen ? alen : blen);
1350 int rlen, i, maxspot;
1352 BignumInt *workspace;
1355 /* mlen space for a, mlen space for b, 2*mlen for result,
1356 * plus scratch space for multiplication */
1357 wslen = mlen * 4 + mul_compute_scratch(mlen);
1358 workspace = snewn(wslen, BignumInt);
1359 for (i = 0; i < mlen; i++) {
1360 workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);
1361 workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);
1364 internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
1365 workspace + 2 * mlen, mlen, workspace + 4 * mlen);
1367 /* now just copy the result back */
1368 rlen = alen + blen + 1;
1369 if (addend && rlen <= (int)addend[0])
1370 rlen = addend[0] + 1;
1373 for (i = 1; i <= (int)ret[0]; i++) {
1374 ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
1380 /* now add in the addend, if any */
1382 BignumDblInt carry = 0;
1383 for (i = 1; i <= rlen; i++) {
1384 carry += (i <= (int)ret[0] ? ret[i] : 0);
1385 carry += (i <= (int)addend[0] ? addend[i] : 0);
1386 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1387 carry >>= BIGNUM_INT_BITS;
1388 if (ret[i] != 0 && i > maxspot)
1394 for (i = 0; i < wslen; i++)
1401 * Non-modular multiplication.
1403 Bignum bigmul(Bignum a, Bignum b)
1405 return bigmuladd(a, b, NULL);
1411 Bignum bigadd(Bignum a, Bignum b)
1413 int alen = a[0], blen = b[0];
1414 int rlen = (alen > blen ? alen : blen) + 1;
1423 for (i = 1; i <= rlen; i++) {
1424 carry += (i <= (int)a[0] ? a[i] : 0);
1425 carry += (i <= (int)b[0] ? b[i] : 0);
1426 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1427 carry >>= BIGNUM_INT_BITS;
1428 if (ret[i] != 0 && i > maxspot)
1437 * Subtraction. Returns a-b, or NULL if the result would come out
1438 * negative (recall that this entire bignum module only handles
1439 * positive numbers).
1441 Bignum bigsub(Bignum a, Bignum b)
1443 int alen = a[0], blen = b[0];
1444 int rlen = (alen > blen ? alen : blen);
1453 for (i = 1; i <= rlen; i++) {
1454 carry += (i <= (int)a[0] ? a[i] : 0);
1455 carry += (i <= (int)b[0] ? b[i] ^ BIGNUM_INT_MASK : BIGNUM_INT_MASK);
1456 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1457 carry >>= BIGNUM_INT_BITS;
1458 if (ret[i] != 0 && i > maxspot)
1472 * Create a bignum which is the bitmask covering another one. That
1473 * is, the smallest integer which is >= N and is also one less than
1476 Bignum bignum_bitmask(Bignum n)
1478 Bignum ret = copybn(n);
1483 while (n[i] == 0 && i > 0)
1486 return ret; /* input was zero */
1492 ret[i] = BIGNUM_INT_MASK;
1497 * Convert a (max 32-bit) long into a bignum.
1499 Bignum bignum_from_long(unsigned long nn)
1502 BignumDblInt n = nn;
1505 ret[1] = (BignumInt)(n & BIGNUM_INT_MASK);
1506 ret[2] = (BignumInt)((n >> BIGNUM_INT_BITS) & BIGNUM_INT_MASK);
1508 ret[0] = (ret[2] ? 2 : 1);
1513 * Add a long to a bignum.
1515 Bignum bignum_add_long(Bignum number, unsigned long addendx)
1517 Bignum ret = newbn(number[0] + 1);
1519 BignumDblInt carry = 0, addend = addendx;
1521 for (i = 1; i <= (int)ret[0]; i++) {
1522 carry += addend & BIGNUM_INT_MASK;
1523 carry += (i <= (int)number[0] ? number[i] : 0);
1524 addend >>= BIGNUM_INT_BITS;
1525 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1526 carry >>= BIGNUM_INT_BITS;
1535 * Compute the residue of a bignum, modulo a (max 16-bit) short.
1537 unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
1539 BignumDblInt mod, r;
1544 for (i = number[0]; i > 0; i--)
1545 r = (r * (BIGNUM_TOP_BIT % mod) * 2 + number[i] % mod) % mod;
1546 return (unsigned short) r;
1550 void diagbn(char *prefix, Bignum md)
1552 int i, nibbles, morenibbles;
1553 static const char hex[] = "0123456789ABCDEF";
1555 debug(("%s0x", prefix ? prefix : ""));
1557 nibbles = (3 + bignum_bitcount(md)) / 4;
1560 morenibbles = 4 * md[0] - nibbles;
1561 for (i = 0; i < morenibbles; i++)
1563 for (i = nibbles; i--;)
1565 hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
1575 Bignum bigdiv(Bignum a, Bignum b)
1577 Bignum q = newbn(a[0]);
1578 bigdivmod(a, b, NULL, q);
1585 Bignum bigmod(Bignum a, Bignum b)
1587 Bignum r = newbn(b[0]);
1588 bigdivmod(a, b, r, NULL);
1593 * Greatest common divisor.
1595 Bignum biggcd(Bignum av, Bignum bv)
1597 Bignum a = copybn(av);
1598 Bignum b = copybn(bv);
1600 while (bignum_cmp(b, Zero) != 0) {
1601 Bignum t = newbn(b[0]);
1602 bigdivmod(a, b, t, NULL);
1603 while (t[0] > 1 && t[t[0]] == 0)
1615 * Modular inverse, using Euclid's extended algorithm.
1617 Bignum modinv(Bignum number, Bignum modulus)
1619 Bignum a = copybn(modulus);
1620 Bignum b = copybn(number);
1621 Bignum xp = copybn(Zero);
1622 Bignum x = copybn(One);
1625 while (bignum_cmp(b, One) != 0) {
1626 Bignum t = newbn(b[0]);
1627 Bignum q = newbn(a[0]);
1628 bigdivmod(a, b, t, q);
1629 while (t[0] > 1 && t[t[0]] == 0)
1636 x = bigmuladd(q, xp, t);
1646 /* now we know that sign * x == 1, and that x < modulus */
1648 /* set a new x to be modulus - x */
1649 Bignum newx = newbn(modulus[0]);
1650 BignumInt carry = 0;
1654 for (i = 1; i <= (int)newx[0]; i++) {
1655 BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);
1656 BignumInt bword = (i <= (int)x[0] ? x[i] : 0);
1657 newx[i] = aword - bword - carry;
1659 carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
1673 * Render a bignum into decimal. Return a malloced string holding
1674 * the decimal representation.
1676 char *bignum_decimal(Bignum x)
1678 int ndigits, ndigit;
1682 BignumInt *workspace;
1685 * First, estimate the number of digits. Since log(10)/log(2)
1686 * is just greater than 93/28 (the joys of continued fraction
1687 * approximations...) we know that for every 93 bits, we need
1688 * at most 28 digits. This will tell us how much to malloc.
1690 * Formally: if x has i bits, that means x is strictly less
1691 * than 2^i. Since 2 is less than 10^(28/93), this is less than
1692 * 10^(28i/93). We need an integer power of ten, so we must
1693 * round up (rounding down might make it less than x again).
1694 * Therefore if we multiply the bit count by 28/93, rounding
1695 * up, we will have enough digits.
1697 * i=0 (i.e., x=0) is an irritating special case.
1699 i = bignum_bitcount(x);
1701 ndigits = 1; /* x = 0 */
1703 ndigits = (28 * i + 92) / 93; /* multiply by 28/93 and round up */
1704 ndigits++; /* allow for trailing \0 */
1705 ret = snewn(ndigits, char);
1708 * Now allocate some workspace to hold the binary form as we
1709 * repeatedly divide it by ten. Initialise this to the
1710 * big-endian form of the number.
1712 workspace = snewn(x[0], BignumInt);
1713 for (i = 0; i < (int)x[0]; i++)
1714 workspace[i] = x[x[0] - i];
1717 * Next, write the decimal number starting with the last digit.
1718 * We use ordinary short division, dividing 10 into the
1721 ndigit = ndigits - 1;
1726 for (i = 0; i < (int)x[0]; i++) {
1727 carry = (carry << BIGNUM_INT_BITS) + workspace[i];
1728 workspace[i] = (BignumInt) (carry / 10);
1733 ret[--ndigit] = (char) (carry + '0');
1737 * There's a chance we've fallen short of the start of the
1738 * string. Correct if so.
1741 memmove(ret, ret + ndigit, ndigits - ndigit);
1757 * gcc -g -O0 -DTESTBN -o testbn sshbn.c misc.c -I unix -I charset
1759 * Then feed to this program's standard input the output of
1760 * testdata/bignum.py .
1763 void modalfatalbox(char *p, ...)
1766 fprintf(stderr, "FATAL ERROR: ");
1768 vfprintf(stderr, p, ap);
1770 fputc('\n', stderr);
1774 #define fromxdigit(c) ( (c)>'9' ? ((c)&0xDF) - 'A' + 10 : (c) - '0' )
1776 int main(int argc, char **argv)
1780 int passes = 0, fails = 0;
1782 while ((buf = fgetline(stdin)) != NULL) {
1783 int maxlen = strlen(buf);
1784 unsigned char *data = snewn(maxlen, unsigned char);
1785 unsigned char *ptrs[5], *q;
1794 while (*bufp && !isspace((unsigned char)*bufp))
1803 while (*bufp && !isxdigit((unsigned char)*bufp))
1810 while (*bufp && isxdigit((unsigned char)*bufp))
1814 if (ptrnum >= lenof(ptrs))
1818 for (i = -((end - start) & 1); i < end-start; i += 2) {
1819 unsigned char val = (i < 0 ? 0 : fromxdigit(start[i]));
1820 val = val * 16 + fromxdigit(start[i+1]);
1827 if (!strcmp(buf, "mul")) {
1831 printf("%d: mul with %d parameters, expected 3\n", line);
1834 a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1835 b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1836 c = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1839 if (bignum_cmp(c, p) == 0) {
1842 char *as = bignum_decimal(a);
1843 char *bs = bignum_decimal(b);
1844 char *cs = bignum_decimal(c);
1845 char *ps = bignum_decimal(p);
1847 printf("%d: fail: %s * %s gave %s expected %s\n",
1848 line, as, bs, ps, cs);
1860 } else if (!strcmp(buf, "pow")) {
1861 Bignum base, expt, modulus, expected, answer;
1864 printf("%d: mul with %d parameters, expected 3\n", line);
1868 base = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1869 expt = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1870 modulus = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1871 expected = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);
1872 answer = modpow(base, expt, modulus);
1874 if (bignum_cmp(expected, answer) == 0) {
1877 char *as = bignum_decimal(base);
1878 char *bs = bignum_decimal(expt);
1879 char *cs = bignum_decimal(modulus);
1880 char *ds = bignum_decimal(answer);
1881 char *ps = bignum_decimal(expected);
1883 printf("%d: fail: %s ^ %s mod %s gave %s expected %s\n",
1884 line, as, bs, cs, ds, ps);
1899 printf("%d: unrecognised test keyword: '%s'\n", line, buf);
1907 printf("passed %d failed %d total %d\n", passes, fails, passes+fails);