Move the malloc and free of scratch space out of the internal_mul
[u/mdw/putty] / sshbn.c
1 /*
2 * Bignum routines for RSA and DH and stuff.
3 */
4
5 #include <stdio.h>
6 #include <assert.h>
7 #include <stdlib.h>
8 #include <string.h>
9
10 #include "misc.h"
11
12 /*
13 * Usage notes:
14 * * Do not call the DIVMOD_WORD macro with expressions such as array
15 * subscripts, as some implementations object to this (see below).
16 * * Note that none of the division methods below will cope if the
17 * quotient won't fit into BIGNUM_INT_BITS. Callers should be careful
18 * to avoid this case.
19 * If this condition occurs, in the case of the x86 DIV instruction,
20 * an overflow exception will occur, which (according to a correspondent)
21 * will manifest on Windows as something like
22 * 0xC0000095: Integer overflow
23 * The C variant won't give the right answer, either.
24 */
25
26 #if defined __GNUC__ && defined __i386__
27 typedef unsigned long BignumInt;
28 typedef unsigned long long BignumDblInt;
29 #define BIGNUM_INT_MASK 0xFFFFFFFFUL
30 #define BIGNUM_TOP_BIT 0x80000000UL
31 #define BIGNUM_INT_BITS 32
32 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
33 #define DIVMOD_WORD(q, r, hi, lo, w) \
34 __asm__("div %2" : \
35 "=d" (r), "=a" (q) : \
36 "r" (w), "d" (hi), "a" (lo))
37 #elif defined _MSC_VER && defined _M_IX86
38 typedef unsigned __int32 BignumInt;
39 typedef unsigned __int64 BignumDblInt;
40 #define BIGNUM_INT_MASK 0xFFFFFFFFUL
41 #define BIGNUM_TOP_BIT 0x80000000UL
42 #define BIGNUM_INT_BITS 32
43 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
44 /* Note: MASM interprets array subscripts in the macro arguments as
45 * assembler syntax, which gives the wrong answer. Don't supply them.
46 * <http://msdn2.microsoft.com/en-us/library/bf1dw62z.aspx> */
47 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
48 __asm mov edx, hi \
49 __asm mov eax, lo \
50 __asm div w \
51 __asm mov r, edx \
52 __asm mov q, eax \
53 } while(0)
54 #elif defined _LP64
55 /* 64-bit architectures can do 32x32->64 chunks at a time */
56 typedef unsigned int BignumInt;
57 typedef unsigned long BignumDblInt;
58 #define BIGNUM_INT_MASK 0xFFFFFFFFU
59 #define BIGNUM_TOP_BIT 0x80000000U
60 #define BIGNUM_INT_BITS 32
61 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
62 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
63 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
64 q = n / w; \
65 r = n % w; \
66 } while (0)
67 #elif defined _LLP64
68 /* 64-bit architectures in which unsigned long is 32 bits, not 64 */
69 typedef unsigned long BignumInt;
70 typedef unsigned long long BignumDblInt;
71 #define BIGNUM_INT_MASK 0xFFFFFFFFUL
72 #define BIGNUM_TOP_BIT 0x80000000UL
73 #define BIGNUM_INT_BITS 32
74 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
75 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
76 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
77 q = n / w; \
78 r = n % w; \
79 } while (0)
80 #else
81 /* Fallback for all other cases */
82 typedef unsigned short BignumInt;
83 typedef unsigned long BignumDblInt;
84 #define BIGNUM_INT_MASK 0xFFFFU
85 #define BIGNUM_TOP_BIT 0x8000U
86 #define BIGNUM_INT_BITS 16
87 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
88 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
89 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
90 q = n / w; \
91 r = n % w; \
92 } while (0)
93 #endif
94
95 #define BIGNUM_INT_BYTES (BIGNUM_INT_BITS / 8)
96
97 #define BIGNUM_INTERNAL
98 typedef BignumInt *Bignum;
99
100 #include "ssh.h"
101
102 BignumInt bnZero[1] = { 0 };
103 BignumInt bnOne[2] = { 1, 1 };
104
105 /*
106 * The Bignum format is an array of `BignumInt'. The first
107 * element of the array counts the remaining elements. The
108 * remaining elements express the actual number, base 2^BIGNUM_INT_BITS, _least_
109 * significant digit first. (So it's trivial to extract the bit
110 * with value 2^n for any n.)
111 *
112 * All Bignums in this module are positive. Negative numbers must
113 * be dealt with outside it.
114 *
115 * INVARIANT: the most significant word of any Bignum must be
116 * nonzero.
117 */
118
119 Bignum Zero = bnZero, One = bnOne;
120
121 static Bignum newbn(int length)
122 {
123 Bignum b = snewn(length + 1, BignumInt);
124 if (!b)
125 abort(); /* FIXME */
126 memset(b, 0, (length + 1) * sizeof(*b));
127 b[0] = length;
128 return b;
129 }
130
131 void bn_restore_invariant(Bignum b)
132 {
133 while (b[0] > 1 && b[b[0]] == 0)
134 b[0]--;
135 }
136
137 Bignum copybn(Bignum orig)
138 {
139 Bignum b = snewn(orig[0] + 1, BignumInt);
140 if (!b)
141 abort(); /* FIXME */
142 memcpy(b, orig, (orig[0] + 1) * sizeof(*b));
143 return b;
144 }
145
146 void freebn(Bignum b)
147 {
148 /*
149 * Burn the evidence, just in case.
150 */
151 memset(b, 0, sizeof(b[0]) * (b[0] + 1));
152 sfree(b);
153 }
154
155 Bignum bn_power_2(int n)
156 {
157 Bignum ret = newbn(n / BIGNUM_INT_BITS + 1);
158 bignum_set_bit(ret, n, 1);
159 return ret;
160 }
161
162 /*
163 * Internal addition. Sets c = a - b, where 'a', 'b' and 'c' are all
164 * big-endian arrays of 'len' BignumInts. Returns a BignumInt carried
165 * off the top.
166 */
167 static BignumInt internal_add(const BignumInt *a, const BignumInt *b,
168 BignumInt *c, int len)
169 {
170 int i;
171 BignumDblInt carry = 0;
172
173 for (i = len-1; i >= 0; i--) {
174 carry += (BignumDblInt)a[i] + b[i];
175 c[i] = (BignumInt)carry;
176 carry >>= BIGNUM_INT_BITS;
177 }
178
179 return (BignumInt)carry;
180 }
181
182 /*
183 * Internal subtraction. Sets c = a - b, where 'a', 'b' and 'c' are
184 * all big-endian arrays of 'len' BignumInts. Any borrow from the top
185 * is ignored.
186 */
187 static void internal_sub(const BignumInt *a, const BignumInt *b,
188 BignumInt *c, int len)
189 {
190 int i;
191 BignumDblInt carry = 1;
192
193 for (i = len-1; i >= 0; i--) {
194 carry += (BignumDblInt)a[i] + (b[i] ^ BIGNUM_INT_MASK);
195 c[i] = (BignumInt)carry;
196 carry >>= BIGNUM_INT_BITS;
197 }
198 }
199
200 /*
201 * Compute c = a * b.
202 * Input is in the first len words of a and b.
203 * Result is returned in the first 2*len words of c.
204 *
205 * 'scratch' must point to an array of BignumInt of size at least
206 * mul_compute_scratch(len). (This covers the needs of internal_mul
207 * and all its recursive calls to itself.)
208 */
209 #define KARATSUBA_THRESHOLD 50
210 static int mul_compute_scratch(int len)
211 {
212 int ret = 0;
213 while (len > KARATSUBA_THRESHOLD) {
214 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
215 int midlen = botlen + 1;
216 ret += 4*midlen;
217 len = midlen;
218 }
219 return ret;
220 }
221 static void internal_mul(const BignumInt *a, const BignumInt *b,
222 BignumInt *c, int len, BignumInt *scratch)
223 {
224 int i, j;
225 BignumDblInt t;
226
227 if (len > KARATSUBA_THRESHOLD) {
228
229 /*
230 * Karatsuba divide-and-conquer algorithm. Cut each input in
231 * half, so that it's expressed as two big 'digits' in a giant
232 * base D:
233 *
234 * a = a_1 D + a_0
235 * b = b_1 D + b_0
236 *
237 * Then the product is of course
238 *
239 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
240 *
241 * and we compute the three coefficients by recursively
242 * calling ourself to do half-length multiplications.
243 *
244 * The clever bit that makes this worth doing is that we only
245 * need _one_ half-length multiplication for the central
246 * coefficient rather than the two that it obviouly looks
247 * like, because we can use a single multiplication to compute
248 *
249 * (a_1 + a_0) (b_1 + b_0) = a_1 b_1 + a_1 b_0 + a_0 b_1 + a_0 b_0
250 *
251 * and then we subtract the other two coefficients (a_1 b_1
252 * and a_0 b_0) which we were computing anyway.
253 *
254 * Hence we get to multiply two numbers of length N in about
255 * three times as much work as it takes to multiply numbers of
256 * length N/2, which is obviously better than the four times
257 * as much work it would take if we just did a long
258 * conventional multiply.
259 */
260
261 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
262 int midlen = botlen + 1;
263 BignumDblInt carry;
264 #ifdef KARA_DEBUG
265 int i;
266 #endif
267
268 /*
269 * The coefficients a_1 b_1 and a_0 b_0 just avoid overlapping
270 * in the output array, so we can compute them immediately in
271 * place.
272 */
273
274 #ifdef KARA_DEBUG
275 printf("a1,a0 = 0x");
276 for (i = 0; i < len; i++) {
277 if (i == toplen) printf(", 0x");
278 printf("%0*x", BIGNUM_INT_BITS/4, a[i]);
279 }
280 printf("\n");
281 printf("b1,b0 = 0x");
282 for (i = 0; i < len; i++) {
283 if (i == toplen) printf(", 0x");
284 printf("%0*x", BIGNUM_INT_BITS/4, b[i]);
285 }
286 printf("\n");
287 #endif
288
289 /* a_1 b_1 */
290 internal_mul(a, b, c, toplen, scratch);
291 #ifdef KARA_DEBUG
292 printf("a1b1 = 0x");
293 for (i = 0; i < 2*toplen; i++) {
294 printf("%0*x", BIGNUM_INT_BITS/4, c[i]);
295 }
296 printf("\n");
297 #endif
298
299 /* a_0 b_0 */
300 internal_mul(a + toplen, b + toplen, c + 2*toplen, botlen, scratch);
301 #ifdef KARA_DEBUG
302 printf("a0b0 = 0x");
303 for (i = 0; i < 2*botlen; i++) {
304 printf("%0*x", BIGNUM_INT_BITS/4, c[2*toplen+i]);
305 }
306 printf("\n");
307 #endif
308
309 /* Zero padding. midlen exceeds toplen by at most 2, so just
310 * zero the first two words of each input and the rest will be
311 * copied over. */
312 scratch[0] = scratch[1] = scratch[midlen] = scratch[midlen+1] = 0;
313
314 for (j = 0; j < toplen; j++) {
315 scratch[midlen - toplen + j] = a[j]; /* a_1 */
316 scratch[2*midlen - toplen + j] = b[j]; /* b_1 */
317 }
318
319 /* compute a_1 + a_0 */
320 scratch[0] = internal_add(scratch+1, a+toplen, scratch+1, botlen);
321 #ifdef KARA_DEBUG
322 printf("a1plusa0 = 0x");
323 for (i = 0; i < midlen; i++) {
324 printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);
325 }
326 printf("\n");
327 #endif
328 /* compute b_1 + b_0 */
329 scratch[midlen] = internal_add(scratch+midlen+1, b+toplen,
330 scratch+midlen+1, botlen);
331 #ifdef KARA_DEBUG
332 printf("b1plusb0 = 0x");
333 for (i = 0; i < midlen; i++) {
334 printf("%0*x", BIGNUM_INT_BITS/4, scratch[midlen+i]);
335 }
336 printf("\n");
337 #endif
338
339 /*
340 * Now we can do the third multiplication.
341 */
342 internal_mul(scratch, scratch + midlen, scratch + 2*midlen, midlen,
343 scratch + 4*midlen);
344 #ifdef KARA_DEBUG
345 printf("a1plusa0timesb1plusb0 = 0x");
346 for (i = 0; i < 2*midlen; i++) {
347 printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);
348 }
349 printf("\n");
350 #endif
351
352 /*
353 * Now we can reuse the first half of 'scratch' to compute the
354 * sum of the outer two coefficients, to subtract from that
355 * product to obtain the middle one.
356 */
357 scratch[0] = scratch[1] = scratch[2] = scratch[3] = 0;
358 for (j = 0; j < 2*toplen; j++)
359 scratch[2*midlen - 2*toplen + j] = c[j];
360 scratch[1] = internal_add(scratch+2, c + 2*toplen,
361 scratch+2, 2*botlen);
362 #ifdef KARA_DEBUG
363 printf("a1b1plusa0b0 = 0x");
364 for (i = 0; i < 2*midlen; i++) {
365 printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);
366 }
367 printf("\n");
368 #endif
369
370 internal_sub(scratch + 2*midlen, scratch,
371 scratch + 2*midlen, 2*midlen);
372 #ifdef KARA_DEBUG
373 printf("a1b0plusa0b1 = 0x");
374 for (i = 0; i < 2*midlen; i++) {
375 printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);
376 }
377 printf("\n");
378 #endif
379
380 /*
381 * And now all we need to do is to add that middle coefficient
382 * back into the output. We may have to propagate a carry
383 * further up the output, but we can be sure it won't
384 * propagate right the way off the top.
385 */
386 carry = internal_add(c + 2*len - botlen - 2*midlen,
387 scratch + 2*midlen,
388 c + 2*len - botlen - 2*midlen, 2*midlen);
389 j = 2*len - botlen - 2*midlen - 1;
390 while (carry) {
391 assert(j >= 0);
392 carry += c[j];
393 c[j] = (BignumInt)carry;
394 carry >>= BIGNUM_INT_BITS;
395 j--;
396 }
397 #ifdef KARA_DEBUG
398 printf("ab = 0x");
399 for (i = 0; i < 2*len; i++) {
400 printf("%0*x", BIGNUM_INT_BITS/4, c[i]);
401 }
402 printf("\n");
403 #endif
404
405 } else {
406
407 /*
408 * Multiply in the ordinary O(N^2) way.
409 */
410
411 for (j = 0; j < 2 * len; j++)
412 c[j] = 0;
413
414 for (i = len - 1; i >= 0; i--) {
415 t = 0;
416 for (j = len - 1; j >= 0; j--) {
417 t += MUL_WORD(a[i], (BignumDblInt) b[j]);
418 t += (BignumDblInt) c[i + j + 1];
419 c[i + j + 1] = (BignumInt) t;
420 t = t >> BIGNUM_INT_BITS;
421 }
422 c[i] = (BignumInt) t;
423 }
424 }
425 }
426
427 /*
428 * Variant form of internal_mul used for the initial step of
429 * Montgomery reduction. Only bothers outputting 'len' words
430 * (everything above that is thrown away).
431 */
432 static void internal_mul_low(const BignumInt *a, const BignumInt *b,
433 BignumInt *c, int len, BignumInt *scratch)
434 {
435 int i, j;
436 BignumDblInt t;
437
438 if (len > KARATSUBA_THRESHOLD) {
439
440 /*
441 * Karatsuba-aware version of internal_mul_low. As before, we
442 * express each input value as a shifted combination of two
443 * halves:
444 *
445 * a = a_1 D + a_0
446 * b = b_1 D + b_0
447 *
448 * Then the full product is, as before,
449 *
450 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
451 *
452 * Provided we choose D on the large side (so that a_0 and b_0
453 * are _at least_ as long as a_1 and b_1), we don't need the
454 * topmost term at all, and we only need half of the middle
455 * term. So there's no point in doing the proper Karatsuba
456 * optimisation which computes the middle term using the top
457 * one, because we'd take as long computing the top one as
458 * just computing the middle one directly.
459 *
460 * So instead, we do a much more obvious thing: we call the
461 * fully optimised internal_mul to compute a_0 b_0, and we
462 * recursively call ourself to compute the _bottom halves_ of
463 * a_1 b_0 and a_0 b_1, each of which we add into the result
464 * in the obvious way.
465 *
466 * In other words, there's no actual Karatsuba _optimisation_
467 * in this function; the only benefit in doing it this way is
468 * that we call internal_mul proper for a large part of the
469 * work, and _that_ can optimise its operation.
470 */
471
472 int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */
473
474 /*
475 * Scratch space for the various bits and pieces we're going
476 * to be adding together: we need botlen*2 words for a_0 b_0
477 * (though we may end up throwing away its topmost word), and
478 * toplen words for each of a_1 b_0 and a_0 b_1. That adds up
479 * to exactly 2*len.
480 */
481
482 /* a_0 b_0 */
483 internal_mul(a + toplen, b + toplen, scratch + 2*toplen, botlen,
484 scratch + 2*len);
485
486 /* a_1 b_0 */
487 internal_mul_low(a, b + len - toplen, scratch + toplen, toplen,
488 scratch + 2*len);
489
490 /* a_0 b_1 */
491 internal_mul_low(a + len - toplen, b, scratch, toplen,
492 scratch + 2*len);
493
494 /* Copy the bottom half of the big coefficient into place */
495 for (j = 0; j < botlen; j++)
496 c[toplen + j] = scratch[2*toplen + botlen + j];
497
498 /* Add the two small coefficients, throwing away the returned carry */
499 internal_add(scratch, scratch + toplen, scratch, toplen);
500
501 /* And add that to the large coefficient, leaving the result in c. */
502 internal_add(scratch, scratch + 2*toplen + botlen - toplen,
503 c, toplen);
504
505 } else {
506
507 for (j = 0; j < len; j++)
508 c[j] = 0;
509
510 for (i = len - 1; i >= 0; i--) {
511 t = 0;
512 for (j = len - 1; j >= len - i - 1; j--) {
513 t += MUL_WORD(a[i], (BignumDblInt) b[j]);
514 t += (BignumDblInt) c[i + j + 1 - len];
515 c[i + j + 1 - len] = (BignumInt) t;
516 t = t >> BIGNUM_INT_BITS;
517 }
518 }
519
520 }
521 }
522
523 /*
524 * Montgomery reduction. Expects x to be a big-endian array of 2*len
525 * BignumInts whose value satisfies 0 <= x < rn (where r = 2^(len *
526 * BIGNUM_INT_BITS) is the Montgomery base). Returns in the same array
527 * a value x' which is congruent to xr^{-1} mod n, and satisfies 0 <=
528 * x' < n.
529 *
530 * 'n' and 'mninv' should be big-endian arrays of 'len' BignumInts
531 * each, containing respectively n and the multiplicative inverse of
532 * -n mod r.
533 *
534 * 'tmp' is an array of BignumInt used as scratch space, of length at
535 * least 3*len + mul_compute_scratch(len).
536 */
537 static void monty_reduce(BignumInt *x, const BignumInt *n,
538 const BignumInt *mninv, BignumInt *tmp, int len)
539 {
540 int i;
541 BignumInt carry;
542
543 /*
544 * Multiply x by (-n)^{-1} mod r. This gives us a value m such
545 * that mn is congruent to -x mod r. Hence, mn+x is an exact
546 * multiple of r, and is also (obviously) congruent to x mod n.
547 */
548 internal_mul_low(x + len, mninv, tmp, len, tmp + 3*len);
549
550 /*
551 * Compute t = (mn+x)/r in ordinary, non-modular, integer
552 * arithmetic. By construction this is exact, and is congruent mod
553 * n to x * r^{-1}, i.e. the answer we want.
554 *
555 * The following multiply leaves that answer in the _most_
556 * significant half of the 'x' array, so then we must shift it
557 * down.
558 */
559 internal_mul(tmp, n, tmp+len, len, tmp + 3*len);
560 carry = internal_add(x, tmp+len, x, 2*len);
561 for (i = 0; i < len; i++)
562 x[len + i] = x[i], x[i] = 0;
563
564 /*
565 * Reduce t mod n. This doesn't require a full-on division by n,
566 * but merely a test and single optional subtraction, since we can
567 * show that 0 <= t < 2n.
568 *
569 * Proof:
570 * + we computed m mod r, so 0 <= m < r.
571 * + so 0 <= mn < rn, obviously
572 * + hence we only need 0 <= x < rn to guarantee that 0 <= mn+x < 2rn
573 * + yielding 0 <= (mn+x)/r < 2n as required.
574 */
575 if (!carry) {
576 for (i = 0; i < len; i++)
577 if (x[len + i] != n[i])
578 break;
579 }
580 if (carry || i >= len || x[len + i] > n[i])
581 internal_sub(x+len, n, x+len, len);
582 }
583
584 static void internal_add_shifted(BignumInt *number,
585 unsigned n, int shift)
586 {
587 int word = 1 + (shift / BIGNUM_INT_BITS);
588 int bshift = shift % BIGNUM_INT_BITS;
589 BignumDblInt addend;
590
591 addend = (BignumDblInt)n << bshift;
592
593 while (addend) {
594 addend += number[word];
595 number[word] = (BignumInt) addend & BIGNUM_INT_MASK;
596 addend >>= BIGNUM_INT_BITS;
597 word++;
598 }
599 }
600
601 /*
602 * Compute a = a % m.
603 * Input in first alen words of a and first mlen words of m.
604 * Output in first alen words of a
605 * (of which first alen-mlen words will be zero).
606 * The MSW of m MUST have its high bit set.
607 * Quotient is accumulated in the `quotient' array, which is a Bignum
608 * rather than the internal bigendian format. Quotient parts are shifted
609 * left by `qshift' before adding into quot.
610 */
611 static void internal_mod(BignumInt *a, int alen,
612 BignumInt *m, int mlen,
613 BignumInt *quot, int qshift)
614 {
615 BignumInt m0, m1;
616 unsigned int h;
617 int i, k;
618
619 m0 = m[0];
620 if (mlen > 1)
621 m1 = m[1];
622 else
623 m1 = 0;
624
625 for (i = 0; i <= alen - mlen; i++) {
626 BignumDblInt t;
627 unsigned int q, r, c, ai1;
628
629 if (i == 0) {
630 h = 0;
631 } else {
632 h = a[i - 1];
633 a[i - 1] = 0;
634 }
635
636 if (i == alen - 1)
637 ai1 = 0;
638 else
639 ai1 = a[i + 1];
640
641 /* Find q = h:a[i] / m0 */
642 if (h >= m0) {
643 /*
644 * Special case.
645 *
646 * To illustrate it, suppose a BignumInt is 8 bits, and
647 * we are dividing (say) A1:23:45:67 by A1:B2:C3. Then
648 * our initial division will be 0xA123 / 0xA1, which
649 * will give a quotient of 0x100 and a divide overflow.
650 * However, the invariants in this division algorithm
651 * are not violated, since the full number A1:23:... is
652 * _less_ than the quotient prefix A1:B2:... and so the
653 * following correction loop would have sorted it out.
654 *
655 * In this situation we set q to be the largest
656 * quotient we _can_ stomach (0xFF, of course).
657 */
658 q = BIGNUM_INT_MASK;
659 } else {
660 /* Macro doesn't want an array subscript expression passed
661 * into it (see definition), so use a temporary. */
662 BignumInt tmplo = a[i];
663 DIVMOD_WORD(q, r, h, tmplo, m0);
664
665 /* Refine our estimate of q by looking at
666 h:a[i]:a[i+1] / m0:m1 */
667 t = MUL_WORD(m1, q);
668 if (t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) {
669 q--;
670 t -= m1;
671 r = (r + m0) & BIGNUM_INT_MASK; /* overflow? */
672 if (r >= (BignumDblInt) m0 &&
673 t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) q--;
674 }
675 }
676
677 /* Subtract q * m from a[i...] */
678 c = 0;
679 for (k = mlen - 1; k >= 0; k--) {
680 t = MUL_WORD(q, m[k]);
681 t += c;
682 c = (unsigned)(t >> BIGNUM_INT_BITS);
683 if ((BignumInt) t > a[i + k])
684 c++;
685 a[i + k] -= (BignumInt) t;
686 }
687
688 /* Add back m in case of borrow */
689 if (c != h) {
690 t = 0;
691 for (k = mlen - 1; k >= 0; k--) {
692 t += m[k];
693 t += a[i + k];
694 a[i + k] = (BignumInt) t;
695 t = t >> BIGNUM_INT_BITS;
696 }
697 q--;
698 }
699 if (quot)
700 internal_add_shifted(quot, q, qshift + BIGNUM_INT_BITS * (alen - mlen - i));
701 }
702 }
703
704 /*
705 * Compute (base ^ exp) % mod, the pedestrian way.
706 */
707 Bignum modpow_simple(Bignum base_in, Bignum exp, Bignum mod)
708 {
709 BignumInt *a, *b, *n, *m, *scratch;
710 int mshift;
711 int mlen, scratchlen, i, j;
712 Bignum base, result;
713
714 /*
715 * The most significant word of mod needs to be non-zero. It
716 * should already be, but let's make sure.
717 */
718 assert(mod[mod[0]] != 0);
719
720 /*
721 * Make sure the base is smaller than the modulus, by reducing
722 * it modulo the modulus if not.
723 */
724 base = bigmod(base_in, mod);
725
726 /* Allocate m of size mlen, copy mod to m */
727 /* We use big endian internally */
728 mlen = mod[0];
729 m = snewn(mlen, BignumInt);
730 for (j = 0; j < mlen; j++)
731 m[j] = mod[mod[0] - j];
732
733 /* Shift m left to make msb bit set */
734 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
735 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
736 break;
737 if (mshift) {
738 for (i = 0; i < mlen - 1; i++)
739 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
740 m[mlen - 1] = m[mlen - 1] << mshift;
741 }
742
743 /* Allocate n of size mlen, copy base to n */
744 n = snewn(mlen, BignumInt);
745 i = mlen - base[0];
746 for (j = 0; j < i; j++)
747 n[j] = 0;
748 for (j = 0; j < (int)base[0]; j++)
749 n[i + j] = base[base[0] - j];
750
751 /* Allocate a and b of size 2*mlen. Set a = 1 */
752 a = snewn(2 * mlen, BignumInt);
753 b = snewn(2 * mlen, BignumInt);
754 for (i = 0; i < 2 * mlen; i++)
755 a[i] = 0;
756 a[2 * mlen - 1] = 1;
757
758 /* Scratch space for multiplies */
759 scratchlen = mul_compute_scratch(mlen);
760 scratch = snewn(scratchlen, BignumInt);
761
762 /* Skip leading zero bits of exp. */
763 i = 0;
764 j = BIGNUM_INT_BITS-1;
765 while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
766 j--;
767 if (j < 0) {
768 i++;
769 j = BIGNUM_INT_BITS-1;
770 }
771 }
772
773 /* Main computation */
774 while (i < (int)exp[0]) {
775 while (j >= 0) {
776 internal_mul(a + mlen, a + mlen, b, mlen, scratch);
777 internal_mod(b, mlen * 2, m, mlen, NULL, 0);
778 if ((exp[exp[0] - i] & (1 << j)) != 0) {
779 internal_mul(b + mlen, n, a, mlen, scratch);
780 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
781 } else {
782 BignumInt *t;
783 t = a;
784 a = b;
785 b = t;
786 }
787 j--;
788 }
789 i++;
790 j = BIGNUM_INT_BITS-1;
791 }
792
793 /* Fixup result in case the modulus was shifted */
794 if (mshift) {
795 for (i = mlen - 1; i < 2 * mlen - 1; i++)
796 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
797 a[2 * mlen - 1] = a[2 * mlen - 1] << mshift;
798 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
799 for (i = 2 * mlen - 1; i >= mlen; i--)
800 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
801 }
802
803 /* Copy result to buffer */
804 result = newbn(mod[0]);
805 for (i = 0; i < mlen; i++)
806 result[result[0] - i] = a[i + mlen];
807 while (result[0] > 1 && result[result[0]] == 0)
808 result[0]--;
809
810 /* Free temporary arrays */
811 for (i = 0; i < 2 * mlen; i++)
812 a[i] = 0;
813 sfree(a);
814 for (i = 0; i < scratchlen; i++)
815 scratch[i] = 0;
816 sfree(scratch);
817 for (i = 0; i < 2 * mlen; i++)
818 b[i] = 0;
819 sfree(b);
820 for (i = 0; i < mlen; i++)
821 m[i] = 0;
822 sfree(m);
823 for (i = 0; i < mlen; i++)
824 n[i] = 0;
825 sfree(n);
826
827 freebn(base);
828
829 return result;
830 }
831
832 /*
833 * Compute (base ^ exp) % mod. Uses the Montgomery multiplication
834 * technique where possible, falling back to modpow_simple otherwise.
835 */
836 Bignum modpow(Bignum base_in, Bignum exp, Bignum mod)
837 {
838 BignumInt *a, *b, *x, *n, *mninv, *scratch;
839 int len, scratchlen, i, j;
840 Bignum base, base2, r, rn, inv, result;
841
842 /*
843 * The most significant word of mod needs to be non-zero. It
844 * should already be, but let's make sure.
845 */
846 assert(mod[mod[0]] != 0);
847
848 /*
849 * mod had better be odd, or we can't do Montgomery multiplication
850 * using a power of two at all.
851 */
852 if (!(mod[1] & 1))
853 return modpow_simple(base_in, exp, mod);
854
855 /*
856 * Make sure the base is smaller than the modulus, by reducing
857 * it modulo the modulus if not.
858 */
859 base = bigmod(base_in, mod);
860
861 /*
862 * Compute the inverse of n mod r, for monty_reduce. (In fact we
863 * want the inverse of _minus_ n mod r, but we'll sort that out
864 * below.)
865 */
866 len = mod[0];
867 r = bn_power_2(BIGNUM_INT_BITS * len);
868 inv = modinv(mod, r);
869
870 /*
871 * Multiply the base by r mod n, to get it into Montgomery
872 * representation.
873 */
874 base2 = modmul(base, r, mod);
875 freebn(base);
876 base = base2;
877
878 rn = bigmod(r, mod); /* r mod n, i.e. Montgomerified 1 */
879
880 freebn(r); /* won't need this any more */
881
882 /*
883 * Set up internal arrays of the right lengths, in big-endian
884 * format, containing the base, the modulus, and the modulus's
885 * inverse.
886 */
887 n = snewn(len, BignumInt);
888 for (j = 0; j < len; j++)
889 n[len - 1 - j] = mod[j + 1];
890
891 mninv = snewn(len, BignumInt);
892 for (j = 0; j < len; j++)
893 mninv[len - 1 - j] = (j < inv[0] ? inv[j + 1] : 0);
894 freebn(inv); /* we don't need this copy of it any more */
895 /* Now negate mninv mod r, so it's the inverse of -n rather than +n. */
896 x = snewn(len, BignumInt);
897 for (j = 0; j < len; j++)
898 x[j] = 0;
899 internal_sub(x, mninv, mninv, len);
900
901 /* x = snewn(len, BignumInt); */ /* already done above */
902 for (j = 0; j < len; j++)
903 x[len - 1 - j] = (j < base[0] ? base[j + 1] : 0);
904 freebn(base); /* we don't need this copy of it any more */
905
906 a = snewn(2*len, BignumInt);
907 b = snewn(2*len, BignumInt);
908 for (j = 0; j < len; j++)
909 a[2*len - 1 - j] = (j < rn[0] ? rn[j + 1] : 0);
910 freebn(rn);
911
912 /* Scratch space for multiplies */
913 scratchlen = 3*len + mul_compute_scratch(len);
914 scratch = snewn(scratchlen, BignumInt);
915
916 /* Skip leading zero bits of exp. */
917 i = 0;
918 j = BIGNUM_INT_BITS-1;
919 while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
920 j--;
921 if (j < 0) {
922 i++;
923 j = BIGNUM_INT_BITS-1;
924 }
925 }
926
927 /* Main computation */
928 while (i < (int)exp[0]) {
929 while (j >= 0) {
930 internal_mul(a + len, a + len, b, len, scratch);
931 monty_reduce(b, n, mninv, scratch, len);
932 if ((exp[exp[0] - i] & (1 << j)) != 0) {
933 internal_mul(b + len, x, a, len, scratch);
934 monty_reduce(a, n, mninv, scratch, len);
935 } else {
936 BignumInt *t;
937 t = a;
938 a = b;
939 b = t;
940 }
941 j--;
942 }
943 i++;
944 j = BIGNUM_INT_BITS-1;
945 }
946
947 /*
948 * Final monty_reduce to get back from the adjusted Montgomery
949 * representation.
950 */
951 monty_reduce(a, n, mninv, scratch, len);
952
953 /* Copy result to buffer */
954 result = newbn(mod[0]);
955 for (i = 0; i < len; i++)
956 result[result[0] - i] = a[i + len];
957 while (result[0] > 1 && result[result[0]] == 0)
958 result[0]--;
959
960 /* Free temporary arrays */
961 for (i = 0; i < scratchlen; i++)
962 scratch[i] = 0;
963 sfree(scratch);
964 for (i = 0; i < 2 * len; i++)
965 a[i] = 0;
966 sfree(a);
967 for (i = 0; i < 2 * len; i++)
968 b[i] = 0;
969 sfree(b);
970 for (i = 0; i < len; i++)
971 mninv[i] = 0;
972 sfree(mninv);
973 for (i = 0; i < len; i++)
974 n[i] = 0;
975 sfree(n);
976 for (i = 0; i < len; i++)
977 x[i] = 0;
978 sfree(x);
979
980 return result;
981 }
982
983 /*
984 * Compute (p * q) % mod.
985 * The most significant word of mod MUST be non-zero.
986 * We assume that the result array is the same size as the mod array.
987 */
988 Bignum modmul(Bignum p, Bignum q, Bignum mod)
989 {
990 BignumInt *a, *n, *m, *o, *scratch;
991 int mshift, scratchlen;
992 int pqlen, mlen, rlen, i, j;
993 Bignum result;
994
995 /* Allocate m of size mlen, copy mod to m */
996 /* We use big endian internally */
997 mlen = mod[0];
998 m = snewn(mlen, BignumInt);
999 for (j = 0; j < mlen; j++)
1000 m[j] = mod[mod[0] - j];
1001
1002 /* Shift m left to make msb bit set */
1003 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
1004 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
1005 break;
1006 if (mshift) {
1007 for (i = 0; i < mlen - 1; i++)
1008 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
1009 m[mlen - 1] = m[mlen - 1] << mshift;
1010 }
1011
1012 pqlen = (p[0] > q[0] ? p[0] : q[0]);
1013
1014 /* Allocate n of size pqlen, copy p to n */
1015 n = snewn(pqlen, BignumInt);
1016 i = pqlen - p[0];
1017 for (j = 0; j < i; j++)
1018 n[j] = 0;
1019 for (j = 0; j < (int)p[0]; j++)
1020 n[i + j] = p[p[0] - j];
1021
1022 /* Allocate o of size pqlen, copy q to o */
1023 o = snewn(pqlen, BignumInt);
1024 i = pqlen - q[0];
1025 for (j = 0; j < i; j++)
1026 o[j] = 0;
1027 for (j = 0; j < (int)q[0]; j++)
1028 o[i + j] = q[q[0] - j];
1029
1030 /* Allocate a of size 2*pqlen for result */
1031 a = snewn(2 * pqlen, BignumInt);
1032
1033 /* Scratch space for multiplies */
1034 scratchlen = mul_compute_scratch(pqlen);
1035 scratch = snewn(scratchlen, BignumInt);
1036
1037 /* Main computation */
1038 internal_mul(n, o, a, pqlen, scratch);
1039 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
1040
1041 /* Fixup result in case the modulus was shifted */
1042 if (mshift) {
1043 for (i = 2 * pqlen - mlen - 1; i < 2 * pqlen - 1; i++)
1044 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
1045 a[2 * pqlen - 1] = a[2 * pqlen - 1] << mshift;
1046 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
1047 for (i = 2 * pqlen - 1; i >= 2 * pqlen - mlen; i--)
1048 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
1049 }
1050
1051 /* Copy result to buffer */
1052 rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
1053 result = newbn(rlen);
1054 for (i = 0; i < rlen; i++)
1055 result[result[0] - i] = a[i + 2 * pqlen - rlen];
1056 while (result[0] > 1 && result[result[0]] == 0)
1057 result[0]--;
1058
1059 /* Free temporary arrays */
1060 for (i = 0; i < scratchlen; i++)
1061 scratch[i] = 0;
1062 sfree(scratch);
1063 for (i = 0; i < 2 * pqlen; i++)
1064 a[i] = 0;
1065 sfree(a);
1066 for (i = 0; i < mlen; i++)
1067 m[i] = 0;
1068 sfree(m);
1069 for (i = 0; i < pqlen; i++)
1070 n[i] = 0;
1071 sfree(n);
1072 for (i = 0; i < pqlen; i++)
1073 o[i] = 0;
1074 sfree(o);
1075
1076 return result;
1077 }
1078
1079 /*
1080 * Compute p % mod.
1081 * The most significant word of mod MUST be non-zero.
1082 * We assume that the result array is the same size as the mod array.
1083 * We optionally write out a quotient if `quotient' is non-NULL.
1084 * We can avoid writing out the result if `result' is NULL.
1085 */
1086 static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
1087 {
1088 BignumInt *n, *m;
1089 int mshift;
1090 int plen, mlen, i, j;
1091
1092 /* Allocate m of size mlen, copy mod to m */
1093 /* We use big endian internally */
1094 mlen = mod[0];
1095 m = snewn(mlen, BignumInt);
1096 for (j = 0; j < mlen; j++)
1097 m[j] = mod[mod[0] - j];
1098
1099 /* Shift m left to make msb bit set */
1100 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
1101 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
1102 break;
1103 if (mshift) {
1104 for (i = 0; i < mlen - 1; i++)
1105 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
1106 m[mlen - 1] = m[mlen - 1] << mshift;
1107 }
1108
1109 plen = p[0];
1110 /* Ensure plen > mlen */
1111 if (plen <= mlen)
1112 plen = mlen + 1;
1113
1114 /* Allocate n of size plen, copy p to n */
1115 n = snewn(plen, BignumInt);
1116 for (j = 0; j < plen; j++)
1117 n[j] = 0;
1118 for (j = 1; j <= (int)p[0]; j++)
1119 n[plen - j] = p[j];
1120
1121 /* Main computation */
1122 internal_mod(n, plen, m, mlen, quotient, mshift);
1123
1124 /* Fixup result in case the modulus was shifted */
1125 if (mshift) {
1126 for (i = plen - mlen - 1; i < plen - 1; i++)
1127 n[i] = (n[i] << mshift) | (n[i + 1] >> (BIGNUM_INT_BITS - mshift));
1128 n[plen - 1] = n[plen - 1] << mshift;
1129 internal_mod(n, plen, m, mlen, quotient, 0);
1130 for (i = plen - 1; i >= plen - mlen; i--)
1131 n[i] = (n[i] >> mshift) | (n[i - 1] << (BIGNUM_INT_BITS - mshift));
1132 }
1133
1134 /* Copy result to buffer */
1135 if (result) {
1136 for (i = 1; i <= (int)result[0]; i++) {
1137 int j = plen - i;
1138 result[i] = j >= 0 ? n[j] : 0;
1139 }
1140 }
1141
1142 /* Free temporary arrays */
1143 for (i = 0; i < mlen; i++)
1144 m[i] = 0;
1145 sfree(m);
1146 for (i = 0; i < plen; i++)
1147 n[i] = 0;
1148 sfree(n);
1149 }
1150
1151 /*
1152 * Decrement a number.
1153 */
1154 void decbn(Bignum bn)
1155 {
1156 int i = 1;
1157 while (i < (int)bn[0] && bn[i] == 0)
1158 bn[i++] = BIGNUM_INT_MASK;
1159 bn[i]--;
1160 }
1161
1162 Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
1163 {
1164 Bignum result;
1165 int w, i;
1166
1167 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
1168
1169 result = newbn(w);
1170 for (i = 1; i <= w; i++)
1171 result[i] = 0;
1172 for (i = nbytes; i--;) {
1173 unsigned char byte = *data++;
1174 result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);
1175 }
1176
1177 while (result[0] > 1 && result[result[0]] == 0)
1178 result[0]--;
1179 return result;
1180 }
1181
1182 /*
1183 * Read an SSH-1-format bignum from a data buffer. Return the number
1184 * of bytes consumed, or -1 if there wasn't enough data.
1185 */
1186 int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)
1187 {
1188 const unsigned char *p = data;
1189 int i;
1190 int w, b;
1191
1192 if (len < 2)
1193 return -1;
1194
1195 w = 0;
1196 for (i = 0; i < 2; i++)
1197 w = (w << 8) + *p++;
1198 b = (w + 7) / 8; /* bits -> bytes */
1199
1200 if (len < b+2)
1201 return -1;
1202
1203 if (!result) /* just return length */
1204 return b + 2;
1205
1206 *result = bignum_from_bytes(p, b);
1207
1208 return p + b - data;
1209 }
1210
1211 /*
1212 * Return the bit count of a bignum, for SSH-1 encoding.
1213 */
1214 int bignum_bitcount(Bignum bn)
1215 {
1216 int bitcount = bn[0] * BIGNUM_INT_BITS - 1;
1217 while (bitcount >= 0
1218 && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;
1219 return bitcount + 1;
1220 }
1221
1222 /*
1223 * Return the byte length of a bignum when SSH-1 encoded.
1224 */
1225 int ssh1_bignum_length(Bignum bn)
1226 {
1227 return 2 + (bignum_bitcount(bn) + 7) / 8;
1228 }
1229
1230 /*
1231 * Return the byte length of a bignum when SSH-2 encoded.
1232 */
1233 int ssh2_bignum_length(Bignum bn)
1234 {
1235 return 4 + (bignum_bitcount(bn) + 8) / 8;
1236 }
1237
1238 /*
1239 * Return a byte from a bignum; 0 is least significant, etc.
1240 */
1241 int bignum_byte(Bignum bn, int i)
1242 {
1243 if (i >= (int)(BIGNUM_INT_BYTES * bn[0]))
1244 return 0; /* beyond the end */
1245 else
1246 return (bn[i / BIGNUM_INT_BYTES + 1] >>
1247 ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;
1248 }
1249
1250 /*
1251 * Return a bit from a bignum; 0 is least significant, etc.
1252 */
1253 int bignum_bit(Bignum bn, int i)
1254 {
1255 if (i >= (int)(BIGNUM_INT_BITS * bn[0]))
1256 return 0; /* beyond the end */
1257 else
1258 return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;
1259 }
1260
1261 /*
1262 * Set a bit in a bignum; 0 is least significant, etc.
1263 */
1264 void bignum_set_bit(Bignum bn, int bitnum, int value)
1265 {
1266 if (bitnum >= (int)(BIGNUM_INT_BITS * bn[0]))
1267 abort(); /* beyond the end */
1268 else {
1269 int v = bitnum / BIGNUM_INT_BITS + 1;
1270 int mask = 1 << (bitnum % BIGNUM_INT_BITS);
1271 if (value)
1272 bn[v] |= mask;
1273 else
1274 bn[v] &= ~mask;
1275 }
1276 }
1277
1278 /*
1279 * Write a SSH-1-format bignum into a buffer. It is assumed the
1280 * buffer is big enough. Returns the number of bytes used.
1281 */
1282 int ssh1_write_bignum(void *data, Bignum bn)
1283 {
1284 unsigned char *p = data;
1285 int len = ssh1_bignum_length(bn);
1286 int i;
1287 int bitc = bignum_bitcount(bn);
1288
1289 *p++ = (bitc >> 8) & 0xFF;
1290 *p++ = (bitc) & 0xFF;
1291 for (i = len - 2; i--;)
1292 *p++ = bignum_byte(bn, i);
1293 return len;
1294 }
1295
1296 /*
1297 * Compare two bignums. Returns like strcmp.
1298 */
1299 int bignum_cmp(Bignum a, Bignum b)
1300 {
1301 int amax = a[0], bmax = b[0];
1302 int i = (amax > bmax ? amax : bmax);
1303 while (i) {
1304 BignumInt aval = (i > amax ? 0 : a[i]);
1305 BignumInt bval = (i > bmax ? 0 : b[i]);
1306 if (aval < bval)
1307 return -1;
1308 if (aval > bval)
1309 return +1;
1310 i--;
1311 }
1312 return 0;
1313 }
1314
1315 /*
1316 * Right-shift one bignum to form another.
1317 */
1318 Bignum bignum_rshift(Bignum a, int shift)
1319 {
1320 Bignum ret;
1321 int i, shiftw, shiftb, shiftbb, bits;
1322 BignumInt ai, ai1;
1323
1324 bits = bignum_bitcount(a) - shift;
1325 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
1326
1327 if (ret) {
1328 shiftw = shift / BIGNUM_INT_BITS;
1329 shiftb = shift % BIGNUM_INT_BITS;
1330 shiftbb = BIGNUM_INT_BITS - shiftb;
1331
1332 ai1 = a[shiftw + 1];
1333 for (i = 1; i <= (int)ret[0]; i++) {
1334 ai = ai1;
1335 ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);
1336 ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;
1337 }
1338 }
1339
1340 return ret;
1341 }
1342
1343 /*
1344 * Non-modular multiplication and addition.
1345 */
1346 Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
1347 {
1348 int alen = a[0], blen = b[0];
1349 int mlen = (alen > blen ? alen : blen);
1350 int rlen, i, maxspot;
1351 int wslen;
1352 BignumInt *workspace;
1353 Bignum ret;
1354
1355 /* mlen space for a, mlen space for b, 2*mlen for result,
1356 * plus scratch space for multiplication */
1357 wslen = mlen * 4 + mul_compute_scratch(mlen);
1358 workspace = snewn(wslen, BignumInt);
1359 for (i = 0; i < mlen; i++) {
1360 workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);
1361 workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);
1362 }
1363
1364 internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
1365 workspace + 2 * mlen, mlen, workspace + 4 * mlen);
1366
1367 /* now just copy the result back */
1368 rlen = alen + blen + 1;
1369 if (addend && rlen <= (int)addend[0])
1370 rlen = addend[0] + 1;
1371 ret = newbn(rlen);
1372 maxspot = 0;
1373 for (i = 1; i <= (int)ret[0]; i++) {
1374 ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
1375 if (ret[i] != 0)
1376 maxspot = i;
1377 }
1378 ret[0] = maxspot;
1379
1380 /* now add in the addend, if any */
1381 if (addend) {
1382 BignumDblInt carry = 0;
1383 for (i = 1; i <= rlen; i++) {
1384 carry += (i <= (int)ret[0] ? ret[i] : 0);
1385 carry += (i <= (int)addend[0] ? addend[i] : 0);
1386 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1387 carry >>= BIGNUM_INT_BITS;
1388 if (ret[i] != 0 && i > maxspot)
1389 maxspot = i;
1390 }
1391 }
1392 ret[0] = maxspot;
1393
1394 for (i = 0; i < wslen; i++)
1395 workspace[i] = 0;
1396 sfree(workspace);
1397 return ret;
1398 }
1399
1400 /*
1401 * Non-modular multiplication.
1402 */
1403 Bignum bigmul(Bignum a, Bignum b)
1404 {
1405 return bigmuladd(a, b, NULL);
1406 }
1407
1408 /*
1409 * Simple addition.
1410 */
1411 Bignum bigadd(Bignum a, Bignum b)
1412 {
1413 int alen = a[0], blen = b[0];
1414 int rlen = (alen > blen ? alen : blen) + 1;
1415 int i, maxspot;
1416 Bignum ret;
1417 BignumDblInt carry;
1418
1419 ret = newbn(rlen);
1420
1421 carry = 0;
1422 maxspot = 0;
1423 for (i = 1; i <= rlen; i++) {
1424 carry += (i <= (int)a[0] ? a[i] : 0);
1425 carry += (i <= (int)b[0] ? b[i] : 0);
1426 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1427 carry >>= BIGNUM_INT_BITS;
1428 if (ret[i] != 0 && i > maxspot)
1429 maxspot = i;
1430 }
1431 ret[0] = maxspot;
1432
1433 return ret;
1434 }
1435
1436 /*
1437 * Subtraction. Returns a-b, or NULL if the result would come out
1438 * negative (recall that this entire bignum module only handles
1439 * positive numbers).
1440 */
1441 Bignum bigsub(Bignum a, Bignum b)
1442 {
1443 int alen = a[0], blen = b[0];
1444 int rlen = (alen > blen ? alen : blen);
1445 int i, maxspot;
1446 Bignum ret;
1447 BignumDblInt carry;
1448
1449 ret = newbn(rlen);
1450
1451 carry = 1;
1452 maxspot = 0;
1453 for (i = 1; i <= rlen; i++) {
1454 carry += (i <= (int)a[0] ? a[i] : 0);
1455 carry += (i <= (int)b[0] ? b[i] ^ BIGNUM_INT_MASK : BIGNUM_INT_MASK);
1456 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1457 carry >>= BIGNUM_INT_BITS;
1458 if (ret[i] != 0 && i > maxspot)
1459 maxspot = i;
1460 }
1461 ret[0] = maxspot;
1462
1463 if (!carry) {
1464 freebn(ret);
1465 return NULL;
1466 }
1467
1468 return ret;
1469 }
1470
1471 /*
1472 * Create a bignum which is the bitmask covering another one. That
1473 * is, the smallest integer which is >= N and is also one less than
1474 * a power of two.
1475 */
1476 Bignum bignum_bitmask(Bignum n)
1477 {
1478 Bignum ret = copybn(n);
1479 int i;
1480 BignumInt j;
1481
1482 i = ret[0];
1483 while (n[i] == 0 && i > 0)
1484 i--;
1485 if (i <= 0)
1486 return ret; /* input was zero */
1487 j = 1;
1488 while (j < n[i])
1489 j = 2 * j + 1;
1490 ret[i] = j;
1491 while (--i > 0)
1492 ret[i] = BIGNUM_INT_MASK;
1493 return ret;
1494 }
1495
1496 /*
1497 * Convert a (max 32-bit) long into a bignum.
1498 */
1499 Bignum bignum_from_long(unsigned long nn)
1500 {
1501 Bignum ret;
1502 BignumDblInt n = nn;
1503
1504 ret = newbn(3);
1505 ret[1] = (BignumInt)(n & BIGNUM_INT_MASK);
1506 ret[2] = (BignumInt)((n >> BIGNUM_INT_BITS) & BIGNUM_INT_MASK);
1507 ret[3] = 0;
1508 ret[0] = (ret[2] ? 2 : 1);
1509 return ret;
1510 }
1511
1512 /*
1513 * Add a long to a bignum.
1514 */
1515 Bignum bignum_add_long(Bignum number, unsigned long addendx)
1516 {
1517 Bignum ret = newbn(number[0] + 1);
1518 int i, maxspot = 0;
1519 BignumDblInt carry = 0, addend = addendx;
1520
1521 for (i = 1; i <= (int)ret[0]; i++) {
1522 carry += addend & BIGNUM_INT_MASK;
1523 carry += (i <= (int)number[0] ? number[i] : 0);
1524 addend >>= BIGNUM_INT_BITS;
1525 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1526 carry >>= BIGNUM_INT_BITS;
1527 if (ret[i] != 0)
1528 maxspot = i;
1529 }
1530 ret[0] = maxspot;
1531 return ret;
1532 }
1533
1534 /*
1535 * Compute the residue of a bignum, modulo a (max 16-bit) short.
1536 */
1537 unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
1538 {
1539 BignumDblInt mod, r;
1540 int i;
1541
1542 r = 0;
1543 mod = modulus;
1544 for (i = number[0]; i > 0; i--)
1545 r = (r * (BIGNUM_TOP_BIT % mod) * 2 + number[i] % mod) % mod;
1546 return (unsigned short) r;
1547 }
1548
1549 #ifdef DEBUG
1550 void diagbn(char *prefix, Bignum md)
1551 {
1552 int i, nibbles, morenibbles;
1553 static const char hex[] = "0123456789ABCDEF";
1554
1555 debug(("%s0x", prefix ? prefix : ""));
1556
1557 nibbles = (3 + bignum_bitcount(md)) / 4;
1558 if (nibbles < 1)
1559 nibbles = 1;
1560 morenibbles = 4 * md[0] - nibbles;
1561 for (i = 0; i < morenibbles; i++)
1562 debug(("-"));
1563 for (i = nibbles; i--;)
1564 debug(("%c",
1565 hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
1566
1567 if (prefix)
1568 debug(("\n"));
1569 }
1570 #endif
1571
1572 /*
1573 * Simple division.
1574 */
1575 Bignum bigdiv(Bignum a, Bignum b)
1576 {
1577 Bignum q = newbn(a[0]);
1578 bigdivmod(a, b, NULL, q);
1579 return q;
1580 }
1581
1582 /*
1583 * Simple remainder.
1584 */
1585 Bignum bigmod(Bignum a, Bignum b)
1586 {
1587 Bignum r = newbn(b[0]);
1588 bigdivmod(a, b, r, NULL);
1589 return r;
1590 }
1591
1592 /*
1593 * Greatest common divisor.
1594 */
1595 Bignum biggcd(Bignum av, Bignum bv)
1596 {
1597 Bignum a = copybn(av);
1598 Bignum b = copybn(bv);
1599
1600 while (bignum_cmp(b, Zero) != 0) {
1601 Bignum t = newbn(b[0]);
1602 bigdivmod(a, b, t, NULL);
1603 while (t[0] > 1 && t[t[0]] == 0)
1604 t[0]--;
1605 freebn(a);
1606 a = b;
1607 b = t;
1608 }
1609
1610 freebn(b);
1611 return a;
1612 }
1613
1614 /*
1615 * Modular inverse, using Euclid's extended algorithm.
1616 */
1617 Bignum modinv(Bignum number, Bignum modulus)
1618 {
1619 Bignum a = copybn(modulus);
1620 Bignum b = copybn(number);
1621 Bignum xp = copybn(Zero);
1622 Bignum x = copybn(One);
1623 int sign = +1;
1624
1625 while (bignum_cmp(b, One) != 0) {
1626 Bignum t = newbn(b[0]);
1627 Bignum q = newbn(a[0]);
1628 bigdivmod(a, b, t, q);
1629 while (t[0] > 1 && t[t[0]] == 0)
1630 t[0]--;
1631 freebn(a);
1632 a = b;
1633 b = t;
1634 t = xp;
1635 xp = x;
1636 x = bigmuladd(q, xp, t);
1637 sign = -sign;
1638 freebn(t);
1639 freebn(q);
1640 }
1641
1642 freebn(b);
1643 freebn(a);
1644 freebn(xp);
1645
1646 /* now we know that sign * x == 1, and that x < modulus */
1647 if (sign < 0) {
1648 /* set a new x to be modulus - x */
1649 Bignum newx = newbn(modulus[0]);
1650 BignumInt carry = 0;
1651 int maxspot = 1;
1652 int i;
1653
1654 for (i = 1; i <= (int)newx[0]; i++) {
1655 BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);
1656 BignumInt bword = (i <= (int)x[0] ? x[i] : 0);
1657 newx[i] = aword - bword - carry;
1658 bword = ~bword;
1659 carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
1660 if (newx[i] != 0)
1661 maxspot = i;
1662 }
1663 newx[0] = maxspot;
1664 freebn(x);
1665 x = newx;
1666 }
1667
1668 /* and return. */
1669 return x;
1670 }
1671
1672 /*
1673 * Render a bignum into decimal. Return a malloced string holding
1674 * the decimal representation.
1675 */
1676 char *bignum_decimal(Bignum x)
1677 {
1678 int ndigits, ndigit;
1679 int i, iszero;
1680 BignumDblInt carry;
1681 char *ret;
1682 BignumInt *workspace;
1683
1684 /*
1685 * First, estimate the number of digits. Since log(10)/log(2)
1686 * is just greater than 93/28 (the joys of continued fraction
1687 * approximations...) we know that for every 93 bits, we need
1688 * at most 28 digits. This will tell us how much to malloc.
1689 *
1690 * Formally: if x has i bits, that means x is strictly less
1691 * than 2^i. Since 2 is less than 10^(28/93), this is less than
1692 * 10^(28i/93). We need an integer power of ten, so we must
1693 * round up (rounding down might make it less than x again).
1694 * Therefore if we multiply the bit count by 28/93, rounding
1695 * up, we will have enough digits.
1696 *
1697 * i=0 (i.e., x=0) is an irritating special case.
1698 */
1699 i = bignum_bitcount(x);
1700 if (!i)
1701 ndigits = 1; /* x = 0 */
1702 else
1703 ndigits = (28 * i + 92) / 93; /* multiply by 28/93 and round up */
1704 ndigits++; /* allow for trailing \0 */
1705 ret = snewn(ndigits, char);
1706
1707 /*
1708 * Now allocate some workspace to hold the binary form as we
1709 * repeatedly divide it by ten. Initialise this to the
1710 * big-endian form of the number.
1711 */
1712 workspace = snewn(x[0], BignumInt);
1713 for (i = 0; i < (int)x[0]; i++)
1714 workspace[i] = x[x[0] - i];
1715
1716 /*
1717 * Next, write the decimal number starting with the last digit.
1718 * We use ordinary short division, dividing 10 into the
1719 * workspace.
1720 */
1721 ndigit = ndigits - 1;
1722 ret[ndigit] = '\0';
1723 do {
1724 iszero = 1;
1725 carry = 0;
1726 for (i = 0; i < (int)x[0]; i++) {
1727 carry = (carry << BIGNUM_INT_BITS) + workspace[i];
1728 workspace[i] = (BignumInt) (carry / 10);
1729 if (workspace[i])
1730 iszero = 0;
1731 carry %= 10;
1732 }
1733 ret[--ndigit] = (char) (carry + '0');
1734 } while (!iszero);
1735
1736 /*
1737 * There's a chance we've fallen short of the start of the
1738 * string. Correct if so.
1739 */
1740 if (ndigit > 0)
1741 memmove(ret, ret + ndigit, ndigits - ndigit);
1742
1743 /*
1744 * Done.
1745 */
1746 sfree(workspace);
1747 return ret;
1748 }
1749
1750 #ifdef TESTBN
1751
1752 #include <stdio.h>
1753 #include <stdlib.h>
1754 #include <ctype.h>
1755
1756 /*
1757 * gcc -g -O0 -DTESTBN -o testbn sshbn.c misc.c -I unix -I charset
1758 *
1759 * Then feed to this program's standard input the output of
1760 * testdata/bignum.py .
1761 */
1762
1763 void modalfatalbox(char *p, ...)
1764 {
1765 va_list ap;
1766 fprintf(stderr, "FATAL ERROR: ");
1767 va_start(ap, p);
1768 vfprintf(stderr, p, ap);
1769 va_end(ap);
1770 fputc('\n', stderr);
1771 exit(1);
1772 }
1773
1774 #define fromxdigit(c) ( (c)>'9' ? ((c)&0xDF) - 'A' + 10 : (c) - '0' )
1775
1776 int main(int argc, char **argv)
1777 {
1778 char *buf;
1779 int line = 0;
1780 int passes = 0, fails = 0;
1781
1782 while ((buf = fgetline(stdin)) != NULL) {
1783 int maxlen = strlen(buf);
1784 unsigned char *data = snewn(maxlen, unsigned char);
1785 unsigned char *ptrs[5], *q;
1786 int ptrnum;
1787 char *bufp = buf;
1788
1789 line++;
1790
1791 q = data;
1792 ptrnum = 0;
1793
1794 while (*bufp && !isspace((unsigned char)*bufp))
1795 bufp++;
1796 if (bufp)
1797 *bufp++ = '\0';
1798
1799 while (*bufp) {
1800 char *start, *end;
1801 int i;
1802
1803 while (*bufp && !isxdigit((unsigned char)*bufp))
1804 bufp++;
1805 start = bufp;
1806
1807 if (!*bufp)
1808 break;
1809
1810 while (*bufp && isxdigit((unsigned char)*bufp))
1811 bufp++;
1812 end = bufp;
1813
1814 if (ptrnum >= lenof(ptrs))
1815 break;
1816 ptrs[ptrnum++] = q;
1817
1818 for (i = -((end - start) & 1); i < end-start; i += 2) {
1819 unsigned char val = (i < 0 ? 0 : fromxdigit(start[i]));
1820 val = val * 16 + fromxdigit(start[i+1]);
1821 *q++ = val;
1822 }
1823
1824 ptrs[ptrnum] = q;
1825 }
1826
1827 if (!strcmp(buf, "mul")) {
1828 Bignum a, b, c, p;
1829
1830 if (ptrnum != 3) {
1831 printf("%d: mul with %d parameters, expected 3\n", line);
1832 exit(1);
1833 }
1834 a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1835 b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1836 c = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1837 p = bigmul(a, b);
1838
1839 if (bignum_cmp(c, p) == 0) {
1840 passes++;
1841 } else {
1842 char *as = bignum_decimal(a);
1843 char *bs = bignum_decimal(b);
1844 char *cs = bignum_decimal(c);
1845 char *ps = bignum_decimal(p);
1846
1847 printf("%d: fail: %s * %s gave %s expected %s\n",
1848 line, as, bs, ps, cs);
1849 fails++;
1850
1851 sfree(as);
1852 sfree(bs);
1853 sfree(cs);
1854 sfree(ps);
1855 }
1856 freebn(a);
1857 freebn(b);
1858 freebn(c);
1859 freebn(p);
1860 } else if (!strcmp(buf, "pow")) {
1861 Bignum base, expt, modulus, expected, answer;
1862
1863 if (ptrnum != 4) {
1864 printf("%d: mul with %d parameters, expected 3\n", line);
1865 exit(1);
1866 }
1867
1868 base = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1869 expt = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1870 modulus = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1871 expected = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);
1872 answer = modpow(base, expt, modulus);
1873
1874 if (bignum_cmp(expected, answer) == 0) {
1875 passes++;
1876 } else {
1877 char *as = bignum_decimal(base);
1878 char *bs = bignum_decimal(expt);
1879 char *cs = bignum_decimal(modulus);
1880 char *ds = bignum_decimal(answer);
1881 char *ps = bignum_decimal(expected);
1882
1883 printf("%d: fail: %s ^ %s mod %s gave %s expected %s\n",
1884 line, as, bs, cs, ds, ps);
1885 fails++;
1886
1887 sfree(as);
1888 sfree(bs);
1889 sfree(cs);
1890 sfree(ds);
1891 sfree(ps);
1892 }
1893 freebn(base);
1894 freebn(expt);
1895 freebn(modulus);
1896 freebn(expected);
1897 freebn(answer);
1898 } else {
1899 printf("%d: unrecognised test keyword: '%s'\n", line, buf);
1900 exit(1);
1901 }
1902
1903 sfree(buf);
1904 sfree(data);
1905 }
1906
1907 printf("passed %d failed %d total %d\n", passes, fails, passes+fails);
1908 return fails != 0;
1909 }
1910
1911 #endif