2 * Bignum routines for RSA and DH and stuff.
\r
16 #define BIGNUM_INTERNAL
\r
17 typedef BignumInt *Bignum;
\r
21 BignumInt bnZero[1] = { 0 };
\r
22 BignumInt bnOne[2] = { 1, 1 };
\r
23 BignumInt bnTen[2] = { 1, 10 };
\r
26 * The Bignum format is an array of `BignumInt'. The first
\r
27 * element of the array counts the remaining elements. The
\r
28 * remaining elements express the actual number, base 2^BIGNUM_INT_BITS, _least_
\r
29 * significant digit first. (So it's trivial to extract the bit
\r
30 * with value 2^n for any n.)
\r
32 * All Bignums in this module are positive. Negative numbers must
\r
33 * be dealt with outside it.
\r
35 * INVARIANT: the most significant word of any Bignum must be
\r
39 Bignum Zero = bnZero, One = bnOne, Ten = bnTen;
\r
41 static Bignum newbn(int length)
\r
45 assert(length >= 0 && length < INT_MAX / BIGNUM_INT_BITS);
\r
47 b = snewn(length + 1, BignumInt);
\r
48 memset(b, 0, (length + 1) * sizeof(*b));
\r
53 void bn_restore_invariant(Bignum b)
\r
55 while (b[0] > 1 && b[b[0]] == 0)
\r
59 Bignum copybn(Bignum orig)
\r
61 Bignum b = snewn(orig[0] + 1, BignumInt);
\r
63 abort(); /* FIXME */
\r
64 memcpy(b, orig, (orig[0] + 1) * sizeof(*b));
\r
68 void freebn(Bignum b)
\r
71 * Burn the evidence, just in case.
\r
73 smemclr(b, sizeof(b[0]) * (b[0] + 1));
\r
77 Bignum bn_power_2(int n)
\r
83 ret = newbn(n / BIGNUM_INT_BITS + 1);
\r
84 bignum_set_bit(ret, n, 1);
\r
89 * Internal addition. Sets c = a - b, where 'a', 'b' and 'c' are all
\r
90 * big-endian arrays of 'len' BignumInts. Returns the carry off the
\r
93 static BignumCarry internal_add(const BignumInt *a, const BignumInt *b,
\r
94 BignumInt *c, int len)
\r
97 BignumCarry carry = 0;
\r
99 for (i = len-1; i >= 0; i--)
\r
100 BignumADC(c[i], carry, a[i], b[i], carry);
\r
102 return (BignumInt)carry;
\r
106 * Internal subtraction. Sets c = a - b, where 'a', 'b' and 'c' are
\r
107 * all big-endian arrays of 'len' BignumInts. Any borrow from the top
\r
110 static void internal_sub(const BignumInt *a, const BignumInt *b,
\r
111 BignumInt *c, int len)
\r
114 BignumCarry carry = 1;
\r
116 for (i = len-1; i >= 0; i--)
\r
117 BignumADC(c[i], carry, a[i], ~b[i], carry);
\r
121 * Compute c = a * b.
\r
122 * Input is in the first len words of a and b.
\r
123 * Result is returned in the first 2*len words of c.
\r
125 * 'scratch' must point to an array of BignumInt of size at least
\r
126 * mul_compute_scratch(len). (This covers the needs of internal_mul
\r
127 * and all its recursive calls to itself.)
\r
129 #define KARATSUBA_THRESHOLD 50
\r
130 static int mul_compute_scratch(int len)
\r
133 while (len > KARATSUBA_THRESHOLD) {
\r
134 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
\r
135 int midlen = botlen + 1;
\r
141 static void internal_mul(const BignumInt *a, const BignumInt *b,
\r
142 BignumInt *c, int len, BignumInt *scratch)
\r
144 if (len > KARATSUBA_THRESHOLD) {
\r
148 * Karatsuba divide-and-conquer algorithm. Cut each input in
\r
149 * half, so that it's expressed as two big 'digits' in a giant
\r
155 * Then the product is of course
\r
157 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
\r
159 * and we compute the three coefficients by recursively
\r
160 * calling ourself to do half-length multiplications.
\r
162 * The clever bit that makes this worth doing is that we only
\r
163 * need _one_ half-length multiplication for the central
\r
164 * coefficient rather than the two that it obviouly looks
\r
165 * like, because we can use a single multiplication to compute
\r
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
\r
169 * and then we subtract the other two coefficients (a_1 b_1
\r
170 * and a_0 b_0) which we were computing anyway.
\r
172 * Hence we get to multiply two numbers of length N in about
\r
173 * three times as much work as it takes to multiply numbers of
\r
174 * length N/2, which is obviously better than the four times
\r
175 * as much work it would take if we just did a long
\r
176 * conventional multiply.
\r
179 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
\r
180 int midlen = botlen + 1;
\r
187 * The coefficients a_1 b_1 and a_0 b_0 just avoid overlapping
\r
188 * in the output array, so we can compute them immediately in
\r
193 printf("a1,a0 = 0x");
\r
194 for (i = 0; i < len; i++) {
\r
195 if (i == toplen) printf(", 0x");
\r
196 printf("%0*x", BIGNUM_INT_BITS/4, a[i]);
\r
199 printf("b1,b0 = 0x");
\r
200 for (i = 0; i < len; i++) {
\r
201 if (i == toplen) printf(", 0x");
\r
202 printf("%0*x", BIGNUM_INT_BITS/4, b[i]);
\r
208 internal_mul(a, b, c, toplen, scratch);
\r
210 printf("a1b1 = 0x");
\r
211 for (i = 0; i < 2*toplen; i++) {
\r
212 printf("%0*x", BIGNUM_INT_BITS/4, c[i]);
\r
218 internal_mul(a + toplen, b + toplen, c + 2*toplen, botlen, scratch);
\r
220 printf("a0b0 = 0x");
\r
221 for (i = 0; i < 2*botlen; i++) {
\r
222 printf("%0*x", BIGNUM_INT_BITS/4, c[2*toplen+i]);
\r
227 /* Zero padding. midlen exceeds toplen by at most 2, so just
\r
228 * zero the first two words of each input and the rest will be
\r
230 scratch[0] = scratch[1] = scratch[midlen] = scratch[midlen+1] = 0;
\r
232 for (i = 0; i < toplen; i++) {
\r
233 scratch[midlen - toplen + i] = a[i]; /* a_1 */
\r
234 scratch[2*midlen - toplen + i] = b[i]; /* b_1 */
\r
237 /* compute a_1 + a_0 */
\r
238 scratch[0] = internal_add(scratch+1, a+toplen, scratch+1, botlen);
\r
240 printf("a1plusa0 = 0x");
\r
241 for (i = 0; i < midlen; i++) {
\r
242 printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);
\r
246 /* compute b_1 + b_0 */
\r
247 scratch[midlen] = internal_add(scratch+midlen+1, b+toplen,
\r
248 scratch+midlen+1, botlen);
\r
250 printf("b1plusb0 = 0x");
\r
251 for (i = 0; i < midlen; i++) {
\r
252 printf("%0*x", BIGNUM_INT_BITS/4, scratch[midlen+i]);
\r
258 * Now we can do the third multiplication.
\r
260 internal_mul(scratch, scratch + midlen, scratch + 2*midlen, midlen,
\r
261 scratch + 4*midlen);
\r
263 printf("a1plusa0timesb1plusb0 = 0x");
\r
264 for (i = 0; i < 2*midlen; i++) {
\r
265 printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);
\r
271 * Now we can reuse the first half of 'scratch' to compute the
\r
272 * sum of the outer two coefficients, to subtract from that
\r
273 * product to obtain the middle one.
\r
275 scratch[0] = scratch[1] = scratch[2] = scratch[3] = 0;
\r
276 for (i = 0; i < 2*toplen; i++)
\r
277 scratch[2*midlen - 2*toplen + i] = c[i];
\r
278 scratch[1] = internal_add(scratch+2, c + 2*toplen,
\r
279 scratch+2, 2*botlen);
\r
281 printf("a1b1plusa0b0 = 0x");
\r
282 for (i = 0; i < 2*midlen; i++) {
\r
283 printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);
\r
288 internal_sub(scratch + 2*midlen, scratch,
\r
289 scratch + 2*midlen, 2*midlen);
\r
291 printf("a1b0plusa0b1 = 0x");
\r
292 for (i = 0; i < 2*midlen; i++) {
\r
293 printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);
\r
299 * And now all we need to do is to add that middle coefficient
\r
300 * back into the output. We may have to propagate a carry
\r
301 * further up the output, but we can be sure it won't
\r
302 * propagate right the way off the top.
\r
304 carry = internal_add(c + 2*len - botlen - 2*midlen,
\r
305 scratch + 2*midlen,
\r
306 c + 2*len - botlen - 2*midlen, 2*midlen);
\r
307 i = 2*len - botlen - 2*midlen - 1;
\r
310 BignumADC(c[i], carry, c[i], 0, carry);
\r
315 for (i = 0; i < 2*len; i++) {
\r
316 printf("%0*x", BIGNUM_INT_BITS/4, c[i]);
\r
324 const BignumInt *ap, *bp;
\r
325 BignumInt *cp, *cps;
\r
328 * Multiply in the ordinary O(N^2) way.
\r
331 for (i = 0; i < 2 * len; i++)
\r
334 for (cps = c + 2*len, ap = a + len; ap-- > a; cps--) {
\r
336 for (cp = cps, bp = b + len; cp--, bp-- > b ;)
\r
337 BignumMULADD2(carry, *cp, *ap, *bp, *cp, carry);
\r
344 * Variant form of internal_mul used for the initial step of
\r
345 * Montgomery reduction. Only bothers outputting 'len' words
\r
346 * (everything above that is thrown away).
\r
348 static void internal_mul_low(const BignumInt *a, const BignumInt *b,
\r
349 BignumInt *c, int len, BignumInt *scratch)
\r
351 if (len > KARATSUBA_THRESHOLD) {
\r
355 * Karatsuba-aware version of internal_mul_low. As before, we
\r
356 * express each input value as a shifted combination of two
\r
362 * Then the full product is, as before,
\r
364 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
\r
366 * Provided we choose D on the large side (so that a_0 and b_0
\r
367 * are _at least_ as long as a_1 and b_1), we don't need the
\r
368 * topmost term at all, and we only need half of the middle
\r
369 * term. So there's no point in doing the proper Karatsuba
\r
370 * optimisation which computes the middle term using the top
\r
371 * one, because we'd take as long computing the top one as
\r
372 * just computing the middle one directly.
\r
374 * So instead, we do a much more obvious thing: we call the
\r
375 * fully optimised internal_mul to compute a_0 b_0, and we
\r
376 * recursively call ourself to compute the _bottom halves_ of
\r
377 * a_1 b_0 and a_0 b_1, each of which we add into the result
\r
378 * in the obvious way.
\r
380 * In other words, there's no actual Karatsuba _optimisation_
\r
381 * in this function; the only benefit in doing it this way is
\r
382 * that we call internal_mul proper for a large part of the
\r
383 * work, and _that_ can optimise its operation.
\r
386 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
\r
389 * Scratch space for the various bits and pieces we're going
\r
390 * to be adding together: we need botlen*2 words for a_0 b_0
\r
391 * (though we may end up throwing away its topmost word), and
\r
392 * toplen words for each of a_1 b_0 and a_0 b_1. That adds up
\r
393 * to exactly 2*len.
\r
397 internal_mul(a + toplen, b + toplen, scratch + 2*toplen, botlen,
\r
401 internal_mul_low(a, b + len - toplen, scratch + toplen, toplen,
\r
405 internal_mul_low(a + len - toplen, b, scratch, toplen,
\r
408 /* Copy the bottom half of the big coefficient into place */
\r
409 for (i = 0; i < botlen; i++)
\r
410 c[toplen + i] = scratch[2*toplen + botlen + i];
\r
412 /* Add the two small coefficients, throwing away the returned carry */
\r
413 internal_add(scratch, scratch + toplen, scratch, toplen);
\r
415 /* And add that to the large coefficient, leaving the result in c. */
\r
416 internal_add(scratch, scratch + 2*toplen + botlen - toplen,
\r
422 const BignumInt *ap, *bp;
\r
423 BignumInt *cp, *cps;
\r
426 * Multiply in the ordinary O(N^2) way.
\r
429 for (i = 0; i < len; i++)
\r
432 for (cps = c + len, ap = a + len; ap-- > a; cps--) {
\r
434 for (cp = cps, bp = b + len; bp--, cp-- > c ;)
\r
435 BignumMULADD2(carry, *cp, *ap, *bp, *cp, carry);
\r
441 * Montgomery reduction. Expects x to be a big-endian array of 2*len
\r
442 * BignumInts whose value satisfies 0 <= x < rn (where r = 2^(len *
\r
443 * BIGNUM_INT_BITS) is the Montgomery base). Returns in the same array
\r
444 * a value x' which is congruent to xr^{-1} mod n, and satisfies 0 <=
\r
447 * 'n' and 'mninv' should be big-endian arrays of 'len' BignumInts
\r
448 * each, containing respectively n and the multiplicative inverse of
\r
451 * 'tmp' is an array of BignumInt used as scratch space, of length at
\r
452 * least 3*len + mul_compute_scratch(len).
\r
454 static void monty_reduce(BignumInt *x, const BignumInt *n,
\r
455 const BignumInt *mninv, BignumInt *tmp, int len)
\r
461 * Multiply x by (-n)^{-1} mod r. This gives us a value m such
\r
462 * that mn is congruent to -x mod r. Hence, mn+x is an exact
\r
463 * multiple of r, and is also (obviously) congruent to x mod n.
\r
465 internal_mul_low(x + len, mninv, tmp, len, tmp + 3*len);
\r
468 * Compute t = (mn+x)/r in ordinary, non-modular, integer
\r
469 * arithmetic. By construction this is exact, and is congruent mod
\r
470 * n to x * r^{-1}, i.e. the answer we want.
\r
472 * The following multiply leaves that answer in the _most_
\r
473 * significant half of the 'x' array, so then we must shift it
\r
476 internal_mul(tmp, n, tmp+len, len, tmp + 3*len);
\r
477 carry = internal_add(x, tmp+len, x, 2*len);
\r
478 for (i = 0; i < len; i++)
\r
479 x[len + i] = x[i], x[i] = 0;
\r
482 * Reduce t mod n. This doesn't require a full-on division by n,
\r
483 * but merely a test and single optional subtraction, since we can
\r
484 * show that 0 <= t < 2n.
\r
487 * + we computed m mod r, so 0 <= m < r.
\r
488 * + so 0 <= mn < rn, obviously
\r
489 * + hence we only need 0 <= x < rn to guarantee that 0 <= mn+x < 2rn
\r
490 * + yielding 0 <= (mn+x)/r < 2n as required.
\r
493 for (i = 0; i < len; i++)
\r
494 if (x[len + i] != n[i])
\r
497 if (carry || i >= len || x[len + i] > n[i])
\r
498 internal_sub(x+len, n, x+len, len);
\r
501 static void internal_add_shifted(BignumInt *number,
\r
502 BignumInt n, int shift)
\r
504 int word = 1 + (shift / BIGNUM_INT_BITS);
\r
505 int bshift = shift % BIGNUM_INT_BITS;
\r
506 BignumInt addendh, addendl;
\r
509 addendl = n << bshift;
\r
510 addendh = (bshift == 0 ? 0 : n >> (BIGNUM_INT_BITS - bshift));
\r
512 assert(word <= number[0]);
\r
513 BignumADC(number[word], carry, number[word], addendl, 0);
\r
515 if (!addendh && !carry)
\r
517 assert(word <= number[0]);
\r
518 BignumADC(number[word], carry, number[word], addendh, carry);
\r
521 assert(word <= number[0]);
\r
522 BignumADC(number[word], carry, number[word], 0, carry);
\r
527 static int bn_clz(BignumInt x)
\r
530 * Count the leading zero bits in x. Equivalently, how far left
\r
531 * would we need to shift x to make its top bit set?
\r
533 * Precondition: x != 0.
\r
536 /* FIXME: would be nice to put in some compiler intrinsics under
\r
539 for (i = BIGNUM_INT_BITS / 2; i != 0; i >>= 1) {
\r
540 if ((x >> (BIGNUM_INT_BITS-i)) == 0) {
\r
548 static BignumInt reciprocal_word(BignumInt d)
\r
550 BignumInt dshort, recip, prodh, prodl;
\r
554 * Input: a BignumInt value d, with its top bit set.
\r
556 assert(d >> (BIGNUM_INT_BITS-1) == 1);
\r
559 * Output: a value, shifted to fill a BignumInt, which is strictly
\r
560 * less than 1/(d+1), i.e. is an *under*-estimate (but by as
\r
561 * little as possible within the constraints) of the reciprocal of
\r
562 * any number whose first BIGNUM_INT_BITS bits match d.
\r
564 * Ideally we'd like to _totally_ fill BignumInt, i.e. always
\r
565 * return a value with the top bit set. Unfortunately we can't
\r
566 * quite guarantee that for all inputs and also return a fixed
\r
567 * exponent. So instead we take our reciprocal to be
\r
568 * 2^(BIGNUM_INT_BITS*2-1) / d, so that it has the top bit clear
\r
569 * only in the exceptional case where d takes exactly the maximum
\r
570 * value BIGNUM_INT_MASK; in that case, the top bit is clear and
\r
571 * the next bit down is set.
\r
575 * Start by computing a half-length version of the answer, by
\r
576 * straightforward division within a BignumInt.
\r
578 dshort = (d >> (BIGNUM_INT_BITS/2)) + 1;
\r
579 recip = (BIGNUM_TOP_BIT + dshort - 1) / dshort;
\r
580 recip <<= BIGNUM_INT_BITS - BIGNUM_INT_BITS/2;
\r
583 * Newton-Raphson iteration to improve that starting reciprocal
\r
584 * estimate: take f(x) = d - 1/x, and then the N-R formula gives
\r
585 * x_new = x - f(x)/f'(x) = x - (d-1/x)/(1/x^2) = x(2-d*x). Or,
\r
586 * taking our fixed-point representation into account, take f(x)
\r
587 * to be d - K/x (where K = 2^(BIGNUM_INT_BITS*2-1) as discussed
\r
588 * above) and then we get (2K - d*x) * x/K.
\r
590 * Newton-Raphson doubles the number of correct bits at every
\r
591 * iteration, and the initial division above already gave us half
\r
592 * the output word, so it's only worth doing one iteration.
\r
594 BignumMULADD(prodh, prodl, recip, d, recip);
\r
599 BignumADC(prodl, c, prodl, 1, 0);
\r
602 BignumMUL(prodh, prodl, prodh, recip);
\r
603 recip = (prodh << 1) | (prodl >> (BIGNUM_INT_BITS-1));
\r
606 * Now make sure we have the best possible reciprocal estimate,
\r
607 * before we return it. We might have been off by a handful either
\r
608 * way - not enough to bother with any better-thought-out kind of
\r
611 BignumMULADD(prodh, prodl, recip, d, recip);
\r
613 if (prodh >= BIGNUM_TOP_BIT) {
\r
616 BignumADC(prodl, c, prodl, ~d, c); prodh += BIGNUM_INT_MASK + c;
\r
619 } while (prodh >= ((BignumInt)1 << (BIGNUM_INT_BITS-1)));
\r
622 BignumInt newprodh, newprodl;
\r
624 BignumADC(newprodl, c, prodl, d, c); newprodh = prodh + c;
\r
625 if (newprodh >= BIGNUM_TOP_BIT)
\r
638 * Compute a = a % m.
\r
639 * Input in first alen words of a and first mlen words of m.
\r
640 * Output in first alen words of a
\r
641 * (of which first alen-mlen words will be zero).
\r
642 * Quotient is accumulated in the `quotient' array, which is a Bignum
\r
643 * rather than the internal bigendian format.
\r
645 * 'recip' must be the result of calling reciprocal_word() on the top
\r
646 * BIGNUM_INT_BITS of the modulus (denoted m0 in comments below), with
\r
647 * the topmost set bit normalised to the MSB of the input to
\r
648 * reciprocal_word. 'rshift' is how far left the top nonzero word of
\r
649 * the modulus had to be shifted to set that top bit.
\r
651 static void internal_mod(BignumInt *a, int alen,
\r
652 BignumInt *m, int mlen,
\r
653 BignumInt *quot, BignumInt recip, int rshift)
\r
657 #ifdef DIVISION_DEBUG
\r
660 printf("start division, m=0x");
\r
661 for (d = 0; d < mlen; d++)
\r
662 printf("%0*llx", BIGNUM_INT_BITS/4, (unsigned long long)m[d]);
\r
663 printf(", recip=%#0*llx, rshift=%d\n",
\r
664 BIGNUM_INT_BITS/4, (unsigned long long)recip, rshift);
\r
669 * Repeatedly use that reciprocal estimate to get a decent number
\r
670 * of quotient bits, and subtract off the resulting multiple of m.
\r
672 * Normally we expect to terminate this loop by means of finding
\r
673 * out q=0 part way through, but one way in which we might not get
\r
674 * that far in the first place is if the input a is actually zero,
\r
675 * in which case we'll discard zero words from the front of a
\r
676 * until we reach the termination condition in the for statement
\r
679 for (i = 0; i <= alen - mlen ;) {
\r
681 BignumInt aword, q;
\r
682 int shift, full_bitoffset, bitoffset, wordoffset;
\r
684 #ifdef DIVISION_DEBUG
\r
687 printf("main loop, a=0x");
\r
688 for (d = 0; d < alen; d++)
\r
689 printf("%0*llx", BIGNUM_INT_BITS/4, (unsigned long long)a[d]);
\r
695 #ifdef DIVISION_DEBUG
\r
696 printf("zero word at i=%d\n", i);
\r
703 shift = bn_clz(aword);
\r
705 if (shift > 0 && i+1 < alen)
\r
706 aword |= a[i+1] >> (BIGNUM_INT_BITS - shift);
\r
710 BignumMUL(q, unused, recip, aword);
\r
714 #ifdef DIVISION_DEBUG
\r
715 printf("i=%d, aword=%#0*llx, shift=%d, q=%#0*llx\n",
\r
716 i, BIGNUM_INT_BITS/4, (unsigned long long)aword,
\r
717 shift, BIGNUM_INT_BITS/4, (unsigned long long)q);
\r
721 * Work out the right bit and word offsets to use when
\r
722 * subtracting q*m from a.
\r
724 * aword was taken from a[i], which means its LSB was at bit
\r
725 * position (alen-1-i) * BIGNUM_INT_BITS. But then we shifted
\r
726 * it left by 'shift', so now the low bit of aword corresponds
\r
727 * to bit position (alen-1-i) * BIGNUM_INT_BITS - shift, i.e.
\r
728 * aword is approximately equal to a / 2^(that).
\r
730 * m0 comes from the top word of mod, so its LSB is at bit
\r
731 * position (mlen-1) * BIGNUM_INT_BITS - rshift, i.e. it can
\r
732 * be considered to be m / 2^(that power). 'recip' is the
\r
733 * reciprocal of m0, times 2^(BIGNUM_INT_BITS*2-1), i.e. it's
\r
734 * about 2^((mlen+1) * BIGNUM_INT_BITS - rshift - 1) / m.
\r
736 * Hence, recip * aword is approximately equal to the product
\r
737 * of those, which simplifies to
\r
739 * a/m * 2^((mlen+2+i-alen)*BIGNUM_INT_BITS + shift - rshift - 1)
\r
741 * But we've also shifted recip*aword down by BIGNUM_INT_BITS
\r
742 * to form q, so we have
\r
744 * q ~= a/m * 2^((mlen+1+i-alen)*BIGNUM_INT_BITS + shift - rshift - 1)
\r
746 * and hence, when we now compute q*m, it will be about
\r
747 * a*2^(all that lot), i.e. the negation of that expression is
\r
748 * how far left we have to shift the product q*m to make it
\r
749 * approximately equal to a.
\r
751 full_bitoffset = -((mlen+1+i-alen)*BIGNUM_INT_BITS + shift-rshift-1);
\r
752 #ifdef DIVISION_DEBUG
\r
753 printf("full_bitoffset=%d\n", full_bitoffset);
\r
756 if (full_bitoffset < 0) {
\r
758 * If we find ourselves needing to shift q*m _right_, that
\r
759 * means we've reached the bottom of the quotient. Clip q
\r
760 * so that its right shift becomes zero, and if that means
\r
761 * q becomes _actually_ zero, this loop is done.
\r
763 if (full_bitoffset <= -BIGNUM_INT_BITS)
\r
765 q >>= -full_bitoffset;
\r
766 full_bitoffset = 0;
\r
769 #ifdef DIVISION_DEBUG
\r
770 printf("now full_bitoffset=%d, q=%#0*llx\n",
\r
771 full_bitoffset, BIGNUM_INT_BITS/4, (unsigned long long)q);
\r
775 wordoffset = full_bitoffset / BIGNUM_INT_BITS;
\r
776 bitoffset = full_bitoffset % BIGNUM_INT_BITS;
\r
777 #ifdef DIVISION_DEBUG
\r
778 printf("wordoffset=%d, bitoffset=%d\n", wordoffset, bitoffset);
\r
781 /* wordoffset as computed above is the offset between the LSWs
\r
782 * of m and a. But in fact m and a are stored MSW-first, so we
\r
783 * need to adjust it to be the offset between the actual array
\r
784 * indices, and flip the sign too. */
\r
785 wordoffset = alen - mlen - wordoffset;
\r
787 if (bitoffset == 0) {
\r
789 BignumInt prev_hi_word = 0;
\r
790 for (k = mlen - 1; wordoffset+k >= i; k--) {
\r
791 BignumInt mword = k<0 ? 0 : m[k];
\r
792 BignumMULADD(prev_hi_word, product, q, mword, prev_hi_word);
\r
793 #ifdef DIVISION_DEBUG
\r
794 printf(" aligned sub: product word for m[%d] = %#0*llx\n",
\r
795 k, BIGNUM_INT_BITS/4,
\r
796 (unsigned long long)product);
\r
798 #ifdef DIVISION_DEBUG
\r
799 printf(" aligned sub: subtrahend for a[%d] = %#0*llx\n",
\r
800 wordoffset+k, BIGNUM_INT_BITS/4,
\r
801 (unsigned long long)product);
\r
803 BignumADC(a[wordoffset+k], c, a[wordoffset+k], ~product, c);
\r
806 BignumInt add_word = 0;
\r
808 BignumInt prev_hi_word = 0;
\r
809 for (k = mlen - 1; wordoffset+k >= i; k--) {
\r
810 BignumInt mword = k<0 ? 0 : m[k];
\r
811 BignumMULADD(prev_hi_word, product, q, mword, prev_hi_word);
\r
812 #ifdef DIVISION_DEBUG
\r
813 printf(" unaligned sub: product word for m[%d] = %#0*llx\n",
\r
814 k, BIGNUM_INT_BITS/4,
\r
815 (unsigned long long)product);
\r
818 add_word |= product << bitoffset;
\r
820 #ifdef DIVISION_DEBUG
\r
821 printf(" unaligned sub: subtrahend for a[%d] = %#0*llx\n",
\r
823 BIGNUM_INT_BITS/4, (unsigned long long)add_word);
\r
825 BignumADC(a[wordoffset+k], c, a[wordoffset+k], ~add_word, c);
\r
827 add_word = product >> (BIGNUM_INT_BITS - bitoffset);
\r
832 #ifdef DIVISION_DEBUG
\r
833 printf("adding quotient word %#0*llx << %d\n",
\r
834 BIGNUM_INT_BITS/4, (unsigned long long)q, full_bitoffset);
\r
836 internal_add_shifted(quot, q, full_bitoffset);
\r
837 #ifdef DIVISION_DEBUG
\r
840 printf("now quot=0x");
\r
841 for (d = quot[0]; d > 0; d--)
\r
842 printf("%0*llx", BIGNUM_INT_BITS/4,
\r
843 (unsigned long long)quot[d]);
\r
850 #ifdef DIVISION_DEBUG
\r
853 printf("end main loop, a=0x");
\r
854 for (d = 0; d < alen; d++)
\r
855 printf("%0*llx", BIGNUM_INT_BITS/4, (unsigned long long)a[d]);
\r
857 printf(", quot=0x");
\r
858 for (d = quot[0]; d > 0; d--)
\r
859 printf("%0*llx", BIGNUM_INT_BITS/4,
\r
860 (unsigned long long)quot[d]);
\r
867 * The above loop should terminate with the remaining value in a
\r
868 * being strictly less than 2*m (if a >= 2*m then we should always
\r
869 * have managed to get a nonzero q word), but we can't guarantee
\r
870 * that it will be strictly less than m: consider a case where the
\r
871 * remainder is 1, and another where the remainder is m-1. By the
\r
872 * time a contains a value that's _about m_, you clearly can't
\r
873 * distinguish those cases by looking at only the top word of a -
\r
874 * you have to go all the way down to the bottom before you find
\r
875 * out whether it's just less or just more than m.
\r
877 * Hence, we now do a final fixup in which we subtract one last
\r
878 * copy of m, or don't, accordingly. We should never have to
\r
879 * subtract more than one copy of m here.
\r
881 for (i = 0; i < alen; i++) {
\r
882 /* Compare a with m, word by word, from the MSW down. As soon
\r
883 * as we encounter a difference, we know whether we need the
\r
885 int mindex = mlen-alen+i;
\r
886 BignumInt mword = mindex < 0 ? 0 : m[mindex];
\r
887 if (a[i] < mword) {
\r
888 #ifdef DIVISION_DEBUG
\r
889 printf("final fixup not needed, a < m\n");
\r
892 } else if (a[i] > mword) {
\r
893 #ifdef DIVISION_DEBUG
\r
894 printf("final fixup is needed, a > m\n");
\r
898 /* If neither of those cases happened, the words are the same,
\r
899 * so keep going and look at the next one. */
\r
901 #ifdef DIVISION_DEBUG
\r
902 if (i == mlen) /* if we printed neither of the above diagnostics */
\r
903 printf("final fixup is needed, a == m\n");
\r
907 * If we got here without returning, then a >= m, so we must
\r
908 * subtract m, and increment the quotient.
\r
912 for (i = alen - 1; i >= 0; i--) {
\r
913 int mindex = mlen-alen+i;
\r
914 BignumInt mword = mindex < 0 ? 0 : m[mindex];
\r
915 BignumADC(a[i], c, a[i], ~mword, c);
\r
919 internal_add_shifted(quot, 1, 0);
\r
921 #ifdef DIVISION_DEBUG
\r
924 printf("after final fixup, a=0x");
\r
925 for (d = 0; d < alen; d++)
\r
926 printf("%0*llx", BIGNUM_INT_BITS/4, (unsigned long long)a[d]);
\r
928 printf(", quot=0x");
\r
929 for (d = quot[0]; d > 0; d--)
\r
930 printf("%0*llx", BIGNUM_INT_BITS/4,
\r
931 (unsigned long long)quot[d]);
\r
939 * Compute (base ^ exp) % mod, the pedestrian way.
\r
941 Bignum modpow_simple(Bignum base_in, Bignum exp, Bignum mod)
\r
943 BignumInt *a, *b, *n, *m, *scratch;
\r
946 int mlen, scratchlen, i, j;
\r
947 Bignum base, result;
\r
950 * The most significant word of mod needs to be non-zero. It
\r
951 * should already be, but let's make sure.
\r
953 assert(mod[mod[0]] != 0);
\r
956 * Make sure the base is smaller than the modulus, by reducing
\r
957 * it modulo the modulus if not.
\r
959 base = bigmod(base_in, mod);
\r
961 /* Allocate m of size mlen, copy mod to m */
\r
962 /* We use big endian internally */
\r
964 m = snewn(mlen, BignumInt);
\r
965 for (j = 0; j < mlen; j++)
\r
966 m[j] = mod[mod[0] - j];
\r
968 /* Allocate n of size mlen, copy base to n */
\r
969 n = snewn(mlen, BignumInt);
\r
970 i = mlen - base[0];
\r
971 for (j = 0; j < i; j++)
\r
973 for (j = 0; j < (int)base[0]; j++)
\r
974 n[i + j] = base[base[0] - j];
\r
976 /* Allocate a and b of size 2*mlen. Set a = 1 */
\r
977 a = snewn(2 * mlen, BignumInt);
\r
978 b = snewn(2 * mlen, BignumInt);
\r
979 for (i = 0; i < 2 * mlen; i++)
\r
981 a[2 * mlen - 1] = 1;
\r
983 /* Scratch space for multiplies */
\r
984 scratchlen = mul_compute_scratch(mlen);
\r
985 scratch = snewn(scratchlen, BignumInt);
\r
987 /* Skip leading zero bits of exp. */
\r
989 j = BIGNUM_INT_BITS-1;
\r
990 while (i < (int)exp[0] && (exp[exp[0] - i] & ((BignumInt)1 << j)) == 0) {
\r
994 j = BIGNUM_INT_BITS-1;
\r
998 /* Compute reciprocal of the top full word of the modulus */
\r
1000 BignumInt m0 = m[0];
\r
1001 rshift = bn_clz(m0);
\r
1005 m0 |= m[1] >> (BIGNUM_INT_BITS - rshift);
\r
1007 recip = reciprocal_word(m0);
\r
1010 /* Main computation */
\r
1011 while (i < (int)exp[0]) {
\r
1013 internal_mul(a + mlen, a + mlen, b, mlen, scratch);
\r
1014 internal_mod(b, mlen * 2, m, mlen, NULL, recip, rshift);
\r
1015 if ((exp[exp[0] - i] & ((BignumInt)1 << j)) != 0) {
\r
1016 internal_mul(b + mlen, n, a, mlen, scratch);
\r
1017 internal_mod(a, mlen * 2, m, mlen, NULL, recip, rshift);
\r
1027 j = BIGNUM_INT_BITS-1;
\r
1030 /* Copy result to buffer */
\r
1031 result = newbn(mod[0]);
\r
1032 for (i = 0; i < mlen; i++)
\r
1033 result[result[0] - i] = a[i + mlen];
\r
1034 while (result[0] > 1 && result[result[0]] == 0)
\r
1037 /* Free temporary arrays */
\r
1038 smemclr(a, 2 * mlen * sizeof(*a));
\r
1040 smemclr(scratch, scratchlen * sizeof(*scratch));
\r
1042 smemclr(b, 2 * mlen * sizeof(*b));
\r
1044 smemclr(m, mlen * sizeof(*m));
\r
1046 smemclr(n, mlen * sizeof(*n));
\r
1055 * Compute (base ^ exp) % mod. Uses the Montgomery multiplication
\r
1056 * technique where possible, falling back to modpow_simple otherwise.
\r
1058 Bignum modpow(Bignum base_in, Bignum exp, Bignum mod)
\r
1060 BignumInt *a, *b, *x, *n, *mninv, *scratch;
\r
1061 int len, scratchlen, i, j;
\r
1062 Bignum base, base2, r, rn, inv, result;
\r
1065 * The most significant word of mod needs to be non-zero. It
\r
1066 * should already be, but let's make sure.
\r
1068 assert(mod[mod[0]] != 0);
\r
1071 * mod had better be odd, or we can't do Montgomery multiplication
\r
1072 * using a power of two at all.
\r
1074 if (!(mod[1] & 1))
\r
1075 return modpow_simple(base_in, exp, mod);
\r
1078 * Make sure the base is smaller than the modulus, by reducing
\r
1079 * it modulo the modulus if not.
\r
1081 base = bigmod(base_in, mod);
\r
1084 * Compute the inverse of n mod r, for monty_reduce. (In fact we
\r
1085 * want the inverse of _minus_ n mod r, but we'll sort that out
\r
1089 r = bn_power_2(BIGNUM_INT_BITS * len);
\r
1090 inv = modinv(mod, r);
\r
1091 assert(inv); /* cannot fail, since mod is odd and r is a power of 2 */
\r
1094 * Multiply the base by r mod n, to get it into Montgomery
\r
1097 base2 = modmul(base, r, mod);
\r
1101 rn = bigmod(r, mod); /* r mod n, i.e. Montgomerified 1 */
\r
1103 freebn(r); /* won't need this any more */
\r
1106 * Set up internal arrays of the right lengths, in big-endian
\r
1107 * format, containing the base, the modulus, and the modulus's
\r
1110 n = snewn(len, BignumInt);
\r
1111 for (j = 0; j < len; j++)
\r
1112 n[len - 1 - j] = mod[j + 1];
\r
1114 mninv = snewn(len, BignumInt);
\r
1115 for (j = 0; j < len; j++)
\r
1116 mninv[len - 1 - j] = (j < (int)inv[0] ? inv[j + 1] : 0);
\r
1117 freebn(inv); /* we don't need this copy of it any more */
\r
1118 /* Now negate mninv mod r, so it's the inverse of -n rather than +n. */
\r
1119 x = snewn(len, BignumInt);
\r
1120 for (j = 0; j < len; j++)
\r
1122 internal_sub(x, mninv, mninv, len);
\r
1124 /* x = snewn(len, BignumInt); */ /* already done above */
\r
1125 for (j = 0; j < len; j++)
\r
1126 x[len - 1 - j] = (j < (int)base[0] ? base[j + 1] : 0);
\r
1127 freebn(base); /* we don't need this copy of it any more */
\r
1129 a = snewn(2*len, BignumInt);
\r
1130 b = snewn(2*len, BignumInt);
\r
1131 for (j = 0; j < len; j++)
\r
1132 a[2*len - 1 - j] = (j < (int)rn[0] ? rn[j + 1] : 0);
\r
1135 /* Scratch space for multiplies */
\r
1136 scratchlen = 3*len + mul_compute_scratch(len);
\r
1137 scratch = snewn(scratchlen, BignumInt);
\r
1139 /* Skip leading zero bits of exp. */
\r
1141 j = BIGNUM_INT_BITS-1;
\r
1142 while (i < (int)exp[0] && (exp[exp[0] - i] & ((BignumInt)1 << j)) == 0) {
\r
1146 j = BIGNUM_INT_BITS-1;
\r
1150 /* Main computation */
\r
1151 while (i < (int)exp[0]) {
\r
1153 internal_mul(a + len, a + len, b, len, scratch);
\r
1154 monty_reduce(b, n, mninv, scratch, len);
\r
1155 if ((exp[exp[0] - i] & ((BignumInt)1 << j)) != 0) {
\r
1156 internal_mul(b + len, x, a, len, scratch);
\r
1157 monty_reduce(a, n, mninv, scratch, len);
\r
1167 j = BIGNUM_INT_BITS-1;
\r
1171 * Final monty_reduce to get back from the adjusted Montgomery
\r
1174 monty_reduce(a, n, mninv, scratch, len);
\r
1176 /* Copy result to buffer */
\r
1177 result = newbn(mod[0]);
\r
1178 for (i = 0; i < len; i++)
\r
1179 result[result[0] - i] = a[i + len];
\r
1180 while (result[0] > 1 && result[result[0]] == 0)
\r
1183 /* Free temporary arrays */
\r
1184 smemclr(scratch, scratchlen * sizeof(*scratch));
\r
1186 smemclr(a, 2 * len * sizeof(*a));
\r
1188 smemclr(b, 2 * len * sizeof(*b));
\r
1190 smemclr(mninv, len * sizeof(*mninv));
\r
1192 smemclr(n, len * sizeof(*n));
\r
1194 smemclr(x, len * sizeof(*x));
\r
1201 * Compute (p * q) % mod.
\r
1202 * The most significant word of mod MUST be non-zero.
\r
1203 * We assume that the result array is the same size as the mod array.
\r
1205 Bignum modmul(Bignum p, Bignum q, Bignum mod)
\r
1207 BignumInt *a, *n, *m, *o, *scratch;
\r
1209 int rshift, scratchlen;
\r
1210 int pqlen, mlen, rlen, i, j;
\r
1214 * The most significant word of mod needs to be non-zero. It
\r
1215 * should already be, but let's make sure.
\r
1217 assert(mod[mod[0]] != 0);
\r
1219 /* Allocate m of size mlen, copy mod to m */
\r
1220 /* We use big endian internally */
\r
1222 m = snewn(mlen, BignumInt);
\r
1223 for (j = 0; j < mlen; j++)
\r
1224 m[j] = mod[mod[0] - j];
\r
1226 pqlen = (p[0] > q[0] ? p[0] : q[0]);
\r
1229 * Make sure that we're allowing enough space. The shifting below
\r
1230 * will underflow the vectors we allocate if pqlen is too small.
\r
1232 if (2*pqlen <= mlen)
\r
1233 pqlen = mlen/2 + 1;
\r
1235 /* Allocate n of size pqlen, copy p to n */
\r
1236 n = snewn(pqlen, BignumInt);
\r
1238 for (j = 0; j < i; j++)
\r
1240 for (j = 0; j < (int)p[0]; j++)
\r
1241 n[i + j] = p[p[0] - j];
\r
1243 /* Allocate o of size pqlen, copy q to o */
\r
1244 o = snewn(pqlen, BignumInt);
\r
1246 for (j = 0; j < i; j++)
\r
1248 for (j = 0; j < (int)q[0]; j++)
\r
1249 o[i + j] = q[q[0] - j];
\r
1251 /* Allocate a of size 2*pqlen for result */
\r
1252 a = snewn(2 * pqlen, BignumInt);
\r
1254 /* Scratch space for multiplies */
\r
1255 scratchlen = mul_compute_scratch(pqlen);
\r
1256 scratch = snewn(scratchlen, BignumInt);
\r
1258 /* Compute reciprocal of the top full word of the modulus */
\r
1260 BignumInt m0 = m[0];
\r
1261 rshift = bn_clz(m0);
\r
1265 m0 |= m[1] >> (BIGNUM_INT_BITS - rshift);
\r
1267 recip = reciprocal_word(m0);
\r
1270 /* Main computation */
\r
1271 internal_mul(n, o, a, pqlen, scratch);
\r
1272 internal_mod(a, pqlen * 2, m, mlen, NULL, recip, rshift);
\r
1274 /* Copy result to buffer */
\r
1275 rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
\r
1276 result = newbn(rlen);
\r
1277 for (i = 0; i < rlen; i++)
\r
1278 result[result[0] - i] = a[i + 2 * pqlen - rlen];
\r
1279 while (result[0] > 1 && result[result[0]] == 0)
\r
1282 /* Free temporary arrays */
\r
1283 smemclr(scratch, scratchlen * sizeof(*scratch));
\r
1285 smemclr(a, 2 * pqlen * sizeof(*a));
\r
1287 smemclr(m, mlen * sizeof(*m));
\r
1289 smemclr(n, pqlen * sizeof(*n));
\r
1291 smemclr(o, pqlen * sizeof(*o));
\r
1297 Bignum modsub(const Bignum a, const Bignum b, const Bignum n)
\r
1299 Bignum a1, b1, ret;
\r
1301 if (bignum_cmp(a, n) >= 0) a1 = bigmod(a, n);
\r
1303 if (bignum_cmp(b, n) >= 0) b1 = bigmod(b, n);
\r
1306 if (bignum_cmp(a1, b1) >= 0) /* a >= b */
\r
1308 ret = bigsub(a1, b1);
\r
1312 /* Handle going round the corner of the modulus without having
\r
1313 * negative support in Bignum */
\r
1314 Bignum tmp = bigsub(n, b1);
\r
1316 ret = bigadd(tmp, a1);
\r
1320 if (a != a1) freebn(a1);
\r
1321 if (b != b1) freebn(b1);
\r
1327 * Compute p % mod.
\r
1328 * The most significant word of mod MUST be non-zero.
\r
1329 * We assume that the result array is the same size as the mod array.
\r
1330 * We optionally write out a quotient if `quotient' is non-NULL.
\r
1331 * We can avoid writing out the result if `result' is NULL.
\r
1333 static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
\r
1338 int plen, mlen, i, j;
\r
1341 * The most significant word of mod needs to be non-zero. It
\r
1342 * should already be, but let's make sure.
\r
1344 assert(mod[mod[0]] != 0);
\r
1346 /* Allocate m of size mlen, copy mod to m */
\r
1347 /* We use big endian internally */
\r
1349 m = snewn(mlen, BignumInt);
\r
1350 for (j = 0; j < mlen; j++)
\r
1351 m[j] = mod[mod[0] - j];
\r
1354 /* Ensure plen > mlen */
\r
1358 /* Allocate n of size plen, copy p to n */
\r
1359 n = snewn(plen, BignumInt);
\r
1360 for (j = 0; j < plen; j++)
\r
1362 for (j = 1; j <= (int)p[0]; j++)
\r
1363 n[plen - j] = p[j];
\r
1365 /* Compute reciprocal of the top full word of the modulus */
\r
1367 BignumInt m0 = m[0];
\r
1368 rshift = bn_clz(m0);
\r
1372 m0 |= m[1] >> (BIGNUM_INT_BITS - rshift);
\r
1374 recip = reciprocal_word(m0);
\r
1377 /* Main computation */
\r
1378 internal_mod(n, plen, m, mlen, quotient, recip, rshift);
\r
1380 /* Copy result to buffer */
\r
1382 for (i = 1; i <= (int)result[0]; i++) {
\r
1384 result[i] = j >= 0 ? n[j] : 0;
\r
1388 /* Free temporary arrays */
\r
1389 smemclr(m, mlen * sizeof(*m));
\r
1391 smemclr(n, plen * sizeof(*n));
\r
1396 * Decrement a number.
\r
1398 void decbn(Bignum bn)
\r
1401 while (i < (int)bn[0] && bn[i] == 0)
\r
1402 bn[i++] = BIGNUM_INT_MASK;
\r
1406 Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
\r
1411 assert(nbytes >= 0 && nbytes < INT_MAX/8);
\r
1413 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
\r
1415 result = newbn(w);
\r
1416 for (i = 1; i <= w; i++)
\r
1418 for (i = nbytes; i--;) {
\r
1419 unsigned char byte = *data++;
\r
1420 result[1 + i / BIGNUM_INT_BYTES] |=
\r
1421 (BignumInt)byte << (8*i % BIGNUM_INT_BITS);
\r
1424 bn_restore_invariant(result);
\r
1428 Bignum bignum_from_bytes_le(const unsigned char *data, int nbytes)
\r
1433 assert(nbytes >= 0 && nbytes < INT_MAX/8);
\r
1435 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
\r
1437 result = newbn(w);
\r
1438 for (i = 1; i <= w; i++)
\r
1440 for (i = 0; i < nbytes; ++i) {
\r
1441 unsigned char byte = *data++;
\r
1442 result[1 + i / BIGNUM_INT_BYTES] |=
\r
1443 (BignumInt)byte << (8*i % BIGNUM_INT_BITS);
\r
1446 bn_restore_invariant(result);
\r
1450 Bignum bignum_from_decimal(const char *decimal)
\r
1452 Bignum result = copybn(Zero);
\r
1454 while (*decimal) {
\r
1457 if (!isdigit((unsigned char)*decimal)) {
\r
1462 tmp = bigmul(result, Ten);
\r
1463 tmp2 = bignum_from_long(*decimal - '0');
\r
1465 result = bigadd(tmp, tmp2);
\r
1475 Bignum bignum_random_in_range(const Bignum lower, const Bignum upper)
\r
1477 Bignum ret = NULL;
\r
1478 unsigned char *bytes;
\r
1479 int upper_len = bignum_bitcount(upper);
\r
1480 int upper_bytes = upper_len / 8;
\r
1481 int upper_bits = upper_len % 8;
\r
1482 if (upper_bits) ++upper_bytes;
\r
1484 bytes = snewn(upper_bytes, unsigned char);
\r
1488 if (ret) freebn(ret);
\r
1490 for (i = 0; i < upper_bytes; ++i)
\r
1492 bytes[i] = (unsigned char)random_byte();
\r
1494 /* Mask the top to reduce failure rate to 50/50 */
\r
1497 bytes[i - 1] &= 0xFF >> (8 - upper_bits);
\r
1500 ret = bignum_from_bytes(bytes, upper_bytes);
\r
1501 } while (bignum_cmp(ret, lower) < 0 || bignum_cmp(ret, upper) > 0);
\r
1502 smemclr(bytes, upper_bytes);
\r
1509 * Read an SSH-1-format bignum from a data buffer. Return the number
\r
1510 * of bytes consumed, or -1 if there wasn't enough data.
\r
1512 int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)
\r
1514 const unsigned char *p = data;
\r
1522 for (i = 0; i < 2; i++)
\r
1523 w = (w << 8) + *p++;
\r
1524 b = (w + 7) / 8; /* bits -> bytes */
\r
1529 if (!result) /* just return length */
\r
1532 *result = bignum_from_bytes(p, b);
\r
1534 return p + b - data;
\r
1538 * Return the bit count of a bignum, for SSH-1 encoding.
\r
1540 int bignum_bitcount(Bignum bn)
\r
1542 int bitcount = bn[0] * BIGNUM_INT_BITS - 1;
\r
1543 while (bitcount >= 0
\r
1544 && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;
\r
1545 return bitcount + 1;
\r
1549 * Return the byte length of a bignum when SSH-1 encoded.
\r
1551 int ssh1_bignum_length(Bignum bn)
\r
1553 return 2 + (bignum_bitcount(bn) + 7) / 8;
\r
1557 * Return the byte length of a bignum when SSH-2 encoded.
\r
1559 int ssh2_bignum_length(Bignum bn)
\r
1561 return 4 + (bignum_bitcount(bn) + 8) / 8;
\r
1565 * Return a byte from a bignum; 0 is least significant, etc.
\r
1567 int bignum_byte(Bignum bn, int i)
\r
1569 if (i < 0 || i >= (int)(BIGNUM_INT_BYTES * bn[0]))
\r
1570 return 0; /* beyond the end */
\r
1572 return (bn[i / BIGNUM_INT_BYTES + 1] >>
\r
1573 ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;
\r
1577 * Return a bit from a bignum; 0 is least significant, etc.
\r
1579 int bignum_bit(Bignum bn, int i)
\r
1581 if (i < 0 || i >= (int)(BIGNUM_INT_BITS * bn[0]))
\r
1582 return 0; /* beyond the end */
\r
1584 return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;
\r
1588 * Set a bit in a bignum; 0 is least significant, etc.
\r
1590 void bignum_set_bit(Bignum bn, int bitnum, int value)
\r
1592 if (bitnum < 0 || bitnum >= (int)(BIGNUM_INT_BITS * bn[0])) {
\r
1593 if (value) abort(); /* beyond the end */
\r
1595 int v = bitnum / BIGNUM_INT_BITS + 1;
\r
1596 BignumInt mask = (BignumInt)1 << (bitnum % BIGNUM_INT_BITS);
\r
1605 * Write a SSH-1-format bignum into a buffer. It is assumed the
\r
1606 * buffer is big enough. Returns the number of bytes used.
\r
1608 int ssh1_write_bignum(void *data, Bignum bn)
\r
1610 unsigned char *p = data;
\r
1611 int len = ssh1_bignum_length(bn);
\r
1613 int bitc = bignum_bitcount(bn);
\r
1615 *p++ = (bitc >> 8) & 0xFF;
\r
1616 *p++ = (bitc) & 0xFF;
\r
1617 for (i = len - 2; i--;)
\r
1618 *p++ = bignum_byte(bn, i);
\r
1623 * Compare two bignums. Returns like strcmp.
\r
1625 int bignum_cmp(Bignum a, Bignum b)
\r
1627 int amax = a[0], bmax = b[0];
\r
1630 /* Annoyingly we have two representations of zero */
\r
1631 if (amax == 1 && a[amax] == 0)
\r
1633 if (bmax == 1 && b[bmax] == 0)
\r
1636 assert(amax == 0 || a[amax] != 0);
\r
1637 assert(bmax == 0 || b[bmax] != 0);
\r
1639 i = (amax > bmax ? amax : bmax);
\r
1641 BignumInt aval = (i > amax ? 0 : a[i]);
\r
1642 BignumInt bval = (i > bmax ? 0 : b[i]);
\r
1653 * Right-shift one bignum to form another.
\r
1655 Bignum bignum_rshift(Bignum a, int shift)
\r
1658 int i, shiftw, shiftb, shiftbb, bits;
\r
1659 BignumInt ai, ai1;
\r
1661 assert(shift >= 0);
\r
1663 bits = bignum_bitcount(a) - shift;
\r
1664 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
\r
1667 shiftw = shift / BIGNUM_INT_BITS;
\r
1668 shiftb = shift % BIGNUM_INT_BITS;
\r
1669 shiftbb = BIGNUM_INT_BITS - shiftb;
\r
1671 ai1 = a[shiftw + 1];
\r
1672 for (i = 1; i <= (int)ret[0]; i++) {
\r
1674 ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);
\r
1675 ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;
\r
1683 * Left-shift one bignum to form another.
\r
1685 Bignum bignum_lshift(Bignum a, int shift)
\r
1688 int bits, shiftWords, shiftBits;
\r
1690 assert(shift >= 0);
\r
1692 bits = bignum_bitcount(a) + shift;
\r
1693 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
\r
1695 shiftWords = shift / BIGNUM_INT_BITS;
\r
1696 shiftBits = shift % BIGNUM_INT_BITS;
\r
1698 if (shiftBits == 0)
\r
1700 memcpy(&ret[1 + shiftWords], &a[1], sizeof(BignumInt) * a[0]);
\r
1705 BignumInt carry = 0;
\r
1707 /* Remember that Bignum[0] is length, so add 1 */
\r
1708 for (i = shiftWords + 1; i < ((int)a[0]) + shiftWords + 1; ++i)
\r
1710 BignumInt from = a[i - shiftWords];
\r
1711 ret[i] = (from << shiftBits) | carry;
\r
1712 carry = from >> (BIGNUM_INT_BITS - shiftBits);
\r
1714 if (carry) ret[i] = carry;
\r
1721 * Non-modular multiplication and addition.
\r
1723 Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
\r
1725 int alen = a[0], blen = b[0];
\r
1726 int mlen = (alen > blen ? alen : blen);
\r
1727 int rlen, i, maxspot;
\r
1729 BignumInt *workspace;
\r
1732 /* mlen space for a, mlen space for b, 2*mlen for result,
\r
1733 * plus scratch space for multiplication */
\r
1734 wslen = mlen * 4 + mul_compute_scratch(mlen);
\r
1735 workspace = snewn(wslen, BignumInt);
\r
1736 for (i = 0; i < mlen; i++) {
\r
1737 workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);
\r
1738 workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);
\r
1741 internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
\r
1742 workspace + 2 * mlen, mlen, workspace + 4 * mlen);
\r
1744 /* now just copy the result back */
\r
1745 rlen = alen + blen + 1;
\r
1746 if (addend && rlen <= (int)addend[0])
\r
1747 rlen = addend[0] + 1;
\r
1748 ret = newbn(rlen);
\r
1750 for (i = 1; i <= (int)ret[0]; i++) {
\r
1751 ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
\r
1757 /* now add in the addend, if any */
\r
1759 BignumCarry carry = 0;
\r
1760 for (i = 1; i <= rlen; i++) {
\r
1761 BignumInt retword = (i <= (int)ret[0] ? ret[i] : 0);
\r
1762 BignumInt addword = (i <= (int)addend[0] ? addend[i] : 0);
\r
1763 BignumADC(ret[i], carry, retword, addword, carry);
\r
1764 if (ret[i] != 0 && i > maxspot)
\r
1770 smemclr(workspace, wslen * sizeof(*workspace));
\r
1776 * Non-modular multiplication.
\r
1778 Bignum bigmul(Bignum a, Bignum b)
\r
1780 return bigmuladd(a, b, NULL);
\r
1784 * Simple addition.
\r
1786 Bignum bigadd(Bignum a, Bignum b)
\r
1788 int alen = a[0], blen = b[0];
\r
1789 int rlen = (alen > blen ? alen : blen) + 1;
\r
1792 BignumCarry carry;
\r
1794 ret = newbn(rlen);
\r
1798 for (i = 1; i <= rlen; i++) {
\r
1799 BignumInt aword = (i <= (int)a[0] ? a[i] : 0);
\r
1800 BignumInt bword = (i <= (int)b[0] ? b[i] : 0);
\r
1801 BignumADC(ret[i], carry, aword, bword, carry);
\r
1802 if (ret[i] != 0 && i > maxspot)
\r
1811 * Subtraction. Returns a-b, or NULL if the result would come out
\r
1812 * negative (recall that this entire bignum module only handles
\r
1813 * positive numbers).
\r
1815 Bignum bigsub(Bignum a, Bignum b)
\r
1817 int alen = a[0], blen = b[0];
\r
1818 int rlen = (alen > blen ? alen : blen);
\r
1821 BignumCarry carry;
\r
1823 ret = newbn(rlen);
\r
1827 for (i = 1; i <= rlen; i++) {
\r
1828 BignumInt aword = (i <= (int)a[0] ? a[i] : 0);
\r
1829 BignumInt bword = (i <= (int)b[0] ? b[i] : 0);
\r
1830 BignumADC(ret[i], carry, aword, ~bword, carry);
\r
1831 if (ret[i] != 0 && i > maxspot)
\r
1845 * Create a bignum which is the bitmask covering another one. That
\r
1846 * is, the smallest integer which is >= N and is also one less than
\r
1849 Bignum bignum_bitmask(Bignum n)
\r
1851 Bignum ret = copybn(n);
\r
1856 while (n[i] == 0 && i > 0)
\r
1859 return ret; /* input was zero */
\r
1865 ret[i] = BIGNUM_INT_MASK;
\r
1870 * Convert an unsigned long into a bignum.
\r
1872 Bignum bignum_from_long(unsigned long n)
\r
1874 const int maxwords =
\r
1875 (sizeof(unsigned long) + sizeof(BignumInt) - 1) / sizeof(BignumInt);
\r
1879 ret = newbn(maxwords);
\r
1881 for (i = 0; i < maxwords; i++) {
\r
1882 ret[i+1] = n >> (i * BIGNUM_INT_BITS);
\r
1883 if (ret[i+1] != 0)
\r
1891 * Add a long to a bignum.
\r
1893 Bignum bignum_add_long(Bignum number, unsigned long n)
\r
1895 const int maxwords =
\r
1896 (sizeof(unsigned long) + sizeof(BignumInt) - 1) / sizeof(BignumInt);
\r
1899 BignumCarry carry;
\r
1901 words = number[0];
\r
1902 if (words < maxwords)
\r
1905 ret = newbn(words);
\r
1909 for (i = 0; i < words; i++) {
\r
1910 BignumInt nword = (i < maxwords ? n >> (i * BIGNUM_INT_BITS) : 0);
\r
1911 BignumInt numword = (i < number[0] ? number[i+1] : 0);
\r
1912 BignumADC(ret[i+1], carry, numword, nword, carry);
\r
1913 if (ret[i+1] != 0)
\r
1920 * Compute the residue of a bignum, modulo a (max 16-bit) short.
\r
1922 unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
\r
1924 unsigned long mod = modulus, r = 0;
\r
1925 /* Precompute (BIGNUM_INT_MASK+1) % mod */
\r
1926 unsigned long base_r = (BIGNUM_INT_MASK - modulus + 1) % mod;
\r
1929 for (i = number[0]; i > 0; i--) {
\r
1931 * Conceptually, ((r << BIGNUM_INT_BITS) + number[i]) % mod
\r
1933 r = ((r * base_r) + (number[i] % mod)) % mod;
\r
1935 return (unsigned short) r;
\r
1939 void diagbn(char *prefix, Bignum md)
\r
1941 int i, nibbles, morenibbles;
\r
1942 static const char hex[] = "0123456789ABCDEF";
\r
1944 debug(("%s0x", prefix ? prefix : ""));
\r
1946 nibbles = (3 + bignum_bitcount(md)) / 4;
\r
1949 morenibbles = 4 * md[0] - nibbles;
\r
1950 for (i = 0; i < morenibbles; i++)
\r
1952 for (i = nibbles; i--;)
\r
1954 hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
\r
1962 * Simple division.
\r
1964 Bignum bigdiv(Bignum a, Bignum b)
\r
1966 Bignum q = newbn(a[0]);
\r
1967 bigdivmod(a, b, NULL, q);
\r
1968 while (q[0] > 1 && q[q[0]] == 0)
\r
1974 * Simple remainder.
\r
1976 Bignum bigmod(Bignum a, Bignum b)
\r
1978 Bignum r = newbn(b[0]);
\r
1979 bigdivmod(a, b, r, NULL);
\r
1980 while (r[0] > 1 && r[r[0]] == 0)
\r
1986 * Greatest common divisor.
\r
1988 Bignum biggcd(Bignum av, Bignum bv)
\r
1990 Bignum a = copybn(av);
\r
1991 Bignum b = copybn(bv);
\r
1993 while (bignum_cmp(b, Zero) != 0) {
\r
1994 Bignum t = newbn(b[0]);
\r
1995 bigdivmod(a, b, t, NULL);
\r
1996 while (t[0] > 1 && t[t[0]] == 0)
\r
2008 * Modular inverse, using Euclid's extended algorithm.
\r
2010 Bignum modinv(Bignum number, Bignum modulus)
\r
2012 Bignum a = copybn(modulus);
\r
2013 Bignum b = copybn(number);
\r
2014 Bignum xp = copybn(Zero);
\r
2015 Bignum x = copybn(One);
\r
2018 assert(number[number[0]] != 0);
\r
2019 assert(modulus[modulus[0]] != 0);
\r
2021 while (bignum_cmp(b, One) != 0) {
\r
2024 if (bignum_cmp(b, Zero) == 0) {
\r
2026 * Found a common factor between the inputs, so we cannot
\r
2027 * return a modular inverse at all.
\r
2038 bigdivmod(a, b, t, q);
\r
2039 while (t[0] > 1 && t[t[0]] == 0)
\r
2041 while (q[0] > 1 && q[q[0]] == 0)
\r
2048 x = bigmuladd(q, xp, t);
\r
2058 /* now we know that sign * x == 1, and that x < modulus */
\r
2060 /* set a new x to be modulus - x */
\r
2061 Bignum newx = newbn(modulus[0]);
\r
2062 BignumInt carry = 0;
\r
2066 for (i = 1; i <= (int)newx[0]; i++) {
\r
2067 BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);
\r
2068 BignumInt bword = (i <= (int)x[0] ? x[i] : 0);
\r
2069 newx[i] = aword - bword - carry;
\r
2071 carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
\r
2075 newx[0] = maxspot;
\r
2085 * Render a bignum into decimal. Return a malloced string holding
\r
2086 * the decimal representation.
\r
2088 char *bignum_decimal(Bignum x)
\r
2090 int ndigits, ndigit;
\r
2094 BignumInt *workspace;
\r
2097 * First, estimate the number of digits. Since log(10)/log(2)
\r
2098 * is just greater than 93/28 (the joys of continued fraction
\r
2099 * approximations...) we know that for every 93 bits, we need
\r
2100 * at most 28 digits. This will tell us how much to malloc.
\r
2102 * Formally: if x has i bits, that means x is strictly less
\r
2103 * than 2^i. Since 2 is less than 10^(28/93), this is less than
\r
2104 * 10^(28i/93). We need an integer power of ten, so we must
\r
2105 * round up (rounding down might make it less than x again).
\r
2106 * Therefore if we multiply the bit count by 28/93, rounding
\r
2107 * up, we will have enough digits.
\r
2109 * i=0 (i.e., x=0) is an irritating special case.
\r
2111 i = bignum_bitcount(x);
\r
2113 ndigits = 1; /* x = 0 */
\r
2115 ndigits = (28 * i + 92) / 93; /* multiply by 28/93 and round up */
\r
2116 ndigits++; /* allow for trailing \0 */
\r
2117 ret = snewn(ndigits, char);
\r
2120 * Now allocate some workspace to hold the binary form as we
\r
2121 * repeatedly divide it by ten. Initialise this to the
\r
2122 * big-endian form of the number.
\r
2124 workspace = snewn(x[0], BignumInt);
\r
2125 for (i = 0; i < (int)x[0]; i++)
\r
2126 workspace[i] = x[x[0] - i];
\r
2129 * Next, write the decimal number starting with the last digit.
\r
2130 * We use ordinary short division, dividing 10 into the
\r
2133 ndigit = ndigits - 1;
\r
2134 ret[ndigit] = '\0';
\r
2138 for (i = 0; i < (int)x[0]; i++) {
\r
2140 * Conceptually, we want to compute
\r
2142 * (carry << BIGNUM_INT_BITS) + workspace[i]
\r
2143 * -----------------------------------------
\r
2146 * but we don't have an integer type longer than BignumInt
\r
2147 * to work with. So we have to do it in pieces.
\r
2151 q = workspace[i] / 10;
\r
2152 r = workspace[i] % 10;
\r
2154 /* I want (BIGNUM_INT_MASK+1)/10 but can't say so directly! */
\r
2155 q += carry * ((BIGNUM_INT_MASK-9) / 10 + 1);
\r
2156 r += carry * ((BIGNUM_INT_MASK-9) % 10);
\r
2167 ret[--ndigit] = (char) (carry + '0');
\r
2168 } while (!iszero);
\r
2171 * There's a chance we've fallen short of the start of the
\r
2172 * string. Correct if so.
\r
2175 memmove(ret, ret + ndigit, ndigits - ndigit);
\r
2180 smemclr(workspace, x[0] * sizeof(*workspace));
\r