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 BignumInt 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)
553 assert(m0 >> (BIGNUM_INT_BITS-1) == 1);
559 for (i = 0; i <= alen - mlen; i++) {
561 BignumInt q, r, c, ai1;
575 /* Find q = h:a[i] / m0 */
580 * To illustrate it, suppose a BignumInt is 8 bits, and
581 * we are dividing (say) A1:23:45:67 by A1:B2:C3. Then
582 * our initial division will be 0xA123 / 0xA1, which
583 * will give a quotient of 0x100 and a divide overflow.
584 * However, the invariants in this division algorithm
585 * are not violated, since the full number A1:23:... is
586 * _less_ than the quotient prefix A1:B2:... and so the
587 * following correction loop would have sorted it out.
589 * In this situation we set q to be the largest
590 * quotient we _can_ stomach (0xFF, of course).
594 /* Macro doesn't want an array subscript expression passed
595 * into it (see definition), so use a temporary. */
596 BignumInt tmplo = a[i];
597 DIVMOD_WORD(q, r, h, tmplo, m0);
599 /* Refine our estimate of q by looking at
600 h:a[i]:a[i+1] / m0:m1 */
602 if (t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) {
605 r = (r + m0) & BIGNUM_INT_MASK; /* overflow? */
606 if (r >= (BignumDblInt) m0 &&
607 t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) q--;
611 /* Subtract q * m from a[i...] */
613 for (k = mlen - 1; k >= 0; k--) {
614 t = MUL_WORD(q, m[k]);
616 c = (BignumInt)(t >> BIGNUM_INT_BITS);
617 if ((BignumInt) t > a[i + k])
619 a[i + k] -= (BignumInt) t;
622 /* Add back m in case of borrow */
625 for (k = mlen - 1; k >= 0; k--) {
628 a[i + k] = (BignumInt) t;
629 t = t >> BIGNUM_INT_BITS;
634 internal_add_shifted(quot, q, qshift + BIGNUM_INT_BITS * (alen - mlen - i));
639 * Compute (base ^ exp) % mod, the pedestrian way.
641 Bignum modpow_simple(Bignum base_in, Bignum exp, Bignum mod)
643 BignumInt *a, *b, *n, *m, *scratch;
645 int mlen, scratchlen, i, j;
649 * The most significant word of mod needs to be non-zero. It
650 * should already be, but let's make sure.
652 assert(mod[mod[0]] != 0);
655 * Make sure the base is smaller than the modulus, by reducing
656 * it modulo the modulus if not.
658 base = bigmod(base_in, mod);
660 /* Allocate m of size mlen, copy mod to m */
661 /* We use big endian internally */
663 m = snewn(mlen, BignumInt);
664 for (j = 0; j < mlen; j++)
665 m[j] = mod[mod[0] - j];
667 /* Shift m left to make msb bit set */
668 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
669 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
672 for (i = 0; i < mlen - 1; i++)
673 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
674 m[mlen - 1] = m[mlen - 1] << mshift;
677 /* Allocate n of size mlen, copy base to n */
678 n = snewn(mlen, BignumInt);
680 for (j = 0; j < i; j++)
682 for (j = 0; j < (int)base[0]; j++)
683 n[i + j] = base[base[0] - j];
685 /* Allocate a and b of size 2*mlen. Set a = 1 */
686 a = snewn(2 * mlen, BignumInt);
687 b = snewn(2 * mlen, BignumInt);
688 for (i = 0; i < 2 * mlen; i++)
692 /* Scratch space for multiplies */
693 scratchlen = mul_compute_scratch(mlen);
694 scratch = snewn(scratchlen, BignumInt);
696 /* Skip leading zero bits of exp. */
698 j = BIGNUM_INT_BITS-1;
699 while (i < (int)exp[0] && (exp[exp[0] - i] & ((BignumInt)1 << j)) == 0) {
703 j = BIGNUM_INT_BITS-1;
707 /* Main computation */
708 while (i < (int)exp[0]) {
710 internal_mul(a + mlen, a + mlen, b, mlen, scratch);
711 internal_mod(b, mlen * 2, m, mlen, NULL, 0);
712 if ((exp[exp[0] - i] & ((BignumInt)1 << j)) != 0) {
713 internal_mul(b + mlen, n, a, mlen, scratch);
714 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
724 j = BIGNUM_INT_BITS-1;
727 /* Fixup result in case the modulus was shifted */
729 for (i = mlen - 1; i < 2 * mlen - 1; i++)
730 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
731 a[2 * mlen - 1] = a[2 * mlen - 1] << mshift;
732 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
733 for (i = 2 * mlen - 1; i >= mlen; i--)
734 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
737 /* Copy result to buffer */
738 result = newbn(mod[0]);
739 for (i = 0; i < mlen; i++)
740 result[result[0] - i] = a[i + mlen];
741 while (result[0] > 1 && result[result[0]] == 0)
744 /* Free temporary arrays */
745 smemclr(a, 2 * mlen * sizeof(*a));
747 smemclr(scratch, scratchlen * sizeof(*scratch));
749 smemclr(b, 2 * mlen * sizeof(*b));
751 smemclr(m, mlen * sizeof(*m));
753 smemclr(n, mlen * sizeof(*n));
762 * Compute (base ^ exp) % mod. Uses the Montgomery multiplication
763 * technique where possible, falling back to modpow_simple otherwise.
765 Bignum modpow(Bignum base_in, Bignum exp, Bignum mod)
767 BignumInt *a, *b, *x, *n, *mninv, *scratch;
768 int len, scratchlen, i, j;
769 Bignum base, base2, r, rn, inv, result;
772 * The most significant word of mod needs to be non-zero. It
773 * should already be, but let's make sure.
775 assert(mod[mod[0]] != 0);
778 * mod had better be odd, or we can't do Montgomery multiplication
779 * using a power of two at all.
782 return modpow_simple(base_in, exp, mod);
785 * Make sure the base is smaller than the modulus, by reducing
786 * it modulo the modulus if not.
788 base = bigmod(base_in, mod);
791 * Compute the inverse of n mod r, for monty_reduce. (In fact we
792 * want the inverse of _minus_ n mod r, but we'll sort that out
796 r = bn_power_2(BIGNUM_INT_BITS * len);
797 inv = modinv(mod, r);
798 assert(inv); /* cannot fail, since mod is odd and r is a power of 2 */
801 * Multiply the base by r mod n, to get it into Montgomery
804 base2 = modmul(base, r, mod);
808 rn = bigmod(r, mod); /* r mod n, i.e. Montgomerified 1 */
810 freebn(r); /* won't need this any more */
813 * Set up internal arrays of the right lengths, in big-endian
814 * format, containing the base, the modulus, and the modulus's
817 n = snewn(len, BignumInt);
818 for (j = 0; j < len; j++)
819 n[len - 1 - j] = mod[j + 1];
821 mninv = snewn(len, BignumInt);
822 for (j = 0; j < len; j++)
823 mninv[len - 1 - j] = (j < (int)inv[0] ? inv[j + 1] : 0);
824 freebn(inv); /* we don't need this copy of it any more */
825 /* Now negate mninv mod r, so it's the inverse of -n rather than +n. */
826 x = snewn(len, BignumInt);
827 for (j = 0; j < len; j++)
829 internal_sub(x, mninv, mninv, len);
831 /* x = snewn(len, BignumInt); */ /* already done above */
832 for (j = 0; j < len; j++)
833 x[len - 1 - j] = (j < (int)base[0] ? base[j + 1] : 0);
834 freebn(base); /* we don't need this copy of it any more */
836 a = snewn(2*len, BignumInt);
837 b = snewn(2*len, BignumInt);
838 for (j = 0; j < len; j++)
839 a[2*len - 1 - j] = (j < (int)rn[0] ? rn[j + 1] : 0);
842 /* Scratch space for multiplies */
843 scratchlen = 3*len + mul_compute_scratch(len);
844 scratch = snewn(scratchlen, BignumInt);
846 /* Skip leading zero bits of exp. */
848 j = BIGNUM_INT_BITS-1;
849 while (i < (int)exp[0] && (exp[exp[0] - i] & ((BignumInt)1 << j)) == 0) {
853 j = BIGNUM_INT_BITS-1;
857 /* Main computation */
858 while (i < (int)exp[0]) {
860 internal_mul(a + len, a + len, b, len, scratch);
861 monty_reduce(b, n, mninv, scratch, len);
862 if ((exp[exp[0] - i] & ((BignumInt)1 << j)) != 0) {
863 internal_mul(b + len, x, a, len, scratch);
864 monty_reduce(a, n, mninv, scratch, len);
874 j = BIGNUM_INT_BITS-1;
878 * Final monty_reduce to get back from the adjusted Montgomery
881 monty_reduce(a, n, mninv, scratch, len);
883 /* Copy result to buffer */
884 result = newbn(mod[0]);
885 for (i = 0; i < len; i++)
886 result[result[0] - i] = a[i + len];
887 while (result[0] > 1 && result[result[0]] == 0)
890 /* Free temporary arrays */
891 smemclr(scratch, scratchlen * sizeof(*scratch));
893 smemclr(a, 2 * len * sizeof(*a));
895 smemclr(b, 2 * len * sizeof(*b));
897 smemclr(mninv, len * sizeof(*mninv));
899 smemclr(n, len * sizeof(*n));
901 smemclr(x, len * sizeof(*x));
908 * Compute (p * q) % mod.
909 * The most significant word of mod MUST be non-zero.
910 * We assume that the result array is the same size as the mod array.
912 Bignum modmul(Bignum p, Bignum q, Bignum mod)
914 BignumInt *a, *n, *m, *o, *scratch;
915 int mshift, scratchlen;
916 int pqlen, mlen, rlen, i, j;
920 * The most significant word of mod needs to be non-zero. It
921 * should already be, but let's make sure.
923 assert(mod[mod[0]] != 0);
925 /* Allocate m of size mlen, copy mod to m */
926 /* We use big endian internally */
928 m = snewn(mlen, BignumInt);
929 for (j = 0; j < mlen; j++)
930 m[j] = mod[mod[0] - j];
932 /* Shift m left to make msb bit set */
933 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
934 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
937 for (i = 0; i < mlen - 1; i++)
938 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
939 m[mlen - 1] = m[mlen - 1] << mshift;
942 pqlen = (p[0] > q[0] ? p[0] : q[0]);
945 * Make sure that we're allowing enough space. The shifting below
946 * will underflow the vectors we allocate if pqlen is too small.
951 /* Allocate n of size pqlen, copy p to n */
952 n = snewn(pqlen, BignumInt);
954 for (j = 0; j < i; j++)
956 for (j = 0; j < (int)p[0]; j++)
957 n[i + j] = p[p[0] - j];
959 /* Allocate o of size pqlen, copy q to o */
960 o = snewn(pqlen, BignumInt);
962 for (j = 0; j < i; j++)
964 for (j = 0; j < (int)q[0]; j++)
965 o[i + j] = q[q[0] - j];
967 /* Allocate a of size 2*pqlen for result */
968 a = snewn(2 * pqlen, BignumInt);
970 /* Scratch space for multiplies */
971 scratchlen = mul_compute_scratch(pqlen);
972 scratch = snewn(scratchlen, BignumInt);
974 /* Main computation */
975 internal_mul(n, o, a, pqlen, scratch);
976 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
978 /* Fixup result in case the modulus was shifted */
980 for (i = 2 * pqlen - mlen - 1; i < 2 * pqlen - 1; i++)
981 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
982 a[2 * pqlen - 1] = a[2 * pqlen - 1] << mshift;
983 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
984 for (i = 2 * pqlen - 1; i >= 2 * pqlen - mlen; i--)
985 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
988 /* Copy result to buffer */
989 rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
990 result = newbn(rlen);
991 for (i = 0; i < rlen; i++)
992 result[result[0] - i] = a[i + 2 * pqlen - rlen];
993 while (result[0] > 1 && result[result[0]] == 0)
996 /* Free temporary arrays */
997 smemclr(scratch, scratchlen * sizeof(*scratch));
999 smemclr(a, 2 * pqlen * sizeof(*a));
1001 smemclr(m, mlen * sizeof(*m));
1003 smemclr(n, pqlen * sizeof(*n));
1005 smemclr(o, pqlen * sizeof(*o));
1011 Bignum modsub(const Bignum a, const Bignum b, const Bignum n)
1015 if (bignum_cmp(a, n) >= 0) a1 = bigmod(a, n);
1017 if (bignum_cmp(b, n) >= 0) b1 = bigmod(b, n);
1020 if (bignum_cmp(a1, b1) >= 0) /* a >= b */
1022 ret = bigsub(a1, b1);
1026 /* Handle going round the corner of the modulus without having
1027 * negative support in Bignum */
1028 Bignum tmp = bigsub(n, b1);
1030 ret = bigadd(tmp, a1);
1034 if (a != a1) freebn(a1);
1035 if (b != b1) freebn(b1);
1042 * The most significant word of mod MUST be non-zero.
1043 * We assume that the result array is the same size as the mod array.
1044 * We optionally write out a quotient if `quotient' is non-NULL.
1045 * We can avoid writing out the result if `result' is NULL.
1047 static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
1051 int plen, mlen, i, j;
1054 * The most significant word of mod needs to be non-zero. It
1055 * should already be, but let's make sure.
1057 assert(mod[mod[0]] != 0);
1059 /* Allocate m of size mlen, copy mod to m */
1060 /* We use big endian internally */
1062 m = snewn(mlen, BignumInt);
1063 for (j = 0; j < mlen; j++)
1064 m[j] = mod[mod[0] - j];
1066 /* Shift m left to make msb bit set */
1067 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
1068 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
1071 for (i = 0; i < mlen - 1; i++)
1072 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
1073 m[mlen - 1] = m[mlen - 1] << mshift;
1077 /* Ensure plen > mlen */
1081 /* Allocate n of size plen, copy p to n */
1082 n = snewn(plen, BignumInt);
1083 for (j = 0; j < plen; j++)
1085 for (j = 1; j <= (int)p[0]; j++)
1088 /* Main computation */
1089 internal_mod(n, plen, m, mlen, quotient, mshift);
1091 /* Fixup result in case the modulus was shifted */
1093 for (i = plen - mlen - 1; i < plen - 1; i++)
1094 n[i] = (n[i] << mshift) | (n[i + 1] >> (BIGNUM_INT_BITS - mshift));
1095 n[plen - 1] = n[plen - 1] << mshift;
1096 internal_mod(n, plen, m, mlen, quotient, 0);
1097 for (i = plen - 1; i >= plen - mlen; i--)
1098 n[i] = (n[i] >> mshift) | (n[i - 1] << (BIGNUM_INT_BITS - mshift));
1101 /* Copy result to buffer */
1103 for (i = 1; i <= (int)result[0]; i++) {
1105 result[i] = j >= 0 ? n[j] : 0;
1109 /* Free temporary arrays */
1110 smemclr(m, mlen * sizeof(*m));
1112 smemclr(n, plen * sizeof(*n));
1117 * Decrement a number.
1119 void decbn(Bignum bn)
1122 while (i < (int)bn[0] && bn[i] == 0)
1123 bn[i++] = BIGNUM_INT_MASK;
1127 Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
1132 assert(nbytes >= 0 && nbytes < INT_MAX/8);
1134 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
1137 for (i = 1; i <= w; i++)
1139 for (i = nbytes; i--;) {
1140 unsigned char byte = *data++;
1141 result[1 + i / BIGNUM_INT_BYTES] |=
1142 (BignumInt)byte << (8*i % BIGNUM_INT_BITS);
1145 bn_restore_invariant(result);
1149 Bignum bignum_from_bytes_le(const unsigned char *data, int nbytes)
1154 assert(nbytes >= 0 && nbytes < INT_MAX/8);
1156 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
1159 for (i = 1; i <= w; i++)
1161 for (i = 0; i < nbytes; ++i) {
1162 unsigned char byte = *data++;
1163 result[1 + i / BIGNUM_INT_BYTES] |=
1164 (BignumInt)byte << (8*i % BIGNUM_INT_BITS);
1167 bn_restore_invariant(result);
1171 Bignum bignum_from_decimal(const char *decimal)
1173 Bignum result = copybn(Zero);
1178 if (!isdigit((unsigned char)*decimal)) {
1183 tmp = bigmul(result, Ten);
1184 tmp2 = bignum_from_long(*decimal - '0');
1185 result = bigadd(tmp, tmp2);
1195 Bignum bignum_random_in_range(const Bignum lower, const Bignum upper)
1198 unsigned char *bytes;
1199 int upper_len = bignum_bitcount(upper);
1200 int upper_bytes = upper_len / 8;
1201 int upper_bits = upper_len % 8;
1202 if (upper_bits) ++upper_bytes;
1204 bytes = snewn(upper_bytes, unsigned char);
1208 if (ret) freebn(ret);
1210 for (i = 0; i < upper_bytes; ++i)
1212 bytes[i] = (unsigned char)random_byte();
1214 /* Mask the top to reduce failure rate to 50/50 */
1217 bytes[i - 1] &= 0xFF >> (8 - upper_bits);
1220 ret = bignum_from_bytes(bytes, upper_bytes);
1221 } while (bignum_cmp(ret, lower) < 0 || bignum_cmp(ret, upper) > 0);
1222 smemclr(bytes, upper_bytes);
1229 * Read an SSH-1-format bignum from a data buffer. Return the number
1230 * of bytes consumed, or -1 if there wasn't enough data.
1232 int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)
1234 const unsigned char *p = data;
1242 for (i = 0; i < 2; i++)
1243 w = (w << 8) + *p++;
1244 b = (w + 7) / 8; /* bits -> bytes */
1249 if (!result) /* just return length */
1252 *result = bignum_from_bytes(p, b);
1254 return p + b - data;
1258 * Return the bit count of a bignum, for SSH-1 encoding.
1260 int bignum_bitcount(Bignum bn)
1262 int bitcount = bn[0] * BIGNUM_INT_BITS - 1;
1263 while (bitcount >= 0
1264 && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;
1265 return bitcount + 1;
1269 * Return the byte length of a bignum when SSH-1 encoded.
1271 int ssh1_bignum_length(Bignum bn)
1273 return 2 + (bignum_bitcount(bn) + 7) / 8;
1277 * Return the byte length of a bignum when SSH-2 encoded.
1279 int ssh2_bignum_length(Bignum bn)
1281 return 4 + (bignum_bitcount(bn) + 8) / 8;
1285 * Return a byte from a bignum; 0 is least significant, etc.
1287 int bignum_byte(Bignum bn, int i)
1289 if (i < 0 || i >= (int)(BIGNUM_INT_BYTES * bn[0]))
1290 return 0; /* beyond the end */
1292 return (bn[i / BIGNUM_INT_BYTES + 1] >>
1293 ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;
1297 * Return a bit from a bignum; 0 is least significant, etc.
1299 int bignum_bit(Bignum bn, int i)
1301 if (i < 0 || i >= (int)(BIGNUM_INT_BITS * bn[0]))
1302 return 0; /* beyond the end */
1304 return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;
1308 * Set a bit in a bignum; 0 is least significant, etc.
1310 void bignum_set_bit(Bignum bn, int bitnum, int value)
1312 if (bitnum < 0 || bitnum >= (int)(BIGNUM_INT_BITS * bn[0])) {
1313 if (value) abort(); /* beyond the end */
1315 int v = bitnum / BIGNUM_INT_BITS + 1;
1316 BignumInt mask = (BignumInt)1 << (bitnum % BIGNUM_INT_BITS);
1325 * Write a SSH-1-format bignum into a buffer. It is assumed the
1326 * buffer is big enough. Returns the number of bytes used.
1328 int ssh1_write_bignum(void *data, Bignum bn)
1330 unsigned char *p = data;
1331 int len = ssh1_bignum_length(bn);
1333 int bitc = bignum_bitcount(bn);
1335 *p++ = (bitc >> 8) & 0xFF;
1336 *p++ = (bitc) & 0xFF;
1337 for (i = len - 2; i--;)
1338 *p++ = bignum_byte(bn, i);
1343 * Compare two bignums. Returns like strcmp.
1345 int bignum_cmp(Bignum a, Bignum b)
1347 int amax = a[0], bmax = b[0];
1350 /* Annoyingly we have two representations of zero */
1351 if (amax == 1 && a[amax] == 0)
1353 if (bmax == 1 && b[bmax] == 0)
1356 assert(amax == 0 || a[amax] != 0);
1357 assert(bmax == 0 || b[bmax] != 0);
1359 i = (amax > bmax ? amax : bmax);
1361 BignumInt aval = (i > amax ? 0 : a[i]);
1362 BignumInt bval = (i > bmax ? 0 : b[i]);
1373 * Right-shift one bignum to form another.
1375 Bignum bignum_rshift(Bignum a, int shift)
1378 int i, shiftw, shiftb, shiftbb, bits;
1383 bits = bignum_bitcount(a) - shift;
1384 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
1387 shiftw = shift / BIGNUM_INT_BITS;
1388 shiftb = shift % BIGNUM_INT_BITS;
1389 shiftbb = BIGNUM_INT_BITS - shiftb;
1391 ai1 = a[shiftw + 1];
1392 for (i = 1; i <= (int)ret[0]; i++) {
1394 ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);
1395 ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;
1403 * Left-shift one bignum to form another.
1405 Bignum bignum_lshift(Bignum a, int shift)
1408 int bits, shiftWords, shiftBits;
1412 bits = bignum_bitcount(a) + shift;
1413 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
1415 shiftWords = shift / BIGNUM_INT_BITS;
1416 shiftBits = shift % BIGNUM_INT_BITS;
1420 memcpy(&ret[1 + shiftWords], &a[1], sizeof(BignumInt) * a[0]);
1425 BignumInt carry = 0;
1427 /* Remember that Bignum[0] is length, so add 1 */
1428 for (i = shiftWords + 1; i < ((int)a[0]) + shiftWords + 1; ++i)
1430 BignumInt from = a[i - shiftWords];
1431 ret[i] = (from << shiftBits) | carry;
1432 carry = from >> (BIGNUM_INT_BITS - shiftBits);
1434 if (carry) ret[i] = carry;
1441 * Non-modular multiplication and addition.
1443 Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
1445 int alen = a[0], blen = b[0];
1446 int mlen = (alen > blen ? alen : blen);
1447 int rlen, i, maxspot;
1449 BignumInt *workspace;
1452 /* mlen space for a, mlen space for b, 2*mlen for result,
1453 * plus scratch space for multiplication */
1454 wslen = mlen * 4 + mul_compute_scratch(mlen);
1455 workspace = snewn(wslen, BignumInt);
1456 for (i = 0; i < mlen; i++) {
1457 workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);
1458 workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);
1461 internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
1462 workspace + 2 * mlen, mlen, workspace + 4 * mlen);
1464 /* now just copy the result back */
1465 rlen = alen + blen + 1;
1466 if (addend && rlen <= (int)addend[0])
1467 rlen = addend[0] + 1;
1470 for (i = 1; i <= (int)ret[0]; i++) {
1471 ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
1477 /* now add in the addend, if any */
1479 BignumDblInt carry = 0;
1480 for (i = 1; i <= rlen; i++) {
1481 carry += (i <= (int)ret[0] ? ret[i] : 0);
1482 carry += (i <= (int)addend[0] ? addend[i] : 0);
1483 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1484 carry >>= BIGNUM_INT_BITS;
1485 if (ret[i] != 0 && i > maxspot)
1491 smemclr(workspace, wslen * sizeof(*workspace));
1497 * Non-modular multiplication.
1499 Bignum bigmul(Bignum a, Bignum b)
1501 return bigmuladd(a, b, NULL);
1507 Bignum bigadd(Bignum a, Bignum b)
1509 int alen = a[0], blen = b[0];
1510 int rlen = (alen > blen ? alen : blen) + 1;
1519 for (i = 1; i <= rlen; i++) {
1520 carry += (i <= (int)a[0] ? a[i] : 0);
1521 carry += (i <= (int)b[0] ? b[i] : 0);
1522 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1523 carry >>= BIGNUM_INT_BITS;
1524 if (ret[i] != 0 && i > maxspot)
1533 * Subtraction. Returns a-b, or NULL if the result would come out
1534 * negative (recall that this entire bignum module only handles
1535 * positive numbers).
1537 Bignum bigsub(Bignum a, Bignum b)
1539 int alen = a[0], blen = b[0];
1540 int rlen = (alen > blen ? alen : blen);
1549 for (i = 1; i <= rlen; i++) {
1550 carry += (i <= (int)a[0] ? a[i] : 0);
1551 carry += (i <= (int)b[0] ? b[i] ^ BIGNUM_INT_MASK : BIGNUM_INT_MASK);
1552 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1553 carry >>= BIGNUM_INT_BITS;
1554 if (ret[i] != 0 && i > maxspot)
1568 * Create a bignum which is the bitmask covering another one. That
1569 * is, the smallest integer which is >= N and is also one less than
1572 Bignum bignum_bitmask(Bignum n)
1574 Bignum ret = copybn(n);
1579 while (n[i] == 0 && i > 0)
1582 return ret; /* input was zero */
1588 ret[i] = BIGNUM_INT_MASK;
1593 * Convert a (max 32-bit) long into a bignum.
1595 Bignum bignum_from_long(unsigned long nn)
1598 BignumDblInt n = nn;
1601 ret[1] = (BignumInt)(n & BIGNUM_INT_MASK);
1602 ret[2] = (BignumInt)((n >> BIGNUM_INT_BITS) & BIGNUM_INT_MASK);
1604 ret[0] = (ret[2] ? 2 : 1);
1609 * Add a long to a bignum.
1611 Bignum bignum_add_long(Bignum number, unsigned long addendx)
1613 Bignum ret = newbn(number[0] + 1);
1615 BignumDblInt carry = 0, addend = addendx;
1617 for (i = 1; i <= (int)ret[0]; i++) {
1618 carry += addend & BIGNUM_INT_MASK;
1619 carry += (i <= (int)number[0] ? number[i] : 0);
1620 addend >>= BIGNUM_INT_BITS;
1621 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1622 carry >>= BIGNUM_INT_BITS;
1631 * Compute the residue of a bignum, modulo a (max 16-bit) short.
1633 unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
1635 BignumDblInt mod, r;
1640 for (i = number[0]; i > 0; i--)
1641 r = (r * (BIGNUM_TOP_BIT % mod) * 2 + number[i] % mod) % mod;
1642 return (unsigned short) r;
1646 void diagbn(char *prefix, Bignum md)
1648 int i, nibbles, morenibbles;
1649 static const char hex[] = "0123456789ABCDEF";
1651 debug(("%s0x", prefix ? prefix : ""));
1653 nibbles = (3 + bignum_bitcount(md)) / 4;
1656 morenibbles = 4 * md[0] - nibbles;
1657 for (i = 0; i < morenibbles; i++)
1659 for (i = nibbles; i--;)
1661 hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
1671 Bignum bigdiv(Bignum a, Bignum b)
1673 Bignum q = newbn(a[0]);
1674 bigdivmod(a, b, NULL, q);
1675 while (q[0] > 1 && q[q[0]] == 0)
1683 Bignum bigmod(Bignum a, Bignum b)
1685 Bignum r = newbn(b[0]);
1686 bigdivmod(a, b, r, NULL);
1687 while (r[0] > 1 && r[r[0]] == 0)
1693 * Greatest common divisor.
1695 Bignum biggcd(Bignum av, Bignum bv)
1697 Bignum a = copybn(av);
1698 Bignum b = copybn(bv);
1700 while (bignum_cmp(b, Zero) != 0) {
1701 Bignum t = newbn(b[0]);
1702 bigdivmod(a, b, t, NULL);
1703 while (t[0] > 1 && t[t[0]] == 0)
1715 * Modular inverse, using Euclid's extended algorithm.
1717 Bignum modinv(Bignum number, Bignum modulus)
1719 Bignum a = copybn(modulus);
1720 Bignum b = copybn(number);
1721 Bignum xp = copybn(Zero);
1722 Bignum x = copybn(One);
1725 assert(number[number[0]] != 0);
1726 assert(modulus[modulus[0]] != 0);
1728 while (bignum_cmp(b, One) != 0) {
1731 if (bignum_cmp(b, Zero) == 0) {
1733 * Found a common factor between the inputs, so we cannot
1734 * return a modular inverse at all.
1745 bigdivmod(a, b, t, q);
1746 while (t[0] > 1 && t[t[0]] == 0)
1748 while (q[0] > 1 && q[q[0]] == 0)
1755 x = bigmuladd(q, xp, t);
1765 /* now we know that sign * x == 1, and that x < modulus */
1767 /* set a new x to be modulus - x */
1768 Bignum newx = newbn(modulus[0]);
1769 BignumInt carry = 0;
1773 for (i = 1; i <= (int)newx[0]; i++) {
1774 BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);
1775 BignumInt bword = (i <= (int)x[0] ? x[i] : 0);
1776 newx[i] = aword - bword - carry;
1778 carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
1792 * Render a bignum into decimal. Return a malloced string holding
1793 * the decimal representation.
1795 char *bignum_decimal(Bignum x)
1797 int ndigits, ndigit;
1801 BignumInt *workspace;
1804 * First, estimate the number of digits. Since log(10)/log(2)
1805 * is just greater than 93/28 (the joys of continued fraction
1806 * approximations...) we know that for every 93 bits, we need
1807 * at most 28 digits. This will tell us how much to malloc.
1809 * Formally: if x has i bits, that means x is strictly less
1810 * than 2^i. Since 2 is less than 10^(28/93), this is less than
1811 * 10^(28i/93). We need an integer power of ten, so we must
1812 * round up (rounding down might make it less than x again).
1813 * Therefore if we multiply the bit count by 28/93, rounding
1814 * up, we will have enough digits.
1816 * i=0 (i.e., x=0) is an irritating special case.
1818 i = bignum_bitcount(x);
1820 ndigits = 1; /* x = 0 */
1822 ndigits = (28 * i + 92) / 93; /* multiply by 28/93 and round up */
1823 ndigits++; /* allow for trailing \0 */
1824 ret = snewn(ndigits, char);
1827 * Now allocate some workspace to hold the binary form as we
1828 * repeatedly divide it by ten. Initialise this to the
1829 * big-endian form of the number.
1831 workspace = snewn(x[0], BignumInt);
1832 for (i = 0; i < (int)x[0]; i++)
1833 workspace[i] = x[x[0] - i];
1836 * Next, write the decimal number starting with the last digit.
1837 * We use ordinary short division, dividing 10 into the
1840 ndigit = ndigits - 1;
1845 for (i = 0; i < (int)x[0]; i++) {
1846 carry = (carry << BIGNUM_INT_BITS) + workspace[i];
1847 workspace[i] = (BignumInt) (carry / 10);
1852 ret[--ndigit] = (char) (carry + '0');
1856 * There's a chance we've fallen short of the start of the
1857 * string. Correct if so.
1860 memmove(ret, ret + ndigit, ndigits - ndigit);
1865 smemclr(workspace, x[0] * sizeof(*workspace));
1877 * gcc -Wall -g -O0 -DTESTBN -o testbn sshbn.c misc.c conf.c tree234.c unix/uxmisc.c -I. -I unix -I charset
1879 * Then feed to this program's standard input the output of
1880 * testdata/bignum.py .
1883 void modalfatalbox(const char *p, ...)
1886 fprintf(stderr, "FATAL ERROR: ");
1888 vfprintf(stderr, p, ap);
1890 fputc('\n', stderr);
1894 int random_byte(void)
1896 modalfatalbox("random_byte called in testbn");
1900 #define fromxdigit(c) ( (c)>'9' ? ((c)&0xDF) - 'A' + 10 : (c) - '0' )
1902 int main(int argc, char **argv)
1906 int passes = 0, fails = 0;
1908 while ((buf = fgetline(stdin)) != NULL) {
1909 int maxlen = strlen(buf);
1910 unsigned char *data = snewn(maxlen, unsigned char);
1911 unsigned char *ptrs[5], *q;
1920 while (*bufp && !isspace((unsigned char)*bufp))
1929 while (*bufp && !isxdigit((unsigned char)*bufp))
1936 while (*bufp && isxdigit((unsigned char)*bufp))
1940 if (ptrnum >= lenof(ptrs))
1944 for (i = -((end - start) & 1); i < end-start; i += 2) {
1945 unsigned char val = (i < 0 ? 0 : fromxdigit(start[i]));
1946 val = val * 16 + fromxdigit(start[i+1]);
1953 if (!strcmp(buf, "mul")) {
1957 printf("%d: mul with %d parameters, expected 3\n", line, ptrnum);
1960 a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1961 b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1962 c = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1965 if (bignum_cmp(c, p) == 0) {
1968 char *as = bignum_decimal(a);
1969 char *bs = bignum_decimal(b);
1970 char *cs = bignum_decimal(c);
1971 char *ps = bignum_decimal(p);
1973 printf("%d: fail: %s * %s gave %s expected %s\n",
1974 line, as, bs, ps, cs);
1986 } else if (!strcmp(buf, "modmul")) {
1987 Bignum a, b, m, c, p;
1990 printf("%d: modmul with %d parameters, expected 4\n",
1994 a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1995 b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1996 m = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1997 c = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);
1998 p = modmul(a, b, m);
2000 if (bignum_cmp(c, p) == 0) {
2003 char *as = bignum_decimal(a);
2004 char *bs = bignum_decimal(b);
2005 char *ms = bignum_decimal(m);
2006 char *cs = bignum_decimal(c);
2007 char *ps = bignum_decimal(p);
2009 printf("%d: fail: %s * %s mod %s gave %s expected %s\n",
2010 line, as, bs, ms, ps, cs);
2024 } else if (!strcmp(buf, "pow")) {
2025 Bignum base, expt, modulus, expected, answer;
2028 printf("%d: pow with %d parameters, expected 4\n", line, ptrnum);
2032 base = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
2033 expt = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
2034 modulus = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
2035 expected = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);
2036 answer = modpow(base, expt, modulus);
2038 if (bignum_cmp(expected, answer) == 0) {
2041 char *as = bignum_decimal(base);
2042 char *bs = bignum_decimal(expt);
2043 char *cs = bignum_decimal(modulus);
2044 char *ds = bignum_decimal(answer);
2045 char *ps = bignum_decimal(expected);
2047 printf("%d: fail: %s ^ %s mod %s gave %s expected %s\n",
2048 line, as, bs, cs, ds, ps);
2063 printf("%d: unrecognised test keyword: '%s'\n", line, buf);
2071 printf("passed %d failed %d total %d\n", passes, fails, passes+fails);