2 * Bignum routines for RSA and DH and stuff.
16 #define BIGNUM_INTERNAL
17 typedef BignumInt *Bignum;
21 BignumInt bnZero[1] = { 0 };
22 BignumInt bnOne[2] = { 1, 1 };
23 BignumInt bnTen[2] = { 1, 10 };
26 * The Bignum format is an array of `BignumInt'. The first
27 * element of the array counts the remaining elements. The
28 * remaining elements express the actual number, base 2^BIGNUM_INT_BITS, _least_
29 * significant digit first. (So it's trivial to extract the bit
30 * with value 2^n for any n.)
32 * All Bignums in this module are positive. Negative numbers must
33 * be dealt with outside it.
35 * INVARIANT: the most significant word of any Bignum must be
39 Bignum Zero = bnZero, One = bnOne, Ten = bnTen;
41 static Bignum newbn(int length)
45 assert(length >= 0 && length < INT_MAX / BIGNUM_INT_BITS);
47 b = snewn(length + 1, BignumInt);
48 memset(b, 0, (length + 1) * sizeof(*b));
53 void bn_restore_invariant(Bignum b)
55 while (b[0] > 1 && b[b[0]] == 0)
59 Bignum copybn(Bignum orig)
61 Bignum b = snewn(orig[0] + 1, BignumInt);
64 memcpy(b, orig, (orig[0] + 1) * sizeof(*b));
71 * Burn the evidence, just in case.
73 smemclr(b, sizeof(b[0]) * (b[0] + 1));
77 Bignum bn_power_2(int n)
83 ret = newbn(n / BIGNUM_INT_BITS + 1);
84 bignum_set_bit(ret, n, 1);
89 * Internal addition. Sets c = a - b, where 'a', 'b' and 'c' are all
90 * big-endian arrays of 'len' BignumInts. Returns a BignumInt carried
93 static BignumInt internal_add(const BignumInt *a, const BignumInt *b,
94 BignumInt *c, int len)
97 BignumDblInt carry = 0;
99 for (i = len-1; i >= 0; i--) {
100 carry += (BignumDblInt)a[i] + b[i];
101 c[i] = (BignumInt)carry;
102 carry >>= BIGNUM_INT_BITS;
105 return (BignumInt)carry;
109 * Internal subtraction. Sets c = a - b, where 'a', 'b' and 'c' are
110 * all big-endian arrays of 'len' BignumInts. Any borrow from the top
113 static void internal_sub(const BignumInt *a, const BignumInt *b,
114 BignumInt *c, int len)
117 BignumDblInt carry = 1;
119 for (i = len-1; i >= 0; i--) {
120 carry += (BignumDblInt)a[i] + (b[i] ^ BIGNUM_INT_MASK);
121 c[i] = (BignumInt)carry;
122 carry >>= BIGNUM_INT_BITS;
128 * Input is in the first len words of a and b.
129 * Result is returned in the first 2*len words of c.
131 * 'scratch' must point to an array of BignumInt of size at least
132 * mul_compute_scratch(len). (This covers the needs of internal_mul
133 * and all its recursive calls to itself.)
135 #define KARATSUBA_THRESHOLD 50
136 static int mul_compute_scratch(int len)
139 while (len > KARATSUBA_THRESHOLD) {
140 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
141 int midlen = botlen + 1;
147 static void internal_mul(const BignumInt *a, const BignumInt *b,
148 BignumInt *c, int len, BignumInt *scratch)
150 if (len > KARATSUBA_THRESHOLD) {
154 * Karatsuba divide-and-conquer algorithm. Cut each input in
155 * half, so that it's expressed as two big 'digits' in a giant
161 * Then the product is of course
163 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
165 * and we compute the three coefficients by recursively
166 * calling ourself to do half-length multiplications.
168 * The clever bit that makes this worth doing is that we only
169 * need _one_ half-length multiplication for the central
170 * coefficient rather than the two that it obviouly looks
171 * like, because we can use a single multiplication to compute
173 * (a_1 + a_0) (b_1 + b_0) = a_1 b_1 + a_1 b_0 + a_0 b_1 + a_0 b_0
175 * and then we subtract the other two coefficients (a_1 b_1
176 * and a_0 b_0) which we were computing anyway.
178 * Hence we get to multiply two numbers of length N in about
179 * three times as much work as it takes to multiply numbers of
180 * length N/2, which is obviously better than the four times
181 * as much work it would take if we just did a long
182 * conventional multiply.
185 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
186 int midlen = botlen + 1;
193 * The coefficients a_1 b_1 and a_0 b_0 just avoid overlapping
194 * in the output array, so we can compute them immediately in
199 printf("a1,a0 = 0x");
200 for (i = 0; i < len; i++) {
201 if (i == toplen) printf(", 0x");
202 printf("%0*x", BIGNUM_INT_BITS/4, a[i]);
205 printf("b1,b0 = 0x");
206 for (i = 0; i < len; i++) {
207 if (i == toplen) printf(", 0x");
208 printf("%0*x", BIGNUM_INT_BITS/4, b[i]);
214 internal_mul(a, b, c, toplen, scratch);
217 for (i = 0; i < 2*toplen; i++) {
218 printf("%0*x", BIGNUM_INT_BITS/4, c[i]);
224 internal_mul(a + toplen, b + toplen, c + 2*toplen, botlen, scratch);
227 for (i = 0; i < 2*botlen; i++) {
228 printf("%0*x", BIGNUM_INT_BITS/4, c[2*toplen+i]);
233 /* Zero padding. midlen exceeds toplen by at most 2, so just
234 * zero the first two words of each input and the rest will be
236 scratch[0] = scratch[1] = scratch[midlen] = scratch[midlen+1] = 0;
238 for (i = 0; i < toplen; i++) {
239 scratch[midlen - toplen + i] = a[i]; /* a_1 */
240 scratch[2*midlen - toplen + i] = b[i]; /* b_1 */
243 /* compute a_1 + a_0 */
244 scratch[0] = internal_add(scratch+1, a+toplen, scratch+1, botlen);
246 printf("a1plusa0 = 0x");
247 for (i = 0; i < midlen; i++) {
248 printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);
252 /* compute b_1 + b_0 */
253 scratch[midlen] = internal_add(scratch+midlen+1, b+toplen,
254 scratch+midlen+1, botlen);
256 printf("b1plusb0 = 0x");
257 for (i = 0; i < midlen; i++) {
258 printf("%0*x", BIGNUM_INT_BITS/4, scratch[midlen+i]);
264 * Now we can do the third multiplication.
266 internal_mul(scratch, scratch + midlen, scratch + 2*midlen, midlen,
269 printf("a1plusa0timesb1plusb0 = 0x");
270 for (i = 0; i < 2*midlen; i++) {
271 printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);
277 * Now we can reuse the first half of 'scratch' to compute the
278 * sum of the outer two coefficients, to subtract from that
279 * product to obtain the middle one.
281 scratch[0] = scratch[1] = scratch[2] = scratch[3] = 0;
282 for (i = 0; i < 2*toplen; i++)
283 scratch[2*midlen - 2*toplen + i] = c[i];
284 scratch[1] = internal_add(scratch+2, c + 2*toplen,
285 scratch+2, 2*botlen);
287 printf("a1b1plusa0b0 = 0x");
288 for (i = 0; i < 2*midlen; i++) {
289 printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);
294 internal_sub(scratch + 2*midlen, scratch,
295 scratch + 2*midlen, 2*midlen);
297 printf("a1b0plusa0b1 = 0x");
298 for (i = 0; i < 2*midlen; i++) {
299 printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);
305 * And now all we need to do is to add that middle coefficient
306 * back into the output. We may have to propagate a carry
307 * further up the output, but we can be sure it won't
308 * propagate right the way off the top.
310 carry = internal_add(c + 2*len - botlen - 2*midlen,
312 c + 2*len - botlen - 2*midlen, 2*midlen);
313 i = 2*len - botlen - 2*midlen - 1;
317 c[i] = (BignumInt)carry;
318 carry >>= BIGNUM_INT_BITS;
323 for (i = 0; i < 2*len; i++) {
324 printf("%0*x", BIGNUM_INT_BITS/4, c[i]);
333 const BignumInt *ap, *bp;
337 * Multiply in the ordinary O(N^2) way.
340 for (i = 0; i < 2 * len; i++)
343 for (cps = c + 2*len, ap = a + len; ap-- > a; cps--) {
345 for (cp = cps, bp = b + len; cp--, bp-- > b ;) {
346 t = (MUL_WORD(*ap, *bp) + carry) + *cp;
348 carry = (BignumInt)(t >> BIGNUM_INT_BITS);
356 * Variant form of internal_mul used for the initial step of
357 * Montgomery reduction. Only bothers outputting 'len' words
358 * (everything above that is thrown away).
360 static void internal_mul_low(const BignumInt *a, const BignumInt *b,
361 BignumInt *c, int len, BignumInt *scratch)
363 if (len > KARATSUBA_THRESHOLD) {
367 * Karatsuba-aware version of internal_mul_low. As before, we
368 * express each input value as a shifted combination of two
374 * Then the full product is, as before,
376 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
378 * Provided we choose D on the large side (so that a_0 and b_0
379 * are _at least_ as long as a_1 and b_1), we don't need the
380 * topmost term at all, and we only need half of the middle
381 * term. So there's no point in doing the proper Karatsuba
382 * optimisation which computes the middle term using the top
383 * one, because we'd take as long computing the top one as
384 * just computing the middle one directly.
386 * So instead, we do a much more obvious thing: we call the
387 * fully optimised internal_mul to compute a_0 b_0, and we
388 * recursively call ourself to compute the _bottom halves_ of
389 * a_1 b_0 and a_0 b_1, each of which we add into the result
390 * in the obvious way.
392 * In other words, there's no actual Karatsuba _optimisation_
393 * in this function; the only benefit in doing it this way is
394 * that we call internal_mul proper for a large part of the
395 * work, and _that_ can optimise its operation.
398 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
401 * Scratch space for the various bits and pieces we're going
402 * to be adding together: we need botlen*2 words for a_0 b_0
403 * (though we may end up throwing away its topmost word), and
404 * toplen words for each of a_1 b_0 and a_0 b_1. That adds up
409 internal_mul(a + toplen, b + toplen, scratch + 2*toplen, botlen,
413 internal_mul_low(a, b + len - toplen, scratch + toplen, toplen,
417 internal_mul_low(a + len - toplen, b, scratch, toplen,
420 /* Copy the bottom half of the big coefficient into place */
421 for (i = 0; i < botlen; i++)
422 c[toplen + i] = scratch[2*toplen + botlen + i];
424 /* Add the two small coefficients, throwing away the returned carry */
425 internal_add(scratch, scratch + toplen, scratch, toplen);
427 /* And add that to the large coefficient, leaving the result in c. */
428 internal_add(scratch, scratch + 2*toplen + botlen - toplen,
435 const BignumInt *ap, *bp;
439 * Multiply in the ordinary O(N^2) way.
442 for (i = 0; i < len; i++)
445 for (cps = c + len, ap = a + len; ap-- > a; cps--) {
447 for (cp = cps, bp = b + len; bp--, cp-- > c ;) {
448 t = (MUL_WORD(*ap, *bp) + carry) + *cp;
450 carry = (BignumInt)(t >> BIGNUM_INT_BITS);
457 * Montgomery reduction. Expects x to be a big-endian array of 2*len
458 * BignumInts whose value satisfies 0 <= x < rn (where r = 2^(len *
459 * BIGNUM_INT_BITS) is the Montgomery base). Returns in the same array
460 * a value x' which is congruent to xr^{-1} mod n, and satisfies 0 <=
463 * 'n' and 'mninv' should be big-endian arrays of 'len' BignumInts
464 * each, containing respectively n and the multiplicative inverse of
467 * 'tmp' is an array of BignumInt used as scratch space, of length at
468 * least 3*len + mul_compute_scratch(len).
470 static void monty_reduce(BignumInt *x, const BignumInt *n,
471 const BignumInt *mninv, BignumInt *tmp, int len)
477 * Multiply x by (-n)^{-1} mod r. This gives us a value m such
478 * that mn is congruent to -x mod r. Hence, mn+x is an exact
479 * multiple of r, and is also (obviously) congruent to x mod n.
481 internal_mul_low(x + len, mninv, tmp, len, tmp + 3*len);
484 * Compute t = (mn+x)/r in ordinary, non-modular, integer
485 * arithmetic. By construction this is exact, and is congruent mod
486 * n to x * r^{-1}, i.e. the answer we want.
488 * The following multiply leaves that answer in the _most_
489 * significant half of the 'x' array, so then we must shift it
492 internal_mul(tmp, n, tmp+len, len, tmp + 3*len);
493 carry = internal_add(x, tmp+len, x, 2*len);
494 for (i = 0; i < len; i++)
495 x[len + i] = x[i], x[i] = 0;
498 * Reduce t mod n. This doesn't require a full-on division by n,
499 * but merely a test and single optional subtraction, since we can
500 * show that 0 <= t < 2n.
503 * + we computed m mod r, so 0 <= m < r.
504 * + so 0 <= mn < rn, obviously
505 * + hence we only need 0 <= x < rn to guarantee that 0 <= mn+x < 2rn
506 * + yielding 0 <= (mn+x)/r < 2n as required.
509 for (i = 0; i < len; i++)
510 if (x[len + i] != n[i])
513 if (carry || i >= len || x[len + i] > n[i])
514 internal_sub(x+len, n, x+len, len);
517 static void internal_add_shifted(BignumInt *number,
518 unsigned n, int shift)
520 int word = 1 + (shift / BIGNUM_INT_BITS);
521 int bshift = shift % BIGNUM_INT_BITS;
524 addend = (BignumDblInt)n << bshift;
527 assert(word <= number[0]);
528 addend += number[word];
529 number[word] = (BignumInt) addend & BIGNUM_INT_MASK;
530 addend >>= BIGNUM_INT_BITS;
537 * Input in first alen words of a and first mlen words of m.
538 * Output in first alen words of a
539 * (of which first alen-mlen words will be zero).
540 * The MSW of m MUST have its high bit set.
541 * Quotient is accumulated in the `quotient' array, which is a Bignum
542 * rather than the internal bigendian format. Quotient parts are shifted
543 * left by `qshift' before adding into quot.
545 static void internal_mod(BignumInt *a, int alen,
546 BignumInt *m, int mlen,
547 BignumInt *quot, int qshift)
554 assert(m0 >> (BIGNUM_INT_BITS-1) == 1);
560 for (i = 0; i <= alen - mlen; i++) {
562 unsigned int q, r, c, ai1;
576 /* Find q = h:a[i] / m0 */
581 * To illustrate it, suppose a BignumInt is 8 bits, and
582 * we are dividing (say) A1:23:45:67 by A1:B2:C3. Then
583 * our initial division will be 0xA123 / 0xA1, which
584 * will give a quotient of 0x100 and a divide overflow.
585 * However, the invariants in this division algorithm
586 * are not violated, since the full number A1:23:... is
587 * _less_ than the quotient prefix A1:B2:... and so the
588 * following correction loop would have sorted it out.
590 * In this situation we set q to be the largest
591 * quotient we _can_ stomach (0xFF, of course).
595 /* Macro doesn't want an array subscript expression passed
596 * into it (see definition), so use a temporary. */
597 BignumInt tmplo = a[i];
598 DIVMOD_WORD(q, r, h, tmplo, m0);
600 /* Refine our estimate of q by looking at
601 h:a[i]:a[i+1] / m0:m1 */
603 if (t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) {
606 r = (r + m0) & BIGNUM_INT_MASK; /* overflow? */
607 if (r >= (BignumDblInt) m0 &&
608 t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) q--;
612 /* Subtract q * m from a[i...] */
614 for (k = mlen - 1; k >= 0; k--) {
615 t = MUL_WORD(q, m[k]);
617 c = (unsigned)(t >> BIGNUM_INT_BITS);
618 if ((BignumInt) t > a[i + k])
620 a[i + k] -= (BignumInt) t;
623 /* Add back m in case of borrow */
626 for (k = mlen - 1; k >= 0; k--) {
629 a[i + k] = (BignumInt) t;
630 t = t >> BIGNUM_INT_BITS;
635 internal_add_shifted(quot, q, qshift + BIGNUM_INT_BITS * (alen - mlen - i));
640 * Compute (base ^ exp) % mod, the pedestrian way.
642 Bignum modpow_simple(Bignum base_in, Bignum exp, Bignum mod)
644 BignumInt *a, *b, *n, *m, *scratch;
646 int mlen, scratchlen, i, j;
650 * The most significant word of mod needs to be non-zero. It
651 * should already be, but let's make sure.
653 assert(mod[mod[0]] != 0);
656 * Make sure the base is smaller than the modulus, by reducing
657 * it modulo the modulus if not.
659 base = bigmod(base_in, mod);
661 /* Allocate m of size mlen, copy mod to m */
662 /* We use big endian internally */
664 m = snewn(mlen, BignumInt);
665 for (j = 0; j < mlen; j++)
666 m[j] = mod[mod[0] - j];
668 /* Shift m left to make msb bit set */
669 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
670 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
673 for (i = 0; i < mlen - 1; i++)
674 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
675 m[mlen - 1] = m[mlen - 1] << mshift;
678 /* Allocate n of size mlen, copy base to n */
679 n = snewn(mlen, BignumInt);
681 for (j = 0; j < i; j++)
683 for (j = 0; j < (int)base[0]; j++)
684 n[i + j] = base[base[0] - j];
686 /* Allocate a and b of size 2*mlen. Set a = 1 */
687 a = snewn(2 * mlen, BignumInt);
688 b = snewn(2 * mlen, BignumInt);
689 for (i = 0; i < 2 * mlen; i++)
693 /* Scratch space for multiplies */
694 scratchlen = mul_compute_scratch(mlen);
695 scratch = snewn(scratchlen, BignumInt);
697 /* Skip leading zero bits of exp. */
699 j = BIGNUM_INT_BITS-1;
700 while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
704 j = BIGNUM_INT_BITS-1;
708 /* Main computation */
709 while (i < (int)exp[0]) {
711 internal_mul(a + mlen, a + mlen, b, mlen, scratch);
712 internal_mod(b, mlen * 2, m, mlen, NULL, 0);
713 if ((exp[exp[0] - i] & (1 << j)) != 0) {
714 internal_mul(b + mlen, n, a, mlen, scratch);
715 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
725 j = BIGNUM_INT_BITS-1;
728 /* Fixup result in case the modulus was shifted */
730 for (i = mlen - 1; i < 2 * mlen - 1; i++)
731 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
732 a[2 * mlen - 1] = a[2 * mlen - 1] << mshift;
733 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
734 for (i = 2 * mlen - 1; i >= mlen; i--)
735 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
738 /* Copy result to buffer */
739 result = newbn(mod[0]);
740 for (i = 0; i < mlen; i++)
741 result[result[0] - i] = a[i + mlen];
742 while (result[0] > 1 && result[result[0]] == 0)
745 /* Free temporary arrays */
746 smemclr(a, 2 * mlen * sizeof(*a));
748 smemclr(scratch, scratchlen * sizeof(*scratch));
750 smemclr(b, 2 * mlen * sizeof(*b));
752 smemclr(m, mlen * sizeof(*m));
754 smemclr(n, mlen * sizeof(*n));
763 * Compute (base ^ exp) % mod. Uses the Montgomery multiplication
764 * technique where possible, falling back to modpow_simple otherwise.
766 Bignum modpow(Bignum base_in, Bignum exp, Bignum mod)
768 BignumInt *a, *b, *x, *n, *mninv, *scratch;
769 int len, scratchlen, i, j;
770 Bignum base, base2, r, rn, inv, result;
773 * The most significant word of mod needs to be non-zero. It
774 * should already be, but let's make sure.
776 assert(mod[mod[0]] != 0);
779 * mod had better be odd, or we can't do Montgomery multiplication
780 * using a power of two at all.
783 return modpow_simple(base_in, exp, mod);
786 * Make sure the base is smaller than the modulus, by reducing
787 * it modulo the modulus if not.
789 base = bigmod(base_in, mod);
792 * Compute the inverse of n mod r, for monty_reduce. (In fact we
793 * want the inverse of _minus_ n mod r, but we'll sort that out
797 r = bn_power_2(BIGNUM_INT_BITS * len);
798 inv = modinv(mod, r);
799 assert(inv); /* cannot fail, since mod is odd and r is a power of 2 */
802 * Multiply the base by r mod n, to get it into Montgomery
805 base2 = modmul(base, r, mod);
809 rn = bigmod(r, mod); /* r mod n, i.e. Montgomerified 1 */
811 freebn(r); /* won't need this any more */
814 * Set up internal arrays of the right lengths, in big-endian
815 * format, containing the base, the modulus, and the modulus's
818 n = snewn(len, BignumInt);
819 for (j = 0; j < len; j++)
820 n[len - 1 - j] = mod[j + 1];
822 mninv = snewn(len, BignumInt);
823 for (j = 0; j < len; j++)
824 mninv[len - 1 - j] = (j < (int)inv[0] ? inv[j + 1] : 0);
825 freebn(inv); /* we don't need this copy of it any more */
826 /* Now negate mninv mod r, so it's the inverse of -n rather than +n. */
827 x = snewn(len, BignumInt);
828 for (j = 0; j < len; j++)
830 internal_sub(x, mninv, mninv, len);
832 /* x = snewn(len, BignumInt); */ /* already done above */
833 for (j = 0; j < len; j++)
834 x[len - 1 - j] = (j < (int)base[0] ? base[j + 1] : 0);
835 freebn(base); /* we don't need this copy of it any more */
837 a = snewn(2*len, BignumInt);
838 b = snewn(2*len, BignumInt);
839 for (j = 0; j < len; j++)
840 a[2*len - 1 - j] = (j < (int)rn[0] ? rn[j + 1] : 0);
843 /* Scratch space for multiplies */
844 scratchlen = 3*len + mul_compute_scratch(len);
845 scratch = snewn(scratchlen, BignumInt);
847 /* Skip leading zero bits of exp. */
849 j = BIGNUM_INT_BITS-1;
850 while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
854 j = BIGNUM_INT_BITS-1;
858 /* Main computation */
859 while (i < (int)exp[0]) {
861 internal_mul(a + len, a + len, b, len, scratch);
862 monty_reduce(b, n, mninv, scratch, len);
863 if ((exp[exp[0] - i] & (1 << j)) != 0) {
864 internal_mul(b + len, x, a, len, scratch);
865 monty_reduce(a, n, mninv, scratch, len);
875 j = BIGNUM_INT_BITS-1;
879 * Final monty_reduce to get back from the adjusted Montgomery
882 monty_reduce(a, n, mninv, scratch, len);
884 /* Copy result to buffer */
885 result = newbn(mod[0]);
886 for (i = 0; i < len; i++)
887 result[result[0] - i] = a[i + len];
888 while (result[0] > 1 && result[result[0]] == 0)
891 /* Free temporary arrays */
892 smemclr(scratch, scratchlen * sizeof(*scratch));
894 smemclr(a, 2 * len * sizeof(*a));
896 smemclr(b, 2 * len * sizeof(*b));
898 smemclr(mninv, len * sizeof(*mninv));
900 smemclr(n, len * sizeof(*n));
902 smemclr(x, len * sizeof(*x));
909 * Compute (p * q) % mod.
910 * The most significant word of mod MUST be non-zero.
911 * We assume that the result array is the same size as the mod array.
913 Bignum modmul(Bignum p, Bignum q, Bignum mod)
915 BignumInt *a, *n, *m, *o, *scratch;
916 int mshift, scratchlen;
917 int pqlen, mlen, rlen, i, j;
921 * The most significant word of mod needs to be non-zero. It
922 * should already be, but let's make sure.
924 assert(mod[mod[0]] != 0);
926 /* Allocate m of size mlen, copy mod to m */
927 /* We use big endian internally */
929 m = snewn(mlen, BignumInt);
930 for (j = 0; j < mlen; j++)
931 m[j] = mod[mod[0] - j];
933 /* Shift m left to make msb bit set */
934 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
935 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
938 for (i = 0; i < mlen - 1; i++)
939 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
940 m[mlen - 1] = m[mlen - 1] << mshift;
943 pqlen = (p[0] > q[0] ? p[0] : q[0]);
946 * Make sure that we're allowing enough space. The shifting below
947 * will underflow the vectors we allocate if pqlen is too small.
952 /* Allocate n of size pqlen, copy p to n */
953 n = snewn(pqlen, BignumInt);
955 for (j = 0; j < i; j++)
957 for (j = 0; j < (int)p[0]; j++)
958 n[i + j] = p[p[0] - j];
960 /* Allocate o of size pqlen, copy q to o */
961 o = snewn(pqlen, BignumInt);
963 for (j = 0; j < i; j++)
965 for (j = 0; j < (int)q[0]; j++)
966 o[i + j] = q[q[0] - j];
968 /* Allocate a of size 2*pqlen for result */
969 a = snewn(2 * pqlen, BignumInt);
971 /* Scratch space for multiplies */
972 scratchlen = mul_compute_scratch(pqlen);
973 scratch = snewn(scratchlen, BignumInt);
975 /* Main computation */
976 internal_mul(n, o, a, pqlen, scratch);
977 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
979 /* Fixup result in case the modulus was shifted */
981 for (i = 2 * pqlen - mlen - 1; i < 2 * pqlen - 1; i++)
982 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
983 a[2 * pqlen - 1] = a[2 * pqlen - 1] << mshift;
984 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
985 for (i = 2 * pqlen - 1; i >= 2 * pqlen - mlen; i--)
986 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
989 /* Copy result to buffer */
990 rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
991 result = newbn(rlen);
992 for (i = 0; i < rlen; i++)
993 result[result[0] - i] = a[i + 2 * pqlen - rlen];
994 while (result[0] > 1 && result[result[0]] == 0)
997 /* Free temporary arrays */
998 smemclr(scratch, scratchlen * sizeof(*scratch));
1000 smemclr(a, 2 * pqlen * sizeof(*a));
1002 smemclr(m, mlen * sizeof(*m));
1004 smemclr(n, pqlen * sizeof(*n));
1006 smemclr(o, pqlen * sizeof(*o));
1012 Bignum modsub(const Bignum a, const Bignum b, const Bignum n)
1016 if (bignum_cmp(a, n) >= 0) a1 = bigmod(a, n);
1018 if (bignum_cmp(b, n) >= 0) b1 = bigmod(b, n);
1021 if (bignum_cmp(a1, b1) >= 0) /* a >= b */
1023 ret = bigsub(a1, b1);
1027 /* Handle going round the corner of the modulus without having
1028 * negative support in Bignum */
1029 Bignum tmp = bigsub(n, b1);
1031 ret = bigadd(tmp, a1);
1035 if (a != a1) freebn(a1);
1036 if (b != b1) freebn(b1);
1043 * The most significant word of mod MUST be non-zero.
1044 * We assume that the result array is the same size as the mod array.
1045 * We optionally write out a quotient if `quotient' is non-NULL.
1046 * We can avoid writing out the result if `result' is NULL.
1048 static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
1052 int plen, mlen, i, j;
1055 * The most significant word of mod needs to be non-zero. It
1056 * should already be, but let's make sure.
1058 assert(mod[mod[0]] != 0);
1060 /* Allocate m of size mlen, copy mod to m */
1061 /* We use big endian internally */
1063 m = snewn(mlen, BignumInt);
1064 for (j = 0; j < mlen; j++)
1065 m[j] = mod[mod[0] - j];
1067 /* Shift m left to make msb bit set */
1068 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
1069 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
1072 for (i = 0; i < mlen - 1; i++)
1073 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
1074 m[mlen - 1] = m[mlen - 1] << mshift;
1078 /* Ensure plen > mlen */
1082 /* Allocate n of size plen, copy p to n */
1083 n = snewn(plen, BignumInt);
1084 for (j = 0; j < plen; j++)
1086 for (j = 1; j <= (int)p[0]; j++)
1089 /* Main computation */
1090 internal_mod(n, plen, m, mlen, quotient, mshift);
1092 /* Fixup result in case the modulus was shifted */
1094 for (i = plen - mlen - 1; i < plen - 1; i++)
1095 n[i] = (n[i] << mshift) | (n[i + 1] >> (BIGNUM_INT_BITS - mshift));
1096 n[plen - 1] = n[plen - 1] << mshift;
1097 internal_mod(n, plen, m, mlen, quotient, 0);
1098 for (i = plen - 1; i >= plen - mlen; i--)
1099 n[i] = (n[i] >> mshift) | (n[i - 1] << (BIGNUM_INT_BITS - mshift));
1102 /* Copy result to buffer */
1104 for (i = 1; i <= (int)result[0]; i++) {
1106 result[i] = j >= 0 ? n[j] : 0;
1110 /* Free temporary arrays */
1111 smemclr(m, mlen * sizeof(*m));
1113 smemclr(n, plen * sizeof(*n));
1118 * Decrement a number.
1120 void decbn(Bignum bn)
1123 while (i < (int)bn[0] && bn[i] == 0)
1124 bn[i++] = BIGNUM_INT_MASK;
1128 Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
1133 assert(nbytes >= 0 && nbytes < INT_MAX/8);
1135 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
1138 for (i = 1; i <= w; i++)
1140 for (i = nbytes; i--;) {
1141 unsigned char byte = *data++;
1142 result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);
1145 while (result[0] > 1 && result[result[0]] == 0)
1150 Bignum bignum_from_bytes_le(const unsigned char *data, int nbytes)
1155 assert(nbytes >= 0 && nbytes < INT_MAX/8);
1157 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
1160 for (i = 1; i <= w; i++)
1162 for (i = 0; i < nbytes; ++i) {
1163 unsigned char byte = *data++;
1164 result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);
1167 while (result[0] > 1 && result[result[0]] == 0)
1172 Bignum bignum_from_decimal(const char *decimal)
1174 Bignum result = copybn(Zero);
1179 if (!isdigit((unsigned char)*decimal)) {
1184 tmp = bigmul(result, Ten);
1185 tmp2 = bignum_from_long(*decimal - '0');
1186 result = bigadd(tmp, tmp2);
1196 Bignum bignum_random_in_range(const Bignum lower, const Bignum upper)
1199 unsigned char *bytes;
1200 int upper_len = bignum_bitcount(upper);
1201 int upper_bytes = upper_len / 8;
1202 int upper_bits = upper_len % 8;
1203 if (upper_bits) ++upper_bytes;
1205 bytes = snewn(upper_bytes, unsigned char);
1209 if (ret) freebn(ret);
1211 for (i = 0; i < upper_bytes; ++i)
1213 bytes[i] = (unsigned char)random_byte();
1215 /* Mask the top to reduce failure rate to 50/50 */
1218 bytes[i - 1] &= 0xFF >> (8 - upper_bits);
1221 ret = bignum_from_bytes(bytes, upper_bytes);
1222 } while (bignum_cmp(ret, lower) < 0 || bignum_cmp(ret, upper) > 0);
1223 smemclr(bytes, upper_bytes);
1230 * Read an SSH-1-format bignum from a data buffer. Return the number
1231 * of bytes consumed, or -1 if there wasn't enough data.
1233 int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)
1235 const unsigned char *p = data;
1243 for (i = 0; i < 2; i++)
1244 w = (w << 8) + *p++;
1245 b = (w + 7) / 8; /* bits -> bytes */
1250 if (!result) /* just return length */
1253 *result = bignum_from_bytes(p, b);
1255 return p + b - data;
1259 * Return the bit count of a bignum, for SSH-1 encoding.
1261 int bignum_bitcount(Bignum bn)
1263 int bitcount = bn[0] * BIGNUM_INT_BITS - 1;
1264 while (bitcount >= 0
1265 && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;
1266 return bitcount + 1;
1270 * Return the byte length of a bignum when SSH-1 encoded.
1272 int ssh1_bignum_length(Bignum bn)
1274 return 2 + (bignum_bitcount(bn) + 7) / 8;
1278 * Return the byte length of a bignum when SSH-2 encoded.
1280 int ssh2_bignum_length(Bignum bn)
1282 return 4 + (bignum_bitcount(bn) + 8) / 8;
1286 * Return a byte from a bignum; 0 is least significant, etc.
1288 int bignum_byte(Bignum bn, int i)
1290 if (i < 0 || i >= (int)(BIGNUM_INT_BYTES * bn[0]))
1291 return 0; /* beyond the end */
1293 return (bn[i / BIGNUM_INT_BYTES + 1] >>
1294 ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;
1298 * Return a bit from a bignum; 0 is least significant, etc.
1300 int bignum_bit(Bignum bn, int i)
1302 if (i < 0 || i >= (int)(BIGNUM_INT_BITS * bn[0]))
1303 return 0; /* beyond the end */
1305 return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;
1309 * Set a bit in a bignum; 0 is least significant, etc.
1311 void bignum_set_bit(Bignum bn, int bitnum, int value)
1313 if (bitnum < 0 || bitnum >= (int)(BIGNUM_INT_BITS * bn[0]))
1314 abort(); /* beyond the end */
1316 int v = bitnum / BIGNUM_INT_BITS + 1;
1317 int mask = 1 << (bitnum % BIGNUM_INT_BITS);
1326 * Write a SSH-1-format bignum into a buffer. It is assumed the
1327 * buffer is big enough. Returns the number of bytes used.
1329 int ssh1_write_bignum(void *data, Bignum bn)
1331 unsigned char *p = data;
1332 int len = ssh1_bignum_length(bn);
1334 int bitc = bignum_bitcount(bn);
1336 *p++ = (bitc >> 8) & 0xFF;
1337 *p++ = (bitc) & 0xFF;
1338 for (i = len - 2; i--;)
1339 *p++ = bignum_byte(bn, i);
1344 * Compare two bignums. Returns like strcmp.
1346 int bignum_cmp(Bignum a, Bignum b)
1348 int amax = a[0], bmax = b[0];
1351 /* Annoyingly we have two representations of zero */
1352 if (amax == 1 && a[amax] == 0)
1354 if (bmax == 1 && b[bmax] == 0)
1357 assert(amax == 0 || a[amax] != 0);
1358 assert(bmax == 0 || b[bmax] != 0);
1360 i = (amax > bmax ? amax : bmax);
1362 BignumInt aval = (i > amax ? 0 : a[i]);
1363 BignumInt bval = (i > bmax ? 0 : b[i]);
1374 * Right-shift one bignum to form another.
1376 Bignum bignum_rshift(Bignum a, int shift)
1379 int i, shiftw, shiftb, shiftbb, bits;
1384 bits = bignum_bitcount(a) - shift;
1385 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
1388 shiftw = shift / BIGNUM_INT_BITS;
1389 shiftb = shift % BIGNUM_INT_BITS;
1390 shiftbb = BIGNUM_INT_BITS - shiftb;
1392 ai1 = a[shiftw + 1];
1393 for (i = 1; i <= (int)ret[0]; i++) {
1395 ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);
1396 ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;
1404 * Left-shift one bignum to form another.
1406 Bignum bignum_lshift(Bignum a, int shift)
1409 int bits, shiftWords, shiftBits;
1413 bits = bignum_bitcount(a) + shift;
1414 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
1416 shiftWords = shift / BIGNUM_INT_BITS;
1417 shiftBits = shift % BIGNUM_INT_BITS;
1421 memcpy(&ret[1 + shiftWords], &a[1], sizeof(BignumInt) * a[0]);
1426 BignumInt carry = 0;
1428 /* Remember that Bignum[0] is length, so add 1 */
1429 for (i = shiftWords + 1; i < ((int)a[0]) + shiftWords + 1; ++i)
1431 BignumInt from = a[i - shiftWords];
1432 ret[i] = (from << shiftBits) | carry;
1433 carry = from >> (BIGNUM_INT_BITS - shiftBits);
1435 if (carry) ret[i] = carry;
1442 * Non-modular multiplication and addition.
1444 Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
1446 int alen = a[0], blen = b[0];
1447 int mlen = (alen > blen ? alen : blen);
1448 int rlen, i, maxspot;
1450 BignumInt *workspace;
1453 /* mlen space for a, mlen space for b, 2*mlen for result,
1454 * plus scratch space for multiplication */
1455 wslen = mlen * 4 + mul_compute_scratch(mlen);
1456 workspace = snewn(wslen, BignumInt);
1457 for (i = 0; i < mlen; i++) {
1458 workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);
1459 workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);
1462 internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
1463 workspace + 2 * mlen, mlen, workspace + 4 * mlen);
1465 /* now just copy the result back */
1466 rlen = alen + blen + 1;
1467 if (addend && rlen <= (int)addend[0])
1468 rlen = addend[0] + 1;
1471 for (i = 1; i <= (int)ret[0]; i++) {
1472 ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
1478 /* now add in the addend, if any */
1480 BignumDblInt carry = 0;
1481 for (i = 1; i <= rlen; i++) {
1482 carry += (i <= (int)ret[0] ? ret[i] : 0);
1483 carry += (i <= (int)addend[0] ? addend[i] : 0);
1484 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1485 carry >>= BIGNUM_INT_BITS;
1486 if (ret[i] != 0 && i > maxspot)
1492 smemclr(workspace, wslen * sizeof(*workspace));
1498 * Non-modular multiplication.
1500 Bignum bigmul(Bignum a, Bignum b)
1502 return bigmuladd(a, b, NULL);
1508 Bignum bigadd(Bignum a, Bignum b)
1510 int alen = a[0], blen = b[0];
1511 int rlen = (alen > blen ? alen : blen) + 1;
1520 for (i = 1; i <= rlen; i++) {
1521 carry += (i <= (int)a[0] ? a[i] : 0);
1522 carry += (i <= (int)b[0] ? b[i] : 0);
1523 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1524 carry >>= BIGNUM_INT_BITS;
1525 if (ret[i] != 0 && i > maxspot)
1534 * Subtraction. Returns a-b, or NULL if the result would come out
1535 * negative (recall that this entire bignum module only handles
1536 * positive numbers).
1538 Bignum bigsub(Bignum a, Bignum b)
1540 int alen = a[0], blen = b[0];
1541 int rlen = (alen > blen ? alen : blen);
1550 for (i = 1; i <= rlen; i++) {
1551 carry += (i <= (int)a[0] ? a[i] : 0);
1552 carry += (i <= (int)b[0] ? b[i] ^ BIGNUM_INT_MASK : BIGNUM_INT_MASK);
1553 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1554 carry >>= BIGNUM_INT_BITS;
1555 if (ret[i] != 0 && i > maxspot)
1569 * Create a bignum which is the bitmask covering another one. That
1570 * is, the smallest integer which is >= N and is also one less than
1573 Bignum bignum_bitmask(Bignum n)
1575 Bignum ret = copybn(n);
1580 while (n[i] == 0 && i > 0)
1583 return ret; /* input was zero */
1589 ret[i] = BIGNUM_INT_MASK;
1594 * Convert a (max 32-bit) long into a bignum.
1596 Bignum bignum_from_long(unsigned long nn)
1599 BignumDblInt n = nn;
1602 ret[1] = (BignumInt)(n & BIGNUM_INT_MASK);
1603 ret[2] = (BignumInt)((n >> BIGNUM_INT_BITS) & BIGNUM_INT_MASK);
1605 ret[0] = (ret[2] ? 2 : 1);
1610 * Add a long to a bignum.
1612 Bignum bignum_add_long(Bignum number, unsigned long addendx)
1614 Bignum ret = newbn(number[0] + 1);
1616 BignumDblInt carry = 0, addend = addendx;
1618 for (i = 1; i <= (int)ret[0]; i++) {
1619 carry += addend & BIGNUM_INT_MASK;
1620 carry += (i <= (int)number[0] ? number[i] : 0);
1621 addend >>= BIGNUM_INT_BITS;
1622 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1623 carry >>= BIGNUM_INT_BITS;
1632 * Compute the residue of a bignum, modulo a (max 16-bit) short.
1634 unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
1636 BignumDblInt mod, r;
1641 for (i = number[0]; i > 0; i--)
1642 r = (r * (BIGNUM_TOP_BIT % mod) * 2 + number[i] % mod) % mod;
1643 return (unsigned short) r;
1647 void diagbn(char *prefix, Bignum md)
1649 int i, nibbles, morenibbles;
1650 static const char hex[] = "0123456789ABCDEF";
1652 debug(("%s0x", prefix ? prefix : ""));
1654 nibbles = (3 + bignum_bitcount(md)) / 4;
1657 morenibbles = 4 * md[0] - nibbles;
1658 for (i = 0; i < morenibbles; i++)
1660 for (i = nibbles; i--;)
1662 hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
1672 Bignum bigdiv(Bignum a, Bignum b)
1674 Bignum q = newbn(a[0]);
1675 bigdivmod(a, b, NULL, q);
1676 while (q[0] > 1 && q[q[0]] == 0)
1684 Bignum bigmod(Bignum a, Bignum b)
1686 Bignum r = newbn(b[0]);
1687 bigdivmod(a, b, r, NULL);
1688 while (r[0] > 1 && r[r[0]] == 0)
1694 * Greatest common divisor.
1696 Bignum biggcd(Bignum av, Bignum bv)
1698 Bignum a = copybn(av);
1699 Bignum b = copybn(bv);
1701 while (bignum_cmp(b, Zero) != 0) {
1702 Bignum t = newbn(b[0]);
1703 bigdivmod(a, b, t, NULL);
1704 while (t[0] > 1 && t[t[0]] == 0)
1716 * Modular inverse, using Euclid's extended algorithm.
1718 Bignum modinv(Bignum number, Bignum modulus)
1720 Bignum a = copybn(modulus);
1721 Bignum b = copybn(number);
1722 Bignum xp = copybn(Zero);
1723 Bignum x = copybn(One);
1726 assert(number[number[0]] != 0);
1727 assert(modulus[modulus[0]] != 0);
1729 while (bignum_cmp(b, One) != 0) {
1732 if (bignum_cmp(b, Zero) == 0) {
1734 * Found a common factor between the inputs, so we cannot
1735 * return a modular inverse at all.
1746 bigdivmod(a, b, t, q);
1747 while (t[0] > 1 && t[t[0]] == 0)
1749 while (q[0] > 1 && q[q[0]] == 0)
1756 x = bigmuladd(q, xp, t);
1766 /* now we know that sign * x == 1, and that x < modulus */
1768 /* set a new x to be modulus - x */
1769 Bignum newx = newbn(modulus[0]);
1770 BignumInt carry = 0;
1774 for (i = 1; i <= (int)newx[0]; i++) {
1775 BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);
1776 BignumInt bword = (i <= (int)x[0] ? x[i] : 0);
1777 newx[i] = aword - bword - carry;
1779 carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
1793 * Render a bignum into decimal. Return a malloced string holding
1794 * the decimal representation.
1796 char *bignum_decimal(Bignum x)
1798 int ndigits, ndigit;
1802 BignumInt *workspace;
1805 * First, estimate the number of digits. Since log(10)/log(2)
1806 * is just greater than 93/28 (the joys of continued fraction
1807 * approximations...) we know that for every 93 bits, we need
1808 * at most 28 digits. This will tell us how much to malloc.
1810 * Formally: if x has i bits, that means x is strictly less
1811 * than 2^i. Since 2 is less than 10^(28/93), this is less than
1812 * 10^(28i/93). We need an integer power of ten, so we must
1813 * round up (rounding down might make it less than x again).
1814 * Therefore if we multiply the bit count by 28/93, rounding
1815 * up, we will have enough digits.
1817 * i=0 (i.e., x=0) is an irritating special case.
1819 i = bignum_bitcount(x);
1821 ndigits = 1; /* x = 0 */
1823 ndigits = (28 * i + 92) / 93; /* multiply by 28/93 and round up */
1824 ndigits++; /* allow for trailing \0 */
1825 ret = snewn(ndigits, char);
1828 * Now allocate some workspace to hold the binary form as we
1829 * repeatedly divide it by ten. Initialise this to the
1830 * big-endian form of the number.
1832 workspace = snewn(x[0], BignumInt);
1833 for (i = 0; i < (int)x[0]; i++)
1834 workspace[i] = x[x[0] - i];
1837 * Next, write the decimal number starting with the last digit.
1838 * We use ordinary short division, dividing 10 into the
1841 ndigit = ndigits - 1;
1846 for (i = 0; i < (int)x[0]; i++) {
1847 carry = (carry << BIGNUM_INT_BITS) + workspace[i];
1848 workspace[i] = (BignumInt) (carry / 10);
1853 ret[--ndigit] = (char) (carry + '0');
1857 * There's a chance we've fallen short of the start of the
1858 * string. Correct if so.
1861 memmove(ret, ret + ndigit, ndigits - ndigit);
1866 smemclr(workspace, x[0] * sizeof(*workspace));
1878 * gcc -Wall -g -O0 -DTESTBN -o testbn sshbn.c misc.c conf.c tree234.c unix/uxmisc.c -I. -I unix -I charset
1880 * Then feed to this program's standard input the output of
1881 * testdata/bignum.py .
1884 void modalfatalbox(const char *p, ...)
1887 fprintf(stderr, "FATAL ERROR: ");
1889 vfprintf(stderr, p, ap);
1891 fputc('\n', stderr);
1895 #define fromxdigit(c) ( (c)>'9' ? ((c)&0xDF) - 'A' + 10 : (c) - '0' )
1897 int main(int argc, char **argv)
1901 int passes = 0, fails = 0;
1903 while ((buf = fgetline(stdin)) != NULL) {
1904 int maxlen = strlen(buf);
1905 unsigned char *data = snewn(maxlen, unsigned char);
1906 unsigned char *ptrs[5], *q;
1915 while (*bufp && !isspace((unsigned char)*bufp))
1924 while (*bufp && !isxdigit((unsigned char)*bufp))
1931 while (*bufp && isxdigit((unsigned char)*bufp))
1935 if (ptrnum >= lenof(ptrs))
1939 for (i = -((end - start) & 1); i < end-start; i += 2) {
1940 unsigned char val = (i < 0 ? 0 : fromxdigit(start[i]));
1941 val = val * 16 + fromxdigit(start[i+1]);
1948 if (!strcmp(buf, "mul")) {
1952 printf("%d: mul with %d parameters, expected 3\n", line, ptrnum);
1955 a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1956 b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1957 c = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1960 if (bignum_cmp(c, p) == 0) {
1963 char *as = bignum_decimal(a);
1964 char *bs = bignum_decimal(b);
1965 char *cs = bignum_decimal(c);
1966 char *ps = bignum_decimal(p);
1968 printf("%d: fail: %s * %s gave %s expected %s\n",
1969 line, as, bs, ps, cs);
1981 } else if (!strcmp(buf, "modmul")) {
1982 Bignum a, b, m, c, p;
1985 printf("%d: modmul with %d parameters, expected 4\n",
1989 a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1990 b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1991 m = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1992 c = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);
1993 p = modmul(a, b, m);
1995 if (bignum_cmp(c, p) == 0) {
1998 char *as = bignum_decimal(a);
1999 char *bs = bignum_decimal(b);
2000 char *ms = bignum_decimal(m);
2001 char *cs = bignum_decimal(c);
2002 char *ps = bignum_decimal(p);
2004 printf("%d: fail: %s * %s mod %s gave %s expected %s\n",
2005 line, as, bs, ms, ps, cs);
2019 } else if (!strcmp(buf, "pow")) {
2020 Bignum base, expt, modulus, expected, answer;
2023 printf("%d: mul with %d parameters, expected 4\n", line, ptrnum);
2027 base = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
2028 expt = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
2029 modulus = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
2030 expected = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);
2031 answer = modpow(base, expt, modulus);
2033 if (bignum_cmp(expected, answer) == 0) {
2036 char *as = bignum_decimal(base);
2037 char *bs = bignum_decimal(expt);
2038 char *cs = bignum_decimal(modulus);
2039 char *ds = bignum_decimal(answer);
2040 char *ps = bignum_decimal(expected);
2042 printf("%d: fail: %s ^ %s mod %s gave %s expected %s\n",
2043 line, as, bs, cs, ds, ps);
2058 printf("%d: unrecognised test keyword: '%s'\n", line, buf);
2066 printf("passed %d failed %d total %d\n", passes, fails, passes+fails);