2 * Bignum routines for RSA and DH and stuff.
11 #define BIGNUM_INTERNAL
12 typedef unsigned short *Bignum;
16 unsigned short bnZero[1] = { 0 };
17 unsigned short bnOne[2] = { 1, 1 };
20 * The Bignum format is an array of `unsigned short'. The first
21 * element of the array counts the remaining elements. The
22 * remaining elements express the actual number, base 2^16, _least_
23 * significant digit first. (So it's trivial to extract the bit
24 * with value 2^n for any n.)
26 * All Bignums in this module are positive. Negative numbers must
27 * be dealt with outside it.
29 * INVARIANT: the most significant word of any Bignum must be
33 Bignum Zero = bnZero, One = bnOne;
35 static Bignum newbn(int length)
37 Bignum b = snewn(length + 1, unsigned short);
40 memset(b, 0, (length + 1) * sizeof(*b));
45 void bn_restore_invariant(Bignum b)
47 while (b[0] > 1 && b[b[0]] == 0)
51 Bignum copybn(Bignum orig)
53 Bignum b = snewn(orig[0] + 1, unsigned short);
56 memcpy(b, orig, (orig[0] + 1) * sizeof(*b));
63 * Burn the evidence, just in case.
65 memset(b, 0, sizeof(b[0]) * (b[0] + 1));
69 Bignum bn_power_2(int n)
71 Bignum ret = newbn(n / 16 + 1);
72 bignum_set_bit(ret, n, 1);
78 * Input is in the first len words of a and b.
79 * Result is returned in the first 2*len words of c.
81 static void internal_mul(unsigned short *a, unsigned short *b,
82 unsigned short *c, int len)
87 for (j = 0; j < 2 * len; j++)
90 for (i = len - 1; i >= 0; i--) {
93 for (j = len - 1; j >= 0; j--) {
94 t += ai * (unsigned long) b[j];
95 t += (unsigned long) c[i + j + 1];
96 c[i + j + 1] = (unsigned short) t;
99 c[i] = (unsigned short) t;
103 static void internal_add_shifted(unsigned short *number,
104 unsigned n, int shift)
106 int word = 1 + (shift / 16);
107 int bshift = shift % 16;
108 unsigned long addend;
110 addend = n << bshift;
113 addend += number[word];
114 number[word] = (unsigned short) addend & 0xFFFF;
122 * Input in first alen words of a and first mlen words of m.
123 * Output in first alen words of a
124 * (of which first alen-mlen words will be zero).
125 * The MSW of m MUST have its high bit set.
126 * Quotient is accumulated in the `quotient' array, which is a Bignum
127 * rather than the internal bigendian format. Quotient parts are shifted
128 * left by `qshift' before adding into quot.
130 static void internal_mod(unsigned short *a, int alen,
131 unsigned short *m, int mlen,
132 unsigned short *quot, int qshift)
134 unsigned short m0, m1;
144 for (i = 0; i <= alen - mlen; i++) {
146 unsigned int q, r, c, ai1;
160 /* Find q = h:a[i] / m0 */
161 t = ((unsigned long) h << 16) + a[i];
165 /* Refine our estimate of q by looking at
166 h:a[i]:a[i+1] / m0:m1 */
167 t = (long) m1 *(long) q;
168 if (t > ((unsigned long) r << 16) + ai1) {
171 r = (r + m0) & 0xffff; /* overflow? */
172 if (r >= (unsigned long) m0 &&
173 t > ((unsigned long) r << 16) + ai1) q--;
176 /* Subtract q * m from a[i...] */
178 for (k = mlen - 1; k >= 0; k--) {
179 t = (long) q *(long) m[k];
182 if ((unsigned short) t > a[i + k])
184 a[i + k] -= (unsigned short) t;
187 /* Add back m in case of borrow */
190 for (k = mlen - 1; k >= 0; k--) {
193 a[i + k] = (unsigned short) t;
199 internal_add_shifted(quot, q, qshift + 16 * (alen - mlen - i));
204 * Compute (base ^ exp) % mod.
205 * The base MUST be smaller than the modulus.
206 * The most significant word of mod MUST be non-zero.
207 * We assume that the result array is the same size as the mod array.
209 Bignum modpow(Bignum base, Bignum exp, Bignum mod)
211 unsigned short *a, *b, *n, *m;
216 /* Allocate m of size mlen, copy mod to m */
217 /* We use big endian internally */
219 m = snewn(mlen, unsigned short);
220 for (j = 0; j < mlen; j++)
221 m[j] = mod[mod[0] - j];
223 /* Shift m left to make msb bit set */
224 for (mshift = 0; mshift < 15; mshift++)
225 if ((m[0] << mshift) & 0x8000)
228 for (i = 0; i < mlen - 1; i++)
229 m[i] = (m[i] << mshift) | (m[i + 1] >> (16 - mshift));
230 m[mlen - 1] = m[mlen - 1] << mshift;
233 /* Allocate n of size mlen, copy base to n */
234 n = snewn(mlen, unsigned short);
236 for (j = 0; j < i; j++)
238 for (j = 0; j < base[0]; j++)
239 n[i + j] = base[base[0] - j];
241 /* Allocate a and b of size 2*mlen. Set a = 1 */
242 a = snewn(2 * mlen, unsigned short);
243 b = snewn(2 * mlen, unsigned short);
244 for (i = 0; i < 2 * mlen; i++)
248 /* Skip leading zero bits of exp. */
251 while (i < exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
259 /* Main computation */
262 internal_mul(a + mlen, a + mlen, b, mlen);
263 internal_mod(b, mlen * 2, m, mlen, NULL, 0);
264 if ((exp[exp[0] - i] & (1 << j)) != 0) {
265 internal_mul(b + mlen, n, a, mlen);
266 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
279 /* Fixup result in case the modulus was shifted */
281 for (i = mlen - 1; i < 2 * mlen - 1; i++)
282 a[i] = (a[i] << mshift) | (a[i + 1] >> (16 - mshift));
283 a[2 * mlen - 1] = a[2 * mlen - 1] << mshift;
284 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
285 for (i = 2 * mlen - 1; i >= mlen; i--)
286 a[i] = (a[i] >> mshift) | (a[i - 1] << (16 - mshift));
289 /* Copy result to buffer */
290 result = newbn(mod[0]);
291 for (i = 0; i < mlen; i++)
292 result[result[0] - i] = a[i + mlen];
293 while (result[0] > 1 && result[result[0]] == 0)
296 /* Free temporary arrays */
297 for (i = 0; i < 2 * mlen; i++)
300 for (i = 0; i < 2 * mlen; i++)
303 for (i = 0; i < mlen; i++)
306 for (i = 0; i < mlen; i++)
314 * Compute (p * q) % mod.
315 * The most significant word of mod MUST be non-zero.
316 * We assume that the result array is the same size as the mod array.
318 Bignum modmul(Bignum p, Bignum q, Bignum mod)
320 unsigned short *a, *n, *m, *o;
322 int pqlen, mlen, rlen, i, j;
325 /* Allocate m of size mlen, copy mod to m */
326 /* We use big endian internally */
328 m = snewn(mlen, unsigned short);
329 for (j = 0; j < mlen; j++)
330 m[j] = mod[mod[0] - j];
332 /* Shift m left to make msb bit set */
333 for (mshift = 0; mshift < 15; mshift++)
334 if ((m[0] << mshift) & 0x8000)
337 for (i = 0; i < mlen - 1; i++)
338 m[i] = (m[i] << mshift) | (m[i + 1] >> (16 - mshift));
339 m[mlen - 1] = m[mlen - 1] << mshift;
342 pqlen = (p[0] > q[0] ? p[0] : q[0]);
344 /* Allocate n of size pqlen, copy p to n */
345 n = snewn(pqlen, unsigned short);
347 for (j = 0; j < i; j++)
349 for (j = 0; j < p[0]; j++)
350 n[i + j] = p[p[0] - j];
352 /* Allocate o of size pqlen, copy q to o */
353 o = snewn(pqlen, unsigned short);
355 for (j = 0; j < i; j++)
357 for (j = 0; j < q[0]; j++)
358 o[i + j] = q[q[0] - j];
360 /* Allocate a of size 2*pqlen for result */
361 a = snewn(2 * pqlen, unsigned short);
363 /* Main computation */
364 internal_mul(n, o, a, pqlen);
365 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
367 /* Fixup result in case the modulus was shifted */
369 for (i = 2 * pqlen - mlen - 1; i < 2 * pqlen - 1; i++)
370 a[i] = (a[i] << mshift) | (a[i + 1] >> (16 - mshift));
371 a[2 * pqlen - 1] = a[2 * pqlen - 1] << mshift;
372 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
373 for (i = 2 * pqlen - 1; i >= 2 * pqlen - mlen; i--)
374 a[i] = (a[i] >> mshift) | (a[i - 1] << (16 - mshift));
377 /* Copy result to buffer */
378 rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
379 result = newbn(rlen);
380 for (i = 0; i < rlen; i++)
381 result[result[0] - i] = a[i + 2 * pqlen - rlen];
382 while (result[0] > 1 && result[result[0]] == 0)
385 /* Free temporary arrays */
386 for (i = 0; i < 2 * pqlen; i++)
389 for (i = 0; i < mlen; i++)
392 for (i = 0; i < pqlen; i++)
395 for (i = 0; i < pqlen; i++)
404 * The most significant word of mod MUST be non-zero.
405 * We assume that the result array is the same size as the mod array.
406 * We optionally write out a quotient if `quotient' is non-NULL.
407 * We can avoid writing out the result if `result' is NULL.
409 static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
411 unsigned short *n, *m;
413 int plen, mlen, i, j;
415 /* Allocate m of size mlen, copy mod to m */
416 /* We use big endian internally */
418 m = snewn(mlen, unsigned short);
419 for (j = 0; j < mlen; j++)
420 m[j] = mod[mod[0] - j];
422 /* Shift m left to make msb bit set */
423 for (mshift = 0; mshift < 15; mshift++)
424 if ((m[0] << mshift) & 0x8000)
427 for (i = 0; i < mlen - 1; i++)
428 m[i] = (m[i] << mshift) | (m[i + 1] >> (16 - mshift));
429 m[mlen - 1] = m[mlen - 1] << mshift;
433 /* Ensure plen > mlen */
437 /* Allocate n of size plen, copy p to n */
438 n = snewn(plen, unsigned short);
439 for (j = 0; j < plen; j++)
441 for (j = 1; j <= p[0]; j++)
444 /* Main computation */
445 internal_mod(n, plen, m, mlen, quotient, mshift);
447 /* Fixup result in case the modulus was shifted */
449 for (i = plen - mlen - 1; i < plen - 1; i++)
450 n[i] = (n[i] << mshift) | (n[i + 1] >> (16 - mshift));
451 n[plen - 1] = n[plen - 1] << mshift;
452 internal_mod(n, plen, m, mlen, quotient, 0);
453 for (i = plen - 1; i >= plen - mlen; i--)
454 n[i] = (n[i] >> mshift) | (n[i - 1] << (16 - mshift));
457 /* Copy result to buffer */
459 for (i = 1; i <= result[0]; i++) {
461 result[i] = j >= 0 ? n[j] : 0;
465 /* Free temporary arrays */
466 for (i = 0; i < mlen; i++)
469 for (i = 0; i < plen; i++)
475 * Decrement a number.
477 void decbn(Bignum bn)
480 while (i < bn[0] && bn[i] == 0)
485 Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
490 w = (nbytes + 1) / 2; /* bytes -> words */
493 for (i = 1; i <= w; i++)
495 for (i = nbytes; i--;) {
496 unsigned char byte = *data++;
498 result[1 + i / 2] |= byte << 8;
500 result[1 + i / 2] |= byte;
503 while (result[0] > 1 && result[result[0]] == 0)
509 * Read an ssh1-format bignum from a data buffer. Return the number
512 int ssh1_read_bignum(const unsigned char *data, Bignum * result)
514 const unsigned char *p = data;
519 for (i = 0; i < 2; i++)
521 b = (w + 7) / 8; /* bits -> bytes */
523 if (!result) /* just return length */
526 *result = bignum_from_bytes(p, b);
532 * Return the bit count of a bignum, for ssh1 encoding.
534 int bignum_bitcount(Bignum bn)
536 int bitcount = bn[0] * 16 - 1;
538 && (bn[bitcount / 16 + 1] >> (bitcount % 16)) == 0) bitcount--;
543 * Return the byte length of a bignum when ssh1 encoded.
545 int ssh1_bignum_length(Bignum bn)
547 return 2 + (bignum_bitcount(bn) + 7) / 8;
551 * Return the byte length of a bignum when ssh2 encoded.
553 int ssh2_bignum_length(Bignum bn)
555 return 4 + (bignum_bitcount(bn) + 8) / 8;
559 * Return a byte from a bignum; 0 is least significant, etc.
561 int bignum_byte(Bignum bn, int i)
564 return 0; /* beyond the end */
566 return (bn[i / 2 + 1] >> 8) & 0xFF;
568 return (bn[i / 2 + 1]) & 0xFF;
572 * Return a bit from a bignum; 0 is least significant, etc.
574 int bignum_bit(Bignum bn, int i)
577 return 0; /* beyond the end */
579 return (bn[i / 16 + 1] >> (i % 16)) & 1;
583 * Set a bit in a bignum; 0 is least significant, etc.
585 void bignum_set_bit(Bignum bn, int bitnum, int value)
587 if (bitnum >= 16 * bn[0])
588 abort(); /* beyond the end */
590 int v = bitnum / 16 + 1;
591 int mask = 1 << (bitnum % 16);
600 * Write a ssh1-format bignum into a buffer. It is assumed the
601 * buffer is big enough. Returns the number of bytes used.
603 int ssh1_write_bignum(void *data, Bignum bn)
605 unsigned char *p = data;
606 int len = ssh1_bignum_length(bn);
608 int bitc = bignum_bitcount(bn);
610 *p++ = (bitc >> 8) & 0xFF;
611 *p++ = (bitc) & 0xFF;
612 for (i = len - 2; i--;)
613 *p++ = bignum_byte(bn, i);
618 * Compare two bignums. Returns like strcmp.
620 int bignum_cmp(Bignum a, Bignum b)
622 int amax = a[0], bmax = b[0];
623 int i = (amax > bmax ? amax : bmax);
625 unsigned short aval = (i > amax ? 0 : a[i]);
626 unsigned short bval = (i > bmax ? 0 : b[i]);
637 * Right-shift one bignum to form another.
639 Bignum bignum_rshift(Bignum a, int shift)
642 int i, shiftw, shiftb, shiftbb, bits;
643 unsigned short ai, ai1;
645 bits = bignum_bitcount(a) - shift;
646 ret = newbn((bits + 15) / 16);
651 shiftbb = 16 - shiftb;
654 for (i = 1; i <= ret[0]; i++) {
656 ai1 = (i + shiftw + 1 <= a[0] ? a[i + shiftw + 1] : 0);
657 ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & 0xFFFF;
665 * Non-modular multiplication and addition.
667 Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
669 int alen = a[0], blen = b[0];
670 int mlen = (alen > blen ? alen : blen);
671 int rlen, i, maxspot;
672 unsigned short *workspace;
675 /* mlen space for a, mlen space for b, 2*mlen for result */
676 workspace = snewn(mlen * 4, unsigned short);
677 for (i = 0; i < mlen; i++) {
678 workspace[0 * mlen + i] = (mlen - i <= a[0] ? a[mlen - i] : 0);
679 workspace[1 * mlen + i] = (mlen - i <= b[0] ? b[mlen - i] : 0);
682 internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
683 workspace + 2 * mlen, mlen);
685 /* now just copy the result back */
686 rlen = alen + blen + 1;
687 if (addend && rlen <= addend[0])
688 rlen = addend[0] + 1;
691 for (i = 1; i <= ret[0]; i++) {
692 ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
698 /* now add in the addend, if any */
700 unsigned long carry = 0;
701 for (i = 1; i <= rlen; i++) {
702 carry += (i <= ret[0] ? ret[i] : 0);
703 carry += (i <= addend[0] ? addend[i] : 0);
704 ret[i] = (unsigned short) carry & 0xFFFF;
706 if (ret[i] != 0 && i > maxspot)
716 * Non-modular multiplication.
718 Bignum bigmul(Bignum a, Bignum b)
720 return bigmuladd(a, b, NULL);
724 * Create a bignum which is the bitmask covering another one. That
725 * is, the smallest integer which is >= N and is also one less than
728 Bignum bignum_bitmask(Bignum n)
730 Bignum ret = copybn(n);
735 while (n[i] == 0 && i > 0)
738 return ret; /* input was zero */
749 * Convert a (max 32-bit) long into a bignum.
751 Bignum bignum_from_long(unsigned long n)
756 ret[1] = (unsigned short)(n & 0xFFFF);
757 ret[2] = (unsigned short)((n >> 16) & 0xFFFF);
759 ret[0] = (ret[2] ? 2 : 1);
764 * Add a long to a bignum.
766 Bignum bignum_add_long(Bignum number, unsigned long addend)
768 Bignum ret = newbn(number[0] + 1);
770 unsigned long carry = 0;
772 for (i = 1; i <= ret[0]; i++) {
773 carry += addend & 0xFFFF;
774 carry += (i <= number[0] ? number[i] : 0);
776 ret[i] = (unsigned short) carry & 0xFFFF;
786 * Compute the residue of a bignum, modulo a (max 16-bit) short.
788 unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
790 unsigned long mod, r;
795 for (i = number[0]; i > 0; i--)
796 r = (r * 65536 + number[i]) % mod;
797 return (unsigned short) r;
801 void diagbn(char *prefix, Bignum md)
804 int i, nibbles, morenibbles;
805 static const char hex[] = "0123456789ABCDEF";
807 debug(("%s0x", prefix ? prefix : ""));
809 nibbles = (3 + bignum_bitcount(md)) / 4;
812 morenibbles = 4 * md[0] - nibbles;
813 for (i = 0; i < morenibbles; i++)
815 for (i = nibbles; i--;)
817 hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
828 Bignum bigdiv(Bignum a, Bignum b)
830 Bignum q = newbn(a[0]);
831 bigdivmod(a, b, NULL, q);
838 Bignum bigmod(Bignum a, Bignum b)
840 Bignum r = newbn(b[0]);
841 bigdivmod(a, b, r, NULL);
846 * Greatest common divisor.
848 Bignum biggcd(Bignum av, Bignum bv)
850 Bignum a = copybn(av);
851 Bignum b = copybn(bv);
853 while (bignum_cmp(b, Zero) != 0) {
854 Bignum t = newbn(b[0]);
855 bigdivmod(a, b, t, NULL);
856 while (t[0] > 1 && t[t[0]] == 0)
868 * Modular inverse, using Euclid's extended algorithm.
870 Bignum modinv(Bignum number, Bignum modulus)
872 Bignum a = copybn(modulus);
873 Bignum b = copybn(number);
874 Bignum xp = copybn(Zero);
875 Bignum x = copybn(One);
878 while (bignum_cmp(b, One) != 0) {
879 Bignum t = newbn(b[0]);
880 Bignum q = newbn(a[0]);
881 bigdivmod(a, b, t, q);
882 while (t[0] > 1 && t[t[0]] == 0)
889 x = bigmuladd(q, xp, t);
898 /* now we know that sign * x == 1, and that x < modulus */
900 /* set a new x to be modulus - x */
901 Bignum newx = newbn(modulus[0]);
902 unsigned short carry = 0;
906 for (i = 1; i <= newx[0]; i++) {
907 unsigned short aword = (i <= modulus[0] ? modulus[i] : 0);
908 unsigned short bword = (i <= x[0] ? x[i] : 0);
909 newx[i] = aword - bword - carry;
911 carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
925 * Render a bignum into decimal. Return a malloced string holding
926 * the decimal representation.
928 char *bignum_decimal(Bignum x)
934 unsigned short *workspace;
937 * First, estimate the number of digits. Since log(10)/log(2)
938 * is just greater than 93/28 (the joys of continued fraction
939 * approximations...) we know that for every 93 bits, we need
940 * at most 28 digits. This will tell us how much to malloc.
942 * Formally: if x has i bits, that means x is strictly less
943 * than 2^i. Since 2 is less than 10^(28/93), this is less than
944 * 10^(28i/93). We need an integer power of ten, so we must
945 * round up (rounding down might make it less than x again).
946 * Therefore if we multiply the bit count by 28/93, rounding
947 * up, we will have enough digits.
949 i = bignum_bitcount(x);
950 ndigits = (28 * i + 92) / 93; /* multiply by 28/93 and round up */
951 ndigits++; /* allow for trailing \0 */
952 ret = snewn(ndigits, char);
955 * Now allocate some workspace to hold the binary form as we
956 * repeatedly divide it by ten. Initialise this to the
957 * big-endian form of the number.
959 workspace = snewn(x[0], unsigned short);
960 for (i = 0; i < x[0]; i++)
961 workspace[i] = x[x[0] - i];
964 * Next, write the decimal number starting with the last digit.
965 * We use ordinary short division, dividing 10 into the
968 ndigit = ndigits - 1;
973 for (i = 0; i < x[0]; i++) {
974 carry = (carry << 16) + workspace[i];
975 workspace[i] = (unsigned short) (carry / 10);
980 ret[--ndigit] = (char) (carry + '0');
984 * There's a chance we've fallen short of the start of the
985 * string. Correct if so.
988 memmove(ret, ret + ndigit, ndigits - ndigit);