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 the carry off the
93 static BignumCarry internal_add(const BignumInt *a, const BignumInt *b,
94 BignumInt *c, int len)
97 BignumCarry carry = 0;
99 for (i = len-1; i >= 0; i--)
100 BignumADC(c[i], carry, a[i], b[i], carry);
102 return (BignumInt)carry;
106 * Internal subtraction. Sets c = a - b, where 'a', 'b' and 'c' are
107 * all big-endian arrays of 'len' BignumInts. Any borrow from the top
110 static void internal_sub(const BignumInt *a, const BignumInt *b,
111 BignumInt *c, int len)
114 BignumCarry carry = 1;
116 for (i = len-1; i >= 0; i--)
117 BignumADC(c[i], carry, a[i], ~b[i], carry);
122 * Input is in the first len words of a and b.
123 * Result is returned in the first 2*len words of c.
125 * 'scratch' must point to an array of BignumInt of size at least
126 * mul_compute_scratch(len). (This covers the needs of internal_mul
127 * and all its recursive calls to itself.)
129 #define KARATSUBA_THRESHOLD 50
130 static int mul_compute_scratch(int len)
133 while (len > KARATSUBA_THRESHOLD) {
134 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
135 int midlen = botlen + 1;
141 static void internal_mul(const BignumInt *a, const BignumInt *b,
142 BignumInt *c, int len, BignumInt *scratch)
144 if (len > KARATSUBA_THRESHOLD) {
148 * Karatsuba divide-and-conquer algorithm. Cut each input in
149 * half, so that it's expressed as two big 'digits' in a giant
155 * Then the product is of course
157 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
159 * and we compute the three coefficients by recursively
160 * calling ourself to do half-length multiplications.
162 * The clever bit that makes this worth doing is that we only
163 * need _one_ half-length multiplication for the central
164 * coefficient rather than the two that it obviouly looks
165 * like, because we can use a single multiplication to compute
167 * (a_1 + a_0) (b_1 + b_0) = a_1 b_1 + a_1 b_0 + a_0 b_1 + a_0 b_0
169 * and then we subtract the other two coefficients (a_1 b_1
170 * and a_0 b_0) which we were computing anyway.
172 * Hence we get to multiply two numbers of length N in about
173 * three times as much work as it takes to multiply numbers of
174 * length N/2, which is obviously better than the four times
175 * as much work it would take if we just did a long
176 * conventional multiply.
179 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
180 int midlen = botlen + 1;
187 * The coefficients a_1 b_1 and a_0 b_0 just avoid overlapping
188 * in the output array, so we can compute them immediately in
193 printf("a1,a0 = 0x");
194 for (i = 0; i < len; i++) {
195 if (i == toplen) printf(", 0x");
196 printf("%0*x", BIGNUM_INT_BITS/4, a[i]);
199 printf("b1,b0 = 0x");
200 for (i = 0; i < len; i++) {
201 if (i == toplen) printf(", 0x");
202 printf("%0*x", BIGNUM_INT_BITS/4, b[i]);
208 internal_mul(a, b, c, toplen, scratch);
211 for (i = 0; i < 2*toplen; i++) {
212 printf("%0*x", BIGNUM_INT_BITS/4, c[i]);
218 internal_mul(a + toplen, b + toplen, c + 2*toplen, botlen, scratch);
221 for (i = 0; i < 2*botlen; i++) {
222 printf("%0*x", BIGNUM_INT_BITS/4, c[2*toplen+i]);
227 /* Zero padding. midlen exceeds toplen by at most 2, so just
228 * zero the first two words of each input and the rest will be
230 scratch[0] = scratch[1] = scratch[midlen] = scratch[midlen+1] = 0;
232 for (i = 0; i < toplen; i++) {
233 scratch[midlen - toplen + i] = a[i]; /* a_1 */
234 scratch[2*midlen - toplen + i] = b[i]; /* b_1 */
237 /* compute a_1 + a_0 */
238 scratch[0] = internal_add(scratch+1, a+toplen, scratch+1, botlen);
240 printf("a1plusa0 = 0x");
241 for (i = 0; i < midlen; i++) {
242 printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);
246 /* compute b_1 + b_0 */
247 scratch[midlen] = internal_add(scratch+midlen+1, b+toplen,
248 scratch+midlen+1, botlen);
250 printf("b1plusb0 = 0x");
251 for (i = 0; i < midlen; i++) {
252 printf("%0*x", BIGNUM_INT_BITS/4, scratch[midlen+i]);
258 * Now we can do the third multiplication.
260 internal_mul(scratch, scratch + midlen, scratch + 2*midlen, midlen,
263 printf("a1plusa0timesb1plusb0 = 0x");
264 for (i = 0; i < 2*midlen; i++) {
265 printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);
271 * Now we can reuse the first half of 'scratch' to compute the
272 * sum of the outer two coefficients, to subtract from that
273 * product to obtain the middle one.
275 scratch[0] = scratch[1] = scratch[2] = scratch[3] = 0;
276 for (i = 0; i < 2*toplen; i++)
277 scratch[2*midlen - 2*toplen + i] = c[i];
278 scratch[1] = internal_add(scratch+2, c + 2*toplen,
279 scratch+2, 2*botlen);
281 printf("a1b1plusa0b0 = 0x");
282 for (i = 0; i < 2*midlen; i++) {
283 printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);
288 internal_sub(scratch + 2*midlen, scratch,
289 scratch + 2*midlen, 2*midlen);
291 printf("a1b0plusa0b1 = 0x");
292 for (i = 0; i < 2*midlen; i++) {
293 printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);
299 * And now all we need to do is to add that middle coefficient
300 * back into the output. We may have to propagate a carry
301 * further up the output, but we can be sure it won't
302 * propagate right the way off the top.
304 carry = internal_add(c + 2*len - botlen - 2*midlen,
306 c + 2*len - botlen - 2*midlen, 2*midlen);
307 i = 2*len - botlen - 2*midlen - 1;
310 BignumADC(c[i], carry, c[i], 0, carry);
315 for (i = 0; i < 2*len; i++) {
316 printf("%0*x", BIGNUM_INT_BITS/4, c[i]);
324 const BignumInt *ap, *bp;
328 * Multiply in the ordinary O(N^2) way.
331 for (i = 0; i < 2 * len; i++)
334 for (cps = c + 2*len, ap = a + len; ap-- > a; cps--) {
336 for (cp = cps, bp = b + len; cp--, bp-- > b ;)
337 BignumMULADD2(carry, *cp, *ap, *bp, *cp, carry);
344 * Variant form of internal_mul used for the initial step of
345 * Montgomery reduction. Only bothers outputting 'len' words
346 * (everything above that is thrown away).
348 static void internal_mul_low(const BignumInt *a, const BignumInt *b,
349 BignumInt *c, int len, BignumInt *scratch)
351 if (len > KARATSUBA_THRESHOLD) {
355 * Karatsuba-aware version of internal_mul_low. As before, we
356 * express each input value as a shifted combination of two
362 * Then the full product is, as before,
364 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
366 * Provided we choose D on the large side (so that a_0 and b_0
367 * are _at least_ as long as a_1 and b_1), we don't need the
368 * topmost term at all, and we only need half of the middle
369 * term. So there's no point in doing the proper Karatsuba
370 * optimisation which computes the middle term using the top
371 * one, because we'd take as long computing the top one as
372 * just computing the middle one directly.
374 * So instead, we do a much more obvious thing: we call the
375 * fully optimised internal_mul to compute a_0 b_0, and we
376 * recursively call ourself to compute the _bottom halves_ of
377 * a_1 b_0 and a_0 b_1, each of which we add into the result
378 * in the obvious way.
380 * In other words, there's no actual Karatsuba _optimisation_
381 * in this function; the only benefit in doing it this way is
382 * that we call internal_mul proper for a large part of the
383 * work, and _that_ can optimise its operation.
386 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
389 * Scratch space for the various bits and pieces we're going
390 * to be adding together: we need botlen*2 words for a_0 b_0
391 * (though we may end up throwing away its topmost word), and
392 * toplen words for each of a_1 b_0 and a_0 b_1. That adds up
397 internal_mul(a + toplen, b + toplen, scratch + 2*toplen, botlen,
401 internal_mul_low(a, b + len - toplen, scratch + toplen, toplen,
405 internal_mul_low(a + len - toplen, b, scratch, toplen,
408 /* Copy the bottom half of the big coefficient into place */
409 for (i = 0; i < botlen; i++)
410 c[toplen + i] = scratch[2*toplen + botlen + i];
412 /* Add the two small coefficients, throwing away the returned carry */
413 internal_add(scratch, scratch + toplen, scratch, toplen);
415 /* And add that to the large coefficient, leaving the result in c. */
416 internal_add(scratch, scratch + 2*toplen + botlen - toplen,
422 const BignumInt *ap, *bp;
426 * Multiply in the ordinary O(N^2) way.
429 for (i = 0; i < len; i++)
432 for (cps = c + len, ap = a + len; ap-- > a; cps--) {
434 for (cp = cps, bp = b + len; bp--, cp-- > c ;)
435 BignumMULADD2(carry, *cp, *ap, *bp, *cp, carry);
441 * Montgomery reduction. Expects x to be a big-endian array of 2*len
442 * BignumInts whose value satisfies 0 <= x < rn (where r = 2^(len *
443 * BIGNUM_INT_BITS) is the Montgomery base). Returns in the same array
444 * a value x' which is congruent to xr^{-1} mod n, and satisfies 0 <=
447 * 'n' and 'mninv' should be big-endian arrays of 'len' BignumInts
448 * each, containing respectively n and the multiplicative inverse of
451 * 'tmp' is an array of BignumInt used as scratch space, of length at
452 * least 3*len + mul_compute_scratch(len).
454 static void monty_reduce(BignumInt *x, const BignumInt *n,
455 const BignumInt *mninv, BignumInt *tmp, int len)
461 * Multiply x by (-n)^{-1} mod r. This gives us a value m such
462 * that mn is congruent to -x mod r. Hence, mn+x is an exact
463 * multiple of r, and is also (obviously) congruent to x mod n.
465 internal_mul_low(x + len, mninv, tmp, len, tmp + 3*len);
468 * Compute t = (mn+x)/r in ordinary, non-modular, integer
469 * arithmetic. By construction this is exact, and is congruent mod
470 * n to x * r^{-1}, i.e. the answer we want.
472 * The following multiply leaves that answer in the _most_
473 * significant half of the 'x' array, so then we must shift it
476 internal_mul(tmp, n, tmp+len, len, tmp + 3*len);
477 carry = internal_add(x, tmp+len, x, 2*len);
478 for (i = 0; i < len; i++)
479 x[len + i] = x[i], x[i] = 0;
482 * Reduce t mod n. This doesn't require a full-on division by n,
483 * but merely a test and single optional subtraction, since we can
484 * show that 0 <= t < 2n.
487 * + we computed m mod r, so 0 <= m < r.
488 * + so 0 <= mn < rn, obviously
489 * + hence we only need 0 <= x < rn to guarantee that 0 <= mn+x < 2rn
490 * + yielding 0 <= (mn+x)/r < 2n as required.
493 for (i = 0; i < len; i++)
494 if (x[len + i] != n[i])
497 if (carry || i >= len || x[len + i] > n[i])
498 internal_sub(x+len, n, x+len, len);
501 static void internal_add_shifted(BignumInt *number,
502 BignumInt n, int shift)
504 int word = 1 + (shift / BIGNUM_INT_BITS);
505 int bshift = shift % BIGNUM_INT_BITS;
506 BignumInt addendh, addendl;
509 addendl = n << bshift;
510 addendh = (bshift == 0 ? 0 : n >> (BIGNUM_INT_BITS - bshift));
512 assert(word <= number[0]);
513 BignumADC(number[word], carry, number[word], addendl, 0);
515 if (!addendh && !carry)
517 assert(word <= number[0]);
518 BignumADC(number[word], carry, number[word], addendh, carry);
521 assert(word <= number[0]);
522 BignumADC(number[word], carry, number[word], 0, carry);
527 static int bn_clz(BignumInt x)
530 * Count the leading zero bits in x. Equivalently, how far left
531 * would we need to shift x to make its top bit set?
533 * Precondition: x != 0.
536 /* FIXME: would be nice to put in some compiler intrinsics under
539 for (i = BIGNUM_INT_BITS / 2; i != 0; i >>= 1) {
540 if ((x >> (BIGNUM_INT_BITS-i)) == 0) {
548 static BignumInt reciprocal_word(BignumInt d)
550 BignumInt dshort, recip, prodh, prodl;
554 * Input: a BignumInt value d, with its top bit set.
556 assert(d >> (BIGNUM_INT_BITS-1) == 1);
559 * Output: a value, shifted to fill a BignumInt, which is strictly
560 * less than 1/(d+1), i.e. is an *under*-estimate (but by as
561 * little as possible within the constraints) of the reciprocal of
562 * any number whose first BIGNUM_INT_BITS bits match d.
564 * Ideally we'd like to _totally_ fill BignumInt, i.e. always
565 * return a value with the top bit set. Unfortunately we can't
566 * quite guarantee that for all inputs and also return a fixed
567 * exponent. So instead we take our reciprocal to be
568 * 2^(BIGNUM_INT_BITS*2-1) / d, so that it has the top bit clear
569 * only in the exceptional case where d takes exactly the maximum
570 * value BIGNUM_INT_MASK; in that case, the top bit is clear and
571 * the next bit down is set.
575 * Start by computing a half-length version of the answer, by
576 * straightforward division within a BignumInt.
578 dshort = (d >> (BIGNUM_INT_BITS/2)) + 1;
579 recip = (BIGNUM_TOP_BIT + dshort - 1) / dshort;
580 recip <<= BIGNUM_INT_BITS - BIGNUM_INT_BITS/2;
583 * Newton-Raphson iteration to improve that starting reciprocal
584 * estimate: take f(x) = d - 1/x, and then the N-R formula gives
585 * x_new = x - f(x)/f'(x) = x - (d-1/x)/(1/x^2) = x(2-d*x). Or,
586 * taking our fixed-point representation into account, take f(x)
587 * to be d - K/x (where K = 2^(BIGNUM_INT_BITS*2-1) as discussed
588 * above) and then we get (2K - d*x) * x/K.
590 * Newton-Raphson doubles the number of correct bits at every
591 * iteration, and the initial division above already gave us half
592 * the output word, so it's only worth doing one iteration.
594 BignumMULADD(prodh, prodl, recip, d, recip);
599 BignumADC(prodl, c, prodl, 1, 0);
602 BignumMUL(prodh, prodl, prodh, recip);
603 recip = (prodh << 1) | (prodl >> (BIGNUM_INT_BITS-1));
606 * Now make sure we have the best possible reciprocal estimate,
607 * before we return it. We might have been off by a handful either
608 * way - not enough to bother with any better-thought-out kind of
611 BignumMULADD(prodh, prodl, recip, d, recip);
613 if (prodh >= BIGNUM_TOP_BIT) {
616 BignumADC(prodl, c, prodl, ~d, c); prodh += BIGNUM_INT_MASK + c;
619 } while (prodh >= ((BignumInt)1 << (BIGNUM_INT_BITS-1)));
622 BignumInt newprodh, newprodl;
624 BignumADC(newprodl, c, prodl, d, c); newprodh = prodh + c;
625 if (newprodh >= BIGNUM_TOP_BIT)
639 * Input in first alen words of a and first mlen words of m.
640 * Output in first alen words of a
641 * (of which first alen-mlen words will be zero).
642 * Quotient is accumulated in the `quotient' array, which is a Bignum
643 * rather than the internal bigendian format.
645 * 'recip' must be the result of calling reciprocal_word() on the top
646 * BIGNUM_INT_BITS of the modulus (denoted m0 in comments below), with
647 * the topmost set bit normalised to the MSB of the input to
648 * reciprocal_word. 'rshift' is how far left the top nonzero word of
649 * the modulus had to be shifted to set that top bit.
651 static void internal_mod(BignumInt *a, int alen,
652 BignumInt *m, int mlen,
653 BignumInt *quot, BignumInt recip, int rshift)
657 #ifdef DIVISION_DEBUG
660 printf("start division, m=0x");
661 for (d = 0; d < mlen; d++)
662 printf("%0*llx", BIGNUM_INT_BITS/4, (unsigned long long)m[d]);
663 printf(", recip=%#0*llx, rshift=%d\n",
664 BIGNUM_INT_BITS/4, (unsigned long long)recip, rshift);
669 * Repeatedly use that reciprocal estimate to get a decent number
670 * of quotient bits, and subtract off the resulting multiple of m.
672 * Normally we expect to terminate this loop by means of finding
673 * out q=0 part way through, but one way in which we might not get
674 * that far in the first place is if the input a is actually zero,
675 * in which case we'll discard zero words from the front of a
676 * until we reach the termination condition in the for statement
679 for (i = 0; i <= alen - mlen ;) {
682 int shift, full_bitoffset, bitoffset, wordoffset;
684 #ifdef DIVISION_DEBUG
687 printf("main loop, a=0x");
688 for (d = 0; d < alen; d++)
689 printf("%0*llx", BIGNUM_INT_BITS/4, (unsigned long long)a[d]);
695 #ifdef DIVISION_DEBUG
696 printf("zero word at i=%d\n", i);
703 shift = bn_clz(aword);
705 if (shift > 0 && i+1 < alen)
706 aword |= a[i+1] >> (BIGNUM_INT_BITS - shift);
710 BignumMUL(q, unused, recip, aword);
714 #ifdef DIVISION_DEBUG
715 printf("i=%d, aword=%#0*llx, shift=%d, q=%#0*llx\n",
716 i, BIGNUM_INT_BITS/4, (unsigned long long)aword,
717 shift, BIGNUM_INT_BITS/4, (unsigned long long)q);
721 * Work out the right bit and word offsets to use when
722 * subtracting q*m from a.
724 * aword was taken from a[i], which means its LSB was at bit
725 * position (alen-1-i) * BIGNUM_INT_BITS. But then we shifted
726 * it left by 'shift', so now the low bit of aword corresponds
727 * to bit position (alen-1-i) * BIGNUM_INT_BITS - shift, i.e.
728 * aword is approximately equal to a / 2^(that).
730 * m0 comes from the top word of mod, so its LSB is at bit
731 * position (mlen-1) * BIGNUM_INT_BITS - rshift, i.e. it can
732 * be considered to be m / 2^(that power). 'recip' is the
733 * reciprocal of m0, times 2^(BIGNUM_INT_BITS*2-1), i.e. it's
734 * about 2^((mlen+1) * BIGNUM_INT_BITS - rshift - 1) / m.
736 * Hence, recip * aword is approximately equal to the product
737 * of those, which simplifies to
739 * a/m * 2^((mlen+2+i-alen)*BIGNUM_INT_BITS + shift - rshift - 1)
741 * But we've also shifted recip*aword down by BIGNUM_INT_BITS
742 * to form q, so we have
744 * q ~= a/m * 2^((mlen+1+i-alen)*BIGNUM_INT_BITS + shift - rshift - 1)
746 * and hence, when we now compute q*m, it will be about
747 * a*2^(all that lot), i.e. the negation of that expression is
748 * how far left we have to shift the product q*m to make it
749 * approximately equal to a.
751 full_bitoffset = -((mlen+1+i-alen)*BIGNUM_INT_BITS + shift-rshift-1);
752 #ifdef DIVISION_DEBUG
753 printf("full_bitoffset=%d\n", full_bitoffset);
756 if (full_bitoffset < 0) {
758 * If we find ourselves needing to shift q*m _right_, that
759 * means we've reached the bottom of the quotient. Clip q
760 * so that its right shift becomes zero, and if that means
761 * q becomes _actually_ zero, this loop is done.
763 if (full_bitoffset <= -BIGNUM_INT_BITS)
765 q >>= -full_bitoffset;
769 #ifdef DIVISION_DEBUG
770 printf("now full_bitoffset=%d, q=%#0*llx\n",
771 full_bitoffset, BIGNUM_INT_BITS/4, (unsigned long long)q);
775 wordoffset = full_bitoffset / BIGNUM_INT_BITS;
776 bitoffset = full_bitoffset % BIGNUM_INT_BITS;
777 #ifdef DIVISION_DEBUG
778 printf("wordoffset=%d, bitoffset=%d\n", wordoffset, bitoffset);
781 /* wordoffset as computed above is the offset between the LSWs
782 * of m and a. But in fact m and a are stored MSW-first, so we
783 * need to adjust it to be the offset between the actual array
784 * indices, and flip the sign too. */
785 wordoffset = alen - mlen - wordoffset;
787 if (bitoffset == 0) {
789 BignumInt prev_hi_word = 0;
790 for (k = mlen - 1; wordoffset+k >= i; k--) {
791 BignumInt mword = k<0 ? 0 : m[k];
792 BignumMULADD(prev_hi_word, product, q, mword, prev_hi_word);
793 #ifdef DIVISION_DEBUG
794 printf(" aligned sub: product word for m[%d] = %#0*llx\n",
795 k, BIGNUM_INT_BITS/4,
796 (unsigned long long)product);
798 #ifdef DIVISION_DEBUG
799 printf(" aligned sub: subtrahend for a[%d] = %#0*llx\n",
800 wordoffset+k, BIGNUM_INT_BITS/4,
801 (unsigned long long)product);
803 BignumADC(a[wordoffset+k], c, a[wordoffset+k], ~product, c);
806 BignumInt add_word = 0;
808 BignumInt prev_hi_word = 0;
809 for (k = mlen - 1; wordoffset+k >= i; k--) {
810 BignumInt mword = k<0 ? 0 : m[k];
811 BignumMULADD(prev_hi_word, product, q, mword, prev_hi_word);
812 #ifdef DIVISION_DEBUG
813 printf(" unaligned sub: product word for m[%d] = %#0*llx\n",
814 k, BIGNUM_INT_BITS/4,
815 (unsigned long long)product);
818 add_word |= product << bitoffset;
820 #ifdef DIVISION_DEBUG
821 printf(" unaligned sub: subtrahend for a[%d] = %#0*llx\n",
823 BIGNUM_INT_BITS/4, (unsigned long long)add_word);
825 BignumADC(a[wordoffset+k], c, a[wordoffset+k], ~add_word, c);
827 add_word = product >> (BIGNUM_INT_BITS - bitoffset);
832 #ifdef DIVISION_DEBUG
833 printf("adding quotient word %#0*llx << %d\n",
834 BIGNUM_INT_BITS/4, (unsigned long long)q, full_bitoffset);
836 internal_add_shifted(quot, q, full_bitoffset);
837 #ifdef DIVISION_DEBUG
840 printf("now quot=0x");
841 for (d = quot[0]; d > 0; d--)
842 printf("%0*llx", BIGNUM_INT_BITS/4,
843 (unsigned long long)quot[d]);
850 #ifdef DIVISION_DEBUG
853 printf("end main loop, a=0x");
854 for (d = 0; d < alen; d++)
855 printf("%0*llx", BIGNUM_INT_BITS/4, (unsigned long long)a[d]);
858 for (d = quot[0]; d > 0; d--)
859 printf("%0*llx", BIGNUM_INT_BITS/4,
860 (unsigned long long)quot[d]);
867 * The above loop should terminate with the remaining value in a
868 * being strictly less than 2*m (if a >= 2*m then we should always
869 * have managed to get a nonzero q word), but we can't guarantee
870 * that it will be strictly less than m: consider a case where the
871 * remainder is 1, and another where the remainder is m-1. By the
872 * time a contains a value that's _about m_, you clearly can't
873 * distinguish those cases by looking at only the top word of a -
874 * you have to go all the way down to the bottom before you find
875 * out whether it's just less or just more than m.
877 * Hence, we now do a final fixup in which we subtract one last
878 * copy of m, or don't, accordingly. We should never have to
879 * subtract more than one copy of m here.
881 for (i = 0; i < alen; i++) {
882 /* Compare a with m, word by word, from the MSW down. As soon
883 * as we encounter a difference, we know whether we need the
885 int mindex = mlen-alen+i;
886 BignumInt mword = mindex < 0 ? 0 : m[mindex];
888 #ifdef DIVISION_DEBUG
889 printf("final fixup not needed, a < m\n");
892 } else if (a[i] > mword) {
893 #ifdef DIVISION_DEBUG
894 printf("final fixup is needed, a > m\n");
898 /* If neither of those cases happened, the words are the same,
899 * so keep going and look at the next one. */
901 #ifdef DIVISION_DEBUG
902 if (i == mlen) /* if we printed neither of the above diagnostics */
903 printf("final fixup is needed, a == m\n");
907 * If we got here without returning, then a >= m, so we must
908 * subtract m, and increment the quotient.
912 for (i = alen - 1; i >= 0; i--) {
913 int mindex = mlen-alen+i;
914 BignumInt mword = mindex < 0 ? 0 : m[mindex];
915 BignumADC(a[i], c, a[i], ~mword, c);
919 internal_add_shifted(quot, 1, 0);
921 #ifdef DIVISION_DEBUG
924 printf("after final fixup, a=0x");
925 for (d = 0; d < alen; d++)
926 printf("%0*llx", BIGNUM_INT_BITS/4, (unsigned long long)a[d]);
929 for (d = quot[0]; d > 0; d--)
930 printf("%0*llx", BIGNUM_INT_BITS/4,
931 (unsigned long long)quot[d]);
939 * Compute (base ^ exp) % mod, the pedestrian way.
941 Bignum modpow_simple(Bignum base_in, Bignum exp, Bignum mod)
943 BignumInt *a, *b, *n, *m, *scratch;
946 int mlen, scratchlen, i, j;
950 * The most significant word of mod needs to be non-zero. It
951 * should already be, but let's make sure.
953 assert(mod[mod[0]] != 0);
956 * Make sure the base is smaller than the modulus, by reducing
957 * it modulo the modulus if not.
959 base = bigmod(base_in, mod);
961 /* Allocate m of size mlen, copy mod to m */
962 /* We use big endian internally */
964 m = snewn(mlen, BignumInt);
965 for (j = 0; j < mlen; j++)
966 m[j] = mod[mod[0] - j];
968 /* Allocate n of size mlen, copy base to n */
969 n = snewn(mlen, BignumInt);
971 for (j = 0; j < i; j++)
973 for (j = 0; j < (int)base[0]; j++)
974 n[i + j] = base[base[0] - j];
976 /* Allocate a and b of size 2*mlen. Set a = 1 */
977 a = snewn(2 * mlen, BignumInt);
978 b = snewn(2 * mlen, BignumInt);
979 for (i = 0; i < 2 * mlen; i++)
983 /* Scratch space for multiplies */
984 scratchlen = mul_compute_scratch(mlen);
985 scratch = snewn(scratchlen, BignumInt);
987 /* Skip leading zero bits of exp. */
989 j = BIGNUM_INT_BITS-1;
990 while (i < (int)exp[0] && (exp[exp[0] - i] & ((BignumInt)1 << j)) == 0) {
994 j = BIGNUM_INT_BITS-1;
998 /* Compute reciprocal of the top full word of the modulus */
1000 BignumInt m0 = m[0];
1001 rshift = bn_clz(m0);
1005 m0 |= m[1] >> (BIGNUM_INT_BITS - rshift);
1007 recip = reciprocal_word(m0);
1010 /* Main computation */
1011 while (i < (int)exp[0]) {
1013 internal_mul(a + mlen, a + mlen, b, mlen, scratch);
1014 internal_mod(b, mlen * 2, m, mlen, NULL, recip, rshift);
1015 if ((exp[exp[0] - i] & ((BignumInt)1 << j)) != 0) {
1016 internal_mul(b + mlen, n, a, mlen, scratch);
1017 internal_mod(a, mlen * 2, m, mlen, NULL, recip, rshift);
1027 j = BIGNUM_INT_BITS-1;
1030 /* Copy result to buffer */
1031 result = newbn(mod[0]);
1032 for (i = 0; i < mlen; i++)
1033 result[result[0] - i] = a[i + mlen];
1034 while (result[0] > 1 && result[result[0]] == 0)
1037 /* Free temporary arrays */
1038 smemclr(a, 2 * mlen * sizeof(*a));
1040 smemclr(scratch, scratchlen * sizeof(*scratch));
1042 smemclr(b, 2 * mlen * sizeof(*b));
1044 smemclr(m, mlen * sizeof(*m));
1046 smemclr(n, mlen * sizeof(*n));
1055 * Compute (base ^ exp) % mod. Uses the Montgomery multiplication
1056 * technique where possible, falling back to modpow_simple otherwise.
1058 Bignum modpow(Bignum base_in, Bignum exp, Bignum mod)
1060 BignumInt *a, *b, *x, *n, *mninv, *scratch;
1061 int len, scratchlen, i, j;
1062 Bignum base, base2, r, rn, inv, result;
1065 * The most significant word of mod needs to be non-zero. It
1066 * should already be, but let's make sure.
1068 assert(mod[mod[0]] != 0);
1071 * mod had better be odd, or we can't do Montgomery multiplication
1072 * using a power of two at all.
1075 return modpow_simple(base_in, exp, mod);
1078 * Make sure the base is smaller than the modulus, by reducing
1079 * it modulo the modulus if not.
1081 base = bigmod(base_in, mod);
1084 * Compute the inverse of n mod r, for monty_reduce. (In fact we
1085 * want the inverse of _minus_ n mod r, but we'll sort that out
1089 r = bn_power_2(BIGNUM_INT_BITS * len);
1090 inv = modinv(mod, r);
1091 assert(inv); /* cannot fail, since mod is odd and r is a power of 2 */
1094 * Multiply the base by r mod n, to get it into Montgomery
1097 base2 = modmul(base, r, mod);
1101 rn = bigmod(r, mod); /* r mod n, i.e. Montgomerified 1 */
1103 freebn(r); /* won't need this any more */
1106 * Set up internal arrays of the right lengths, in big-endian
1107 * format, containing the base, the modulus, and the modulus's
1110 n = snewn(len, BignumInt);
1111 for (j = 0; j < len; j++)
1112 n[len - 1 - j] = mod[j + 1];
1114 mninv = snewn(len, BignumInt);
1115 for (j = 0; j < len; j++)
1116 mninv[len - 1 - j] = (j < (int)inv[0] ? inv[j + 1] : 0);
1117 freebn(inv); /* we don't need this copy of it any more */
1118 /* Now negate mninv mod r, so it's the inverse of -n rather than +n. */
1119 x = snewn(len, BignumInt);
1120 for (j = 0; j < len; j++)
1122 internal_sub(x, mninv, mninv, len);
1124 /* x = snewn(len, BignumInt); */ /* already done above */
1125 for (j = 0; j < len; j++)
1126 x[len - 1 - j] = (j < (int)base[0] ? base[j + 1] : 0);
1127 freebn(base); /* we don't need this copy of it any more */
1129 a = snewn(2*len, BignumInt);
1130 b = snewn(2*len, BignumInt);
1131 for (j = 0; j < len; j++)
1132 a[2*len - 1 - j] = (j < (int)rn[0] ? rn[j + 1] : 0);
1135 /* Scratch space for multiplies */
1136 scratchlen = 3*len + mul_compute_scratch(len);
1137 scratch = snewn(scratchlen, BignumInt);
1139 /* Skip leading zero bits of exp. */
1141 j = BIGNUM_INT_BITS-1;
1142 while (i < (int)exp[0] && (exp[exp[0] - i] & ((BignumInt)1 << j)) == 0) {
1146 j = BIGNUM_INT_BITS-1;
1150 /* Main computation */
1151 while (i < (int)exp[0]) {
1153 internal_mul(a + len, a + len, b, len, scratch);
1154 monty_reduce(b, n, mninv, scratch, len);
1155 if ((exp[exp[0] - i] & ((BignumInt)1 << j)) != 0) {
1156 internal_mul(b + len, x, a, len, scratch);
1157 monty_reduce(a, n, mninv, scratch, len);
1167 j = BIGNUM_INT_BITS-1;
1171 * Final monty_reduce to get back from the adjusted Montgomery
1174 monty_reduce(a, n, mninv, scratch, len);
1176 /* Copy result to buffer */
1177 result = newbn(mod[0]);
1178 for (i = 0; i < len; i++)
1179 result[result[0] - i] = a[i + len];
1180 while (result[0] > 1 && result[result[0]] == 0)
1183 /* Free temporary arrays */
1184 smemclr(scratch, scratchlen * sizeof(*scratch));
1186 smemclr(a, 2 * len * sizeof(*a));
1188 smemclr(b, 2 * len * sizeof(*b));
1190 smemclr(mninv, len * sizeof(*mninv));
1192 smemclr(n, len * sizeof(*n));
1194 smemclr(x, len * sizeof(*x));
1201 * Compute (p * q) % mod.
1202 * The most significant word of mod MUST be non-zero.
1203 * We assume that the result array is the same size as the mod array.
1205 Bignum modmul(Bignum p, Bignum q, Bignum mod)
1207 BignumInt *a, *n, *m, *o, *scratch;
1209 int rshift, scratchlen;
1210 int pqlen, mlen, rlen, i, j;
1214 * The most significant word of mod needs to be non-zero. It
1215 * should already be, but let's make sure.
1217 assert(mod[mod[0]] != 0);
1219 /* Allocate m of size mlen, copy mod to m */
1220 /* We use big endian internally */
1222 m = snewn(mlen, BignumInt);
1223 for (j = 0; j < mlen; j++)
1224 m[j] = mod[mod[0] - j];
1226 pqlen = (p[0] > q[0] ? p[0] : q[0]);
1229 * Make sure that we're allowing enough space. The shifting below
1230 * will underflow the vectors we allocate if pqlen is too small.
1232 if (2*pqlen <= mlen)
1235 /* Allocate n of size pqlen, copy p to n */
1236 n = snewn(pqlen, BignumInt);
1238 for (j = 0; j < i; j++)
1240 for (j = 0; j < (int)p[0]; j++)
1241 n[i + j] = p[p[0] - j];
1243 /* Allocate o of size pqlen, copy q to o */
1244 o = snewn(pqlen, BignumInt);
1246 for (j = 0; j < i; j++)
1248 for (j = 0; j < (int)q[0]; j++)
1249 o[i + j] = q[q[0] - j];
1251 /* Allocate a of size 2*pqlen for result */
1252 a = snewn(2 * pqlen, BignumInt);
1254 /* Scratch space for multiplies */
1255 scratchlen = mul_compute_scratch(pqlen);
1256 scratch = snewn(scratchlen, BignumInt);
1258 /* Compute reciprocal of the top full word of the modulus */
1260 BignumInt m0 = m[0];
1261 rshift = bn_clz(m0);
1265 m0 |= m[1] >> (BIGNUM_INT_BITS - rshift);
1267 recip = reciprocal_word(m0);
1270 /* Main computation */
1271 internal_mul(n, o, a, pqlen, scratch);
1272 internal_mod(a, pqlen * 2, m, mlen, NULL, recip, rshift);
1274 /* Copy result to buffer */
1275 rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
1276 result = newbn(rlen);
1277 for (i = 0; i < rlen; i++)
1278 result[result[0] - i] = a[i + 2 * pqlen - rlen];
1279 while (result[0] > 1 && result[result[0]] == 0)
1282 /* Free temporary arrays */
1283 smemclr(scratch, scratchlen * sizeof(*scratch));
1285 smemclr(a, 2 * pqlen * sizeof(*a));
1287 smemclr(m, mlen * sizeof(*m));
1289 smemclr(n, pqlen * sizeof(*n));
1291 smemclr(o, pqlen * sizeof(*o));
1297 Bignum modsub(const Bignum a, const Bignum b, const Bignum n)
1301 if (bignum_cmp(a, n) >= 0) a1 = bigmod(a, n);
1303 if (bignum_cmp(b, n) >= 0) b1 = bigmod(b, n);
1306 if (bignum_cmp(a1, b1) >= 0) /* a >= b */
1308 ret = bigsub(a1, b1);
1312 /* Handle going round the corner of the modulus without having
1313 * negative support in Bignum */
1314 Bignum tmp = bigsub(n, b1);
1316 ret = bigadd(tmp, a1);
1320 if (a != a1) freebn(a1);
1321 if (b != b1) freebn(b1);
1328 * The most significant word of mod MUST be non-zero.
1329 * We assume that the result array is the same size as the mod array.
1330 * We optionally write out a quotient if `quotient' is non-NULL.
1331 * We can avoid writing out the result if `result' is NULL.
1333 static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
1338 int plen, mlen, i, j;
1341 * The most significant word of mod needs to be non-zero. It
1342 * should already be, but let's make sure.
1344 assert(mod[mod[0]] != 0);
1346 /* Allocate m of size mlen, copy mod to m */
1347 /* We use big endian internally */
1349 m = snewn(mlen, BignumInt);
1350 for (j = 0; j < mlen; j++)
1351 m[j] = mod[mod[0] - j];
1354 /* Ensure plen > mlen */
1358 /* Allocate n of size plen, copy p to n */
1359 n = snewn(plen, BignumInt);
1360 for (j = 0; j < plen; j++)
1362 for (j = 1; j <= (int)p[0]; j++)
1365 /* Compute reciprocal of the top full word of the modulus */
1367 BignumInt m0 = m[0];
1368 rshift = bn_clz(m0);
1372 m0 |= m[1] >> (BIGNUM_INT_BITS - rshift);
1374 recip = reciprocal_word(m0);
1377 /* Main computation */
1378 internal_mod(n, plen, m, mlen, quotient, recip, rshift);
1380 /* Copy result to buffer */
1382 for (i = 1; i <= (int)result[0]; i++) {
1384 result[i] = j >= 0 ? n[j] : 0;
1388 /* Free temporary arrays */
1389 smemclr(m, mlen * sizeof(*m));
1391 smemclr(n, plen * sizeof(*n));
1396 * Decrement a number.
1398 void decbn(Bignum bn)
1401 while (i < (int)bn[0] && bn[i] == 0)
1402 bn[i++] = BIGNUM_INT_MASK;
1406 Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
1411 assert(nbytes >= 0 && nbytes < INT_MAX/8);
1413 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
1416 for (i = 1; i <= w; i++)
1418 for (i = nbytes; i--;) {
1419 unsigned char byte = *data++;
1420 result[1 + i / BIGNUM_INT_BYTES] |=
1421 (BignumInt)byte << (8*i % BIGNUM_INT_BITS);
1424 bn_restore_invariant(result);
1428 Bignum bignum_from_bytes_le(const unsigned char *data, int nbytes)
1433 assert(nbytes >= 0 && nbytes < INT_MAX/8);
1435 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
1438 for (i = 1; i <= w; i++)
1440 for (i = 0; i < nbytes; ++i) {
1441 unsigned char byte = *data++;
1442 result[1 + i / BIGNUM_INT_BYTES] |=
1443 (BignumInt)byte << (8*i % BIGNUM_INT_BITS);
1446 bn_restore_invariant(result);
1450 Bignum bignum_from_decimal(const char *decimal)
1452 Bignum result = copybn(Zero);
1457 if (!isdigit((unsigned char)*decimal)) {
1462 tmp = bigmul(result, Ten);
1463 tmp2 = bignum_from_long(*decimal - '0');
1464 result = bigadd(tmp, tmp2);
1474 Bignum bignum_random_in_range(const Bignum lower, const Bignum upper)
1477 unsigned char *bytes;
1478 int upper_len = bignum_bitcount(upper);
1479 int upper_bytes = upper_len / 8;
1480 int upper_bits = upper_len % 8;
1481 if (upper_bits) ++upper_bytes;
1483 bytes = snewn(upper_bytes, unsigned char);
1487 if (ret) freebn(ret);
1489 for (i = 0; i < upper_bytes; ++i)
1491 bytes[i] = (unsigned char)random_byte();
1493 /* Mask the top to reduce failure rate to 50/50 */
1496 bytes[i - 1] &= 0xFF >> (8 - upper_bits);
1499 ret = bignum_from_bytes(bytes, upper_bytes);
1500 } while (bignum_cmp(ret, lower) < 0 || bignum_cmp(ret, upper) > 0);
1501 smemclr(bytes, upper_bytes);
1508 * Read an SSH-1-format bignum from a data buffer. Return the number
1509 * of bytes consumed, or -1 if there wasn't enough data.
1511 int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)
1513 const unsigned char *p = data;
1521 for (i = 0; i < 2; i++)
1522 w = (w << 8) + *p++;
1523 b = (w + 7) / 8; /* bits -> bytes */
1528 if (!result) /* just return length */
1531 *result = bignum_from_bytes(p, b);
1533 return p + b - data;
1537 * Return the bit count of a bignum, for SSH-1 encoding.
1539 int bignum_bitcount(Bignum bn)
1541 int bitcount = bn[0] * BIGNUM_INT_BITS - 1;
1542 while (bitcount >= 0
1543 && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;
1544 return bitcount + 1;
1548 * Return the byte length of a bignum when SSH-1 encoded.
1550 int ssh1_bignum_length(Bignum bn)
1552 return 2 + (bignum_bitcount(bn) + 7) / 8;
1556 * Return the byte length of a bignum when SSH-2 encoded.
1558 int ssh2_bignum_length(Bignum bn)
1560 return 4 + (bignum_bitcount(bn) + 8) / 8;
1564 * Return a byte from a bignum; 0 is least significant, etc.
1566 int bignum_byte(Bignum bn, int i)
1568 if (i < 0 || i >= (int)(BIGNUM_INT_BYTES * bn[0]))
1569 return 0; /* beyond the end */
1571 return (bn[i / BIGNUM_INT_BYTES + 1] >>
1572 ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;
1576 * Return a bit from a bignum; 0 is least significant, etc.
1578 int bignum_bit(Bignum bn, int i)
1580 if (i < 0 || i >= (int)(BIGNUM_INT_BITS * bn[0]))
1581 return 0; /* beyond the end */
1583 return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;
1587 * Set a bit in a bignum; 0 is least significant, etc.
1589 void bignum_set_bit(Bignum bn, int bitnum, int value)
1591 if (bitnum < 0 || bitnum >= (int)(BIGNUM_INT_BITS * bn[0])) {
1592 if (value) abort(); /* beyond the end */
1594 int v = bitnum / BIGNUM_INT_BITS + 1;
1595 BignumInt mask = (BignumInt)1 << (bitnum % BIGNUM_INT_BITS);
1604 * Write a SSH-1-format bignum into a buffer. It is assumed the
1605 * buffer is big enough. Returns the number of bytes used.
1607 int ssh1_write_bignum(void *data, Bignum bn)
1609 unsigned char *p = data;
1610 int len = ssh1_bignum_length(bn);
1612 int bitc = bignum_bitcount(bn);
1614 *p++ = (bitc >> 8) & 0xFF;
1615 *p++ = (bitc) & 0xFF;
1616 for (i = len - 2; i--;)
1617 *p++ = bignum_byte(bn, i);
1622 * Compare two bignums. Returns like strcmp.
1624 int bignum_cmp(Bignum a, Bignum b)
1626 int amax = a[0], bmax = b[0];
1629 /* Annoyingly we have two representations of zero */
1630 if (amax == 1 && a[amax] == 0)
1632 if (bmax == 1 && b[bmax] == 0)
1635 assert(amax == 0 || a[amax] != 0);
1636 assert(bmax == 0 || b[bmax] != 0);
1638 i = (amax > bmax ? amax : bmax);
1640 BignumInt aval = (i > amax ? 0 : a[i]);
1641 BignumInt bval = (i > bmax ? 0 : b[i]);
1652 * Right-shift one bignum to form another.
1654 Bignum bignum_rshift(Bignum a, int shift)
1657 int i, shiftw, shiftb, shiftbb, bits;
1662 bits = bignum_bitcount(a) - shift;
1663 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
1666 shiftw = shift / BIGNUM_INT_BITS;
1667 shiftb = shift % BIGNUM_INT_BITS;
1668 shiftbb = BIGNUM_INT_BITS - shiftb;
1670 ai1 = a[shiftw + 1];
1671 for (i = 1; i <= (int)ret[0]; i++) {
1673 ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);
1674 ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;
1682 * Left-shift one bignum to form another.
1684 Bignum bignum_lshift(Bignum a, int shift)
1687 int bits, shiftWords, shiftBits;
1691 bits = bignum_bitcount(a) + shift;
1692 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
1694 shiftWords = shift / BIGNUM_INT_BITS;
1695 shiftBits = shift % BIGNUM_INT_BITS;
1699 memcpy(&ret[1 + shiftWords], &a[1], sizeof(BignumInt) * a[0]);
1704 BignumInt carry = 0;
1706 /* Remember that Bignum[0] is length, so add 1 */
1707 for (i = shiftWords + 1; i < ((int)a[0]) + shiftWords + 1; ++i)
1709 BignumInt from = a[i - shiftWords];
1710 ret[i] = (from << shiftBits) | carry;
1711 carry = from >> (BIGNUM_INT_BITS - shiftBits);
1713 if (carry) ret[i] = carry;
1720 * Non-modular multiplication and addition.
1722 Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
1724 int alen = a[0], blen = b[0];
1725 int mlen = (alen > blen ? alen : blen);
1726 int rlen, i, maxspot;
1728 BignumInt *workspace;
1731 /* mlen space for a, mlen space for b, 2*mlen for result,
1732 * plus scratch space for multiplication */
1733 wslen = mlen * 4 + mul_compute_scratch(mlen);
1734 workspace = snewn(wslen, BignumInt);
1735 for (i = 0; i < mlen; i++) {
1736 workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);
1737 workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);
1740 internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
1741 workspace + 2 * mlen, mlen, workspace + 4 * mlen);
1743 /* now just copy the result back */
1744 rlen = alen + blen + 1;
1745 if (addend && rlen <= (int)addend[0])
1746 rlen = addend[0] + 1;
1749 for (i = 1; i <= (int)ret[0]; i++) {
1750 ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
1756 /* now add in the addend, if any */
1758 BignumCarry carry = 0;
1759 for (i = 1; i <= rlen; i++) {
1760 BignumInt retword = (i <= (int)ret[0] ? ret[i] : 0);
1761 BignumInt addword = (i <= (int)addend[0] ? addend[i] : 0);
1762 BignumADC(ret[i], carry, retword, addword, carry);
1763 if (ret[i] != 0 && i > maxspot)
1769 smemclr(workspace, wslen * sizeof(*workspace));
1775 * Non-modular multiplication.
1777 Bignum bigmul(Bignum a, Bignum b)
1779 return bigmuladd(a, b, NULL);
1785 Bignum bigadd(Bignum a, Bignum b)
1787 int alen = a[0], blen = b[0];
1788 int rlen = (alen > blen ? alen : blen) + 1;
1797 for (i = 1; i <= rlen; i++) {
1798 BignumInt aword = (i <= (int)a[0] ? a[i] : 0);
1799 BignumInt bword = (i <= (int)b[0] ? b[i] : 0);
1800 BignumADC(ret[i], carry, aword, bword, carry);
1801 if (ret[i] != 0 && i > maxspot)
1810 * Subtraction. Returns a-b, or NULL if the result would come out
1811 * negative (recall that this entire bignum module only handles
1812 * positive numbers).
1814 Bignum bigsub(Bignum a, Bignum b)
1816 int alen = a[0], blen = b[0];
1817 int rlen = (alen > blen ? alen : blen);
1826 for (i = 1; i <= rlen; i++) {
1827 BignumInt aword = (i <= (int)a[0] ? a[i] : 0);
1828 BignumInt bword = (i <= (int)b[0] ? b[i] : 0);
1829 BignumADC(ret[i], carry, aword, ~bword, carry);
1830 if (ret[i] != 0 && i > maxspot)
1844 * Create a bignum which is the bitmask covering another one. That
1845 * is, the smallest integer which is >= N and is also one less than
1848 Bignum bignum_bitmask(Bignum n)
1850 Bignum ret = copybn(n);
1855 while (n[i] == 0 && i > 0)
1858 return ret; /* input was zero */
1864 ret[i] = BIGNUM_INT_MASK;
1869 * Convert an unsigned long into a bignum.
1871 Bignum bignum_from_long(unsigned long n)
1873 const int maxwords =
1874 (sizeof(unsigned long) + sizeof(BignumInt) - 1) / sizeof(BignumInt);
1878 ret = newbn(maxwords);
1880 for (i = 0; i < maxwords; i++) {
1881 ret[i+1] = n >> (i * BIGNUM_INT_BITS);
1890 * Add a long to a bignum.
1892 Bignum bignum_add_long(Bignum number, unsigned long n)
1894 const int maxwords =
1895 (sizeof(unsigned long) + sizeof(BignumInt) - 1) / sizeof(BignumInt);
1901 if (words < maxwords)
1908 for (i = 0; i < words; i++) {
1909 BignumInt nword = (i < maxwords ? n >> (i * BIGNUM_INT_BITS) : 0);
1910 BignumInt numword = (i < number[0] ? number[i+1] : 0);
1911 BignumADC(ret[i+1], carry, numword, nword, carry);
1919 * Compute the residue of a bignum, modulo a (max 16-bit) short.
1921 unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
1923 unsigned long mod = modulus, r = 0;
1924 /* Precompute (BIGNUM_INT_MASK+1) % mod */
1925 unsigned long base_r = (BIGNUM_INT_MASK - modulus + 1) % mod;
1928 for (i = number[0]; i > 0; i--) {
1930 * Conceptually, ((r << BIGNUM_INT_BITS) + number[i]) % mod
1932 r = ((r * base_r) + (number[i] % mod)) % mod;
1934 return (unsigned short) r;
1938 void diagbn(char *prefix, Bignum md)
1940 int i, nibbles, morenibbles;
1941 static const char hex[] = "0123456789ABCDEF";
1943 debug(("%s0x", prefix ? prefix : ""));
1945 nibbles = (3 + bignum_bitcount(md)) / 4;
1948 morenibbles = 4 * md[0] - nibbles;
1949 for (i = 0; i < morenibbles; i++)
1951 for (i = nibbles; i--;)
1953 hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
1963 Bignum bigdiv(Bignum a, Bignum b)
1965 Bignum q = newbn(a[0]);
1966 bigdivmod(a, b, NULL, q);
1967 while (q[0] > 1 && q[q[0]] == 0)
1975 Bignum bigmod(Bignum a, Bignum b)
1977 Bignum r = newbn(b[0]);
1978 bigdivmod(a, b, r, NULL);
1979 while (r[0] > 1 && r[r[0]] == 0)
1985 * Greatest common divisor.
1987 Bignum biggcd(Bignum av, Bignum bv)
1989 Bignum a = copybn(av);
1990 Bignum b = copybn(bv);
1992 while (bignum_cmp(b, Zero) != 0) {
1993 Bignum t = newbn(b[0]);
1994 bigdivmod(a, b, t, NULL);
1995 while (t[0] > 1 && t[t[0]] == 0)
2007 * Modular inverse, using Euclid's extended algorithm.
2009 Bignum modinv(Bignum number, Bignum modulus)
2011 Bignum a = copybn(modulus);
2012 Bignum b = copybn(number);
2013 Bignum xp = copybn(Zero);
2014 Bignum x = copybn(One);
2017 assert(number[number[0]] != 0);
2018 assert(modulus[modulus[0]] != 0);
2020 while (bignum_cmp(b, One) != 0) {
2023 if (bignum_cmp(b, Zero) == 0) {
2025 * Found a common factor between the inputs, so we cannot
2026 * return a modular inverse at all.
2037 bigdivmod(a, b, t, q);
2038 while (t[0] > 1 && t[t[0]] == 0)
2040 while (q[0] > 1 && q[q[0]] == 0)
2047 x = bigmuladd(q, xp, t);
2057 /* now we know that sign * x == 1, and that x < modulus */
2059 /* set a new x to be modulus - x */
2060 Bignum newx = newbn(modulus[0]);
2061 BignumInt carry = 0;
2065 for (i = 1; i <= (int)newx[0]; i++) {
2066 BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);
2067 BignumInt bword = (i <= (int)x[0] ? x[i] : 0);
2068 newx[i] = aword - bword - carry;
2070 carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
2084 * Render a bignum into decimal. Return a malloced string holding
2085 * the decimal representation.
2087 char *bignum_decimal(Bignum x)
2089 int ndigits, ndigit;
2093 BignumInt *workspace;
2096 * First, estimate the number of digits. Since log(10)/log(2)
2097 * is just greater than 93/28 (the joys of continued fraction
2098 * approximations...) we know that for every 93 bits, we need
2099 * at most 28 digits. This will tell us how much to malloc.
2101 * Formally: if x has i bits, that means x is strictly less
2102 * than 2^i. Since 2 is less than 10^(28/93), this is less than
2103 * 10^(28i/93). We need an integer power of ten, so we must
2104 * round up (rounding down might make it less than x again).
2105 * Therefore if we multiply the bit count by 28/93, rounding
2106 * up, we will have enough digits.
2108 * i=0 (i.e., x=0) is an irritating special case.
2110 i = bignum_bitcount(x);
2112 ndigits = 1; /* x = 0 */
2114 ndigits = (28 * i + 92) / 93; /* multiply by 28/93 and round up */
2115 ndigits++; /* allow for trailing \0 */
2116 ret = snewn(ndigits, char);
2119 * Now allocate some workspace to hold the binary form as we
2120 * repeatedly divide it by ten. Initialise this to the
2121 * big-endian form of the number.
2123 workspace = snewn(x[0], BignumInt);
2124 for (i = 0; i < (int)x[0]; i++)
2125 workspace[i] = x[x[0] - i];
2128 * Next, write the decimal number starting with the last digit.
2129 * We use ordinary short division, dividing 10 into the
2132 ndigit = ndigits - 1;
2137 for (i = 0; i < (int)x[0]; i++) {
2139 * Conceptually, we want to compute
2141 * (carry << BIGNUM_INT_BITS) + workspace[i]
2142 * -----------------------------------------
2145 * but we don't have an integer type longer than BignumInt
2146 * to work with. So we have to do it in pieces.
2150 q = workspace[i] / 10;
2151 r = workspace[i] % 10;
2153 /* I want (BIGNUM_INT_MASK+1)/10 but can't say so directly! */
2154 q += carry * ((BIGNUM_INT_MASK-9) / 10 + 1);
2155 r += carry * ((BIGNUM_INT_MASK-9) % 10);
2166 ret[--ndigit] = (char) (carry + '0');
2170 * There's a chance we've fallen short of the start of the
2171 * string. Correct if so.
2174 memmove(ret, ret + ndigit, ndigits - ndigit);
2179 smemclr(workspace, x[0] * sizeof(*workspace));