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