Avoid trying to take the modular inverse of zero in response to a
[u/mdw/putty] / sshbn.c
CommitLineData
e5574168 1/*
2 * Bignum routines for RSA and DH and stuff.
3 */
4
5#include <stdio.h>
ed953b91 6#include <assert.h>
e5574168 7#include <stdlib.h>
8#include <string.h>
9
5c72ca61 10#include "misc.h"
98ba26b9 11
819a22b3 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
a3412f52 26#if defined __GNUC__ && defined __i386__
27typedef unsigned long BignumInt;
28typedef 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)
a47e8bba 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))
036eddfb 37#elif defined _MSC_VER && defined _M_IX86
38typedef unsigned __int32 BignumInt;
39typedef 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)
819a22b3 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> */
036eddfb 47#define DIVMOD_WORD(q, r, hi, lo, w) do { \
819a22b3 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)
32e51f76 54#elif defined _LP64
55/* 64-bit architectures can do 32x32->64 chunks at a time */
56typedef unsigned int BignumInt;
57typedef 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 */
69typedef unsigned long BignumInt;
70typedef 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)
a3412f52 80#else
32e51f76 81/* Fallback for all other cases */
a3412f52 82typedef unsigned short BignumInt;
83typedef 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)
a47e8bba 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)
a3412f52 93#endif
94
95#define BIGNUM_INT_BYTES (BIGNUM_INT_BITS / 8)
96
3709bfe9 97#define BIGNUM_INTERNAL
a3412f52 98typedef BignumInt *Bignum;
3709bfe9 99
e5574168 100#include "ssh.h"
101
a3412f52 102BignumInt bnZero[1] = { 0 };
103BignumInt bnOne[2] = { 1, 1 };
e5574168 104
7d6ee6ff 105/*
a3412f52 106 * The Bignum format is an array of `BignumInt'. The first
7d6ee6ff 107 * element of the array counts the remaining elements. The
a3412f52 108 * remaining elements express the actual number, base 2^BIGNUM_INT_BITS, _least_
7d6ee6ff 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
7cca0d81 119Bignum Zero = bnZero, One = bnOne;
e5574168 120
32874aea 121static Bignum newbn(int length)
122{
a3412f52 123 Bignum b = snewn(length + 1, BignumInt);
e5574168 124 if (!b)
125 abort(); /* FIXME */
32874aea 126 memset(b, 0, (length + 1) * sizeof(*b));
e5574168 127 b[0] = length;
128 return b;
129}
130
32874aea 131void bn_restore_invariant(Bignum b)
132{
133 while (b[0] > 1 && b[b[0]] == 0)
134 b[0]--;
3709bfe9 135}
136
32874aea 137Bignum copybn(Bignum orig)
138{
a3412f52 139 Bignum b = snewn(orig[0] + 1, BignumInt);
7cca0d81 140 if (!b)
141 abort(); /* FIXME */
32874aea 142 memcpy(b, orig, (orig[0] + 1) * sizeof(*b));
7cca0d81 143 return b;
144}
145
32874aea 146void freebn(Bignum b)
147{
e5574168 148 /*
149 * Burn the evidence, just in case.
150 */
dfb88efd 151 smemclr(b, sizeof(b[0]) * (b[0] + 1));
dcbde236 152 sfree(b);
e5574168 153}
154
32874aea 155Bignum bn_power_2(int n)
156{
a3412f52 157 Bignum ret = newbn(n / BIGNUM_INT_BITS + 1);
3709bfe9 158 bignum_set_bit(ret, n, 1);
159 return ret;
160}
161
e5574168 162/*
0c431b2f 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 */
167static 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 */
187static 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/*
e5574168 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.
5a502a19 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.)
e5574168 208 */
0c431b2f 209#define KARATSUBA_THRESHOLD 50
5a502a19 210static 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}
132c534f 221static void internal_mul(const BignumInt *a, const BignumInt *b,
5a502a19 222 BignumInt *c, int len, BignumInt *scratch)
e5574168 223{
0c431b2f 224 if (len > KARATSUBA_THRESHOLD) {
757b0110 225 int i;
0c431b2f 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;
0c431b2f 261 BignumDblInt carry;
f3c29e34 262#ifdef KARA_DEBUG
263 int i;
264#endif
0c431b2f 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
f3c29e34 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
0c431b2f 287 /* a_1 b_1 */
5a502a19 288 internal_mul(a, b, c, toplen, scratch);
f3c29e34 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
0c431b2f 296
297 /* a_0 b_0 */
5a502a19 298 internal_mul(a + toplen, b + toplen, c + 2*toplen, botlen, scratch);
f3c29e34 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
0c431b2f 306
0c431b2f 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
757b0110 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 */
0c431b2f 315 }
316
317 /* compute a_1 + a_0 */
318 scratch[0] = internal_add(scratch+1, a+toplen, scratch+1, botlen);
f3c29e34 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
0c431b2f 326 /* compute b_1 + b_0 */
327 scratch[midlen] = internal_add(scratch+midlen+1, b+toplen,
328 scratch+midlen+1, botlen);
f3c29e34 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
0c431b2f 336
337 /*
338 * Now we can do the third multiplication.
339 */
5a502a19 340 internal_mul(scratch, scratch + midlen, scratch + 2*midlen, midlen,
341 scratch + 4*midlen);
f3c29e34 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
0c431b2f 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;
757b0110 356 for (i = 0; i < 2*toplen; i++)
357 scratch[2*midlen - 2*toplen + i] = c[i];
0c431b2f 358 scratch[1] = internal_add(scratch+2, c + 2*toplen,
359 scratch+2, 2*botlen);
f3c29e34 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
0c431b2f 367
368 internal_sub(scratch + 2*midlen, scratch,
369 scratch + 2*midlen, 2*midlen);
f3c29e34 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
0c431b2f 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);
757b0110 387 i = 2*len - botlen - 2*midlen - 1;
0c431b2f 388 while (carry) {
757b0110 389 assert(i >= 0);
390 carry += c[i];
391 c[i] = (BignumInt)carry;
0c431b2f 392 carry >>= BIGNUM_INT_BITS;
757b0110 393 i--;
0c431b2f 394 }
f3c29e34 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
0c431b2f 402
0c431b2f 403 } else {
757b0110 404 int i;
405 BignumInt carry;
406 BignumDblInt t;
407 const BignumInt *ap, *bp;
408 BignumInt *cp, *cps;
0c431b2f 409
410 /*
411 * Multiply in the ordinary O(N^2) way.
412 */
413
757b0110 414 for (i = 0; i < 2 * len; i++)
415 c[i] = 0;
0c431b2f 416
757b0110 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;
08b5c9a2 422 carry = (BignumInt)(t >> BIGNUM_INT_BITS);
0c431b2f 423 }
757b0110 424 *cp = carry;
0c431b2f 425 }
e5574168 426 }
427}
428
132c534f 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 */
434static void internal_mul_low(const BignumInt *a, const BignumInt *b,
5a502a19 435 BignumInt *c, int len, BignumInt *scratch)
132c534f 436{
132c534f 437 if (len > KARATSUBA_THRESHOLD) {
757b0110 438 int i;
132c534f 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 */
132c534f 473
474 /*
5a502a19 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.
132c534f 480 */
132c534f 481
482 /* a_0 b_0 */
5a502a19 483 internal_mul(a + toplen, b + toplen, scratch + 2*toplen, botlen,
484 scratch + 2*len);
132c534f 485
486 /* a_1 b_0 */
5a502a19 487 internal_mul_low(a, b + len - toplen, scratch + toplen, toplen,
488 scratch + 2*len);
132c534f 489
490 /* a_0 b_1 */
5a502a19 491 internal_mul_low(a + len - toplen, b, scratch, toplen,
492 scratch + 2*len);
132c534f 493
494 /* Copy the bottom half of the big coefficient into place */
757b0110 495 for (i = 0; i < botlen; i++)
496 c[toplen + i] = scratch[2*toplen + botlen + i];
132c534f 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
132c534f 505 } else {
757b0110 506 int i;
507 BignumInt carry;
508 BignumDblInt t;
509 const BignumInt *ap, *bp;
510 BignumInt *cp, *cps;
132c534f 511
757b0110 512 /*
513 * Multiply in the ordinary O(N^2) way.
514 */
132c534f 515
757b0110 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;
08b5c9a2 524 carry = (BignumInt)(t >> BIGNUM_INT_BITS);
132c534f 525 }
526 }
132c534f 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 *
5a502a19 541 * 'tmp' is an array of BignumInt used as scratch space, of length at
542 * least 3*len + mul_compute_scratch(len).
132c534f 543 */
544static 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 */
5a502a19 555 internal_mul_low(x + len, mninv, tmp, len, tmp + 3*len);
132c534f 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 */
5a502a19 566 internal_mul(tmp, n, tmp+len, len, tmp + 3*len);
132c534f 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
a3412f52 591static void internal_add_shifted(BignumInt *number,
32874aea 592 unsigned n, int shift)
593{
a3412f52 594 int word = 1 + (shift / BIGNUM_INT_BITS);
595 int bshift = shift % BIGNUM_INT_BITS;
596 BignumDblInt addend;
9400cf6f 597
3014da2b 598 addend = (BignumDblInt)n << bshift;
9400cf6f 599
600 while (addend) {
32874aea 601 addend += number[word];
a3412f52 602 number[word] = (BignumInt) addend & BIGNUM_INT_MASK;
603 addend >>= BIGNUM_INT_BITS;
32874aea 604 word++;
9400cf6f 605 }
606}
607
e5574168 608/*
609 * Compute a = a % m.
9400cf6f 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).
e5574168 613 * The MSW of m MUST have its high bit set.
9400cf6f 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.
e5574168 617 */
a3412f52 618static void internal_mod(BignumInt *a, int alen,
619 BignumInt *m, int mlen,
620 BignumInt *quot, int qshift)
e5574168 621{
a3412f52 622 BignumInt m0, m1;
e5574168 623 unsigned int h;
624 int i, k;
625
e5574168 626 m0 = m[0];
8bd9144b 627 assert(m0 >> (BIGNUM_INT_BITS-1) == 1);
9400cf6f 628 if (mlen > 1)
32874aea 629 m1 = m[1];
9400cf6f 630 else
32874aea 631 m1 = 0;
e5574168 632
32874aea 633 for (i = 0; i <= alen - mlen; i++) {
a3412f52 634 BignumDblInt t;
9400cf6f 635 unsigned int q, r, c, ai1;
e5574168 636
637 if (i == 0) {
638 h = 0;
639 } else {
32874aea 640 h = a[i - 1];
641 a[i - 1] = 0;
e5574168 642 }
643
32874aea 644 if (i == alen - 1)
645 ai1 = 0;
646 else
647 ai1 = a[i + 1];
9400cf6f 648
e5574168 649 /* Find q = h:a[i] / m0 */
62ef3d44 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 {
819a22b3 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);
62ef3d44 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 }
e5574168 683 }
684
9400cf6f 685 /* Subtract q * m from a[i...] */
e5574168 686 c = 0;
9400cf6f 687 for (k = mlen - 1; k >= 0; k--) {
a47e8bba 688 t = MUL_WORD(q, m[k]);
e5574168 689 t += c;
62ddb51e 690 c = (unsigned)(t >> BIGNUM_INT_BITS);
a3412f52 691 if ((BignumInt) t > a[i + k])
32874aea 692 c++;
a3412f52 693 a[i + k] -= (BignumInt) t;
e5574168 694 }
695
696 /* Add back m in case of borrow */
697 if (c != h) {
698 t = 0;
9400cf6f 699 for (k = mlen - 1; k >= 0; k--) {
e5574168 700 t += m[k];
32874aea 701 t += a[i + k];
a3412f52 702 a[i + k] = (BignumInt) t;
703 t = t >> BIGNUM_INT_BITS;
e5574168 704 }
32874aea 705 q--;
e5574168 706 }
32874aea 707 if (quot)
a3412f52 708 internal_add_shifted(quot, q, qshift + BIGNUM_INT_BITS * (alen - mlen - i));
e5574168 709 }
710}
711
712/*
09095ac5 713 * Compute (base ^ exp) % mod, the pedestrian way.
e5574168 714 */
09095ac5 715Bignum modpow_simple(Bignum base_in, Bignum exp, Bignum mod)
e5574168 716{
5a502a19 717 BignumInt *a, *b, *n, *m, *scratch;
09095ac5 718 int mshift;
5a502a19 719 int mlen, scratchlen, i, j;
09095ac5 720 Bignum base, result;
ed953b91 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);
e5574168 733
09095ac5 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
5a502a19 766 /* Scratch space for multiplies */
767 scratchlen = mul_compute_scratch(mlen);
768 scratch = snewn(scratchlen, BignumInt);
769
09095ac5 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) {
5a502a19 784 internal_mul(a + mlen, a + mlen, b, mlen, scratch);
09095ac5 785 internal_mod(b, mlen * 2, m, mlen, NULL, 0);
786 if ((exp[exp[0] - i] & (1 << j)) != 0) {
5a502a19 787 internal_mul(b + mlen, n, a, mlen, scratch);
09095ac5 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 */
16430000 819 smemclr(a, 2 * mlen * sizeof(*a));
09095ac5 820 sfree(a);
16430000 821 smemclr(scratch, scratchlen * sizeof(*scratch));
5a502a19 822 sfree(scratch);
16430000 823 smemclr(b, 2 * mlen * sizeof(*b));
09095ac5 824 sfree(b);
16430000 825 smemclr(m, mlen * sizeof(*m));
09095ac5 826 sfree(m);
16430000 827 smemclr(n, mlen * sizeof(*n));
09095ac5 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 */
839Bignum modpow(Bignum base_in, Bignum exp, Bignum mod)
840{
5a502a19 841 BignumInt *a, *b, *x, *n, *mninv, *scratch;
842 int len, scratchlen, i, j;
09095ac5 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
132c534f 851 /*
852 * mod had better be odd, or we can't do Montgomery multiplication
853 * using a power of two at all.
854 */
09095ac5 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);
e5574168 863
132c534f 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);
e5574168 872
132c534f 873 /*
874 * Multiply the base by r mod n, to get it into Montgomery
875 * representation.
876 */
877 base2 = modmul(base, r, mod);
878 freebn(base);
879 base = base2;
880
881 rn = bigmod(r, mod); /* r mod n, i.e. Montgomerified 1 */
882
883 freebn(r); /* won't need this any more */
884
885 /*
886 * Set up internal arrays of the right lengths, in big-endian
887 * format, containing the base, the modulus, and the modulus's
888 * inverse.
889 */
890 n = snewn(len, BignumInt);
891 for (j = 0; j < len; j++)
892 n[len - 1 - j] = mod[j + 1];
893
894 mninv = snewn(len, BignumInt);
895 for (j = 0; j < len; j++)
08b5c9a2 896 mninv[len - 1 - j] = (j < (int)inv[0] ? inv[j + 1] : 0);
132c534f 897 freebn(inv); /* we don't need this copy of it any more */
898 /* Now negate mninv mod r, so it's the inverse of -n rather than +n. */
899 x = snewn(len, BignumInt);
900 for (j = 0; j < len; j++)
901 x[j] = 0;
902 internal_sub(x, mninv, mninv, len);
903
904 /* x = snewn(len, BignumInt); */ /* already done above */
905 for (j = 0; j < len; j++)
08b5c9a2 906 x[len - 1 - j] = (j < (int)base[0] ? base[j + 1] : 0);
132c534f 907 freebn(base); /* we don't need this copy of it any more */
908
909 a = snewn(2*len, BignumInt);
910 b = snewn(2*len, BignumInt);
911 for (j = 0; j < len; j++)
08b5c9a2 912 a[2*len - 1 - j] = (j < (int)rn[0] ? rn[j + 1] : 0);
132c534f 913 freebn(rn);
914
5a502a19 915 /* Scratch space for multiplies */
916 scratchlen = 3*len + mul_compute_scratch(len);
917 scratch = snewn(scratchlen, BignumInt);
e5574168 918
919 /* Skip leading zero bits of exp. */
32874aea 920 i = 0;
a3412f52 921 j = BIGNUM_INT_BITS-1;
62ddb51e 922 while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
e5574168 923 j--;
32874aea 924 if (j < 0) {
925 i++;
a3412f52 926 j = BIGNUM_INT_BITS-1;
32874aea 927 }
e5574168 928 }
929
930 /* Main computation */
62ddb51e 931 while (i < (int)exp[0]) {
e5574168 932 while (j >= 0) {
5a502a19 933 internal_mul(a + len, a + len, b, len, scratch);
934 monty_reduce(b, n, mninv, scratch, len);
e5574168 935 if ((exp[exp[0] - i] & (1 << j)) != 0) {
5a502a19 936 internal_mul(b + len, x, a, len, scratch);
937 monty_reduce(a, n, mninv, scratch, len);
e5574168 938 } else {
a3412f52 939 BignumInt *t;
32874aea 940 t = a;
941 a = b;
942 b = t;
e5574168 943 }
944 j--;
945 }
32874aea 946 i++;
a3412f52 947 j = BIGNUM_INT_BITS-1;
e5574168 948 }
949
132c534f 950 /*
951 * Final monty_reduce to get back from the adjusted Montgomery
952 * representation.
953 */
5a502a19 954 monty_reduce(a, n, mninv, scratch, len);
e5574168 955
956 /* Copy result to buffer */
59600f67 957 result = newbn(mod[0]);
132c534f 958 for (i = 0; i < len; i++)
959 result[result[0] - i] = a[i + len];
32874aea 960 while (result[0] > 1 && result[result[0]] == 0)
961 result[0]--;
e5574168 962
963 /* Free temporary arrays */
16430000 964 smemclr(scratch, scratchlen * sizeof(*scratch));
5a502a19 965 sfree(scratch);
16430000 966 smemclr(a, 2 * len * sizeof(*a));
32874aea 967 sfree(a);
16430000 968 smemclr(b, 2 * len * sizeof(*b));
32874aea 969 sfree(b);
16430000 970 smemclr(mninv, len * sizeof(*mninv));
132c534f 971 sfree(mninv);
16430000 972 smemclr(n, len * sizeof(*n));
32874aea 973 sfree(n);
16430000 974 smemclr(x, len * sizeof(*x));
132c534f 975 sfree(x);
ed953b91 976
59600f67 977 return result;
e5574168 978}
7cca0d81 979
980/*
981 * Compute (p * q) % mod.
982 * The most significant word of mod MUST be non-zero.
983 * We assume that the result array is the same size as the mod array.
984 */
59600f67 985Bignum modmul(Bignum p, Bignum q, Bignum mod)
7cca0d81 986{
5a502a19 987 BignumInt *a, *n, *m, *o, *scratch;
988 int mshift, scratchlen;
80b10571 989 int pqlen, mlen, rlen, i, j;
59600f67 990 Bignum result;
7cca0d81 991
8bd9144b 992 /*
993 * The most significant word of mod needs to be non-zero. It
994 * should already be, but let's make sure.
995 */
996 assert(mod[mod[0]] != 0);
997
7cca0d81 998 /* Allocate m of size mlen, copy mod to m */
999 /* We use big endian internally */
1000 mlen = mod[0];
a3412f52 1001 m = snewn(mlen, BignumInt);
32874aea 1002 for (j = 0; j < mlen; j++)
1003 m[j] = mod[mod[0] - j];
7cca0d81 1004
1005 /* Shift m left to make msb bit set */
a3412f52 1006 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
1007 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
32874aea 1008 break;
7cca0d81 1009 if (mshift) {
1010 for (i = 0; i < mlen - 1; i++)
a3412f52 1011 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
32874aea 1012 m[mlen - 1] = m[mlen - 1] << mshift;
7cca0d81 1013 }
1014
1015 pqlen = (p[0] > q[0] ? p[0] : q[0]);
1016
5064e5e6 1017 /*
1018 * Make sure that we're allowing enough space. The shifting below
1019 * will underflow the vectors we allocate if pqlen is too small.
1020 */
1021 if (2*pqlen <= mlen)
1022 pqlen = mlen/2 + 1;
1023
7cca0d81 1024 /* Allocate n of size pqlen, copy p to n */
a3412f52 1025 n = snewn(pqlen, BignumInt);
7cca0d81 1026 i = pqlen - p[0];
32874aea 1027 for (j = 0; j < i; j++)
1028 n[j] = 0;
62ddb51e 1029 for (j = 0; j < (int)p[0]; j++)
32874aea 1030 n[i + j] = p[p[0] - j];
7cca0d81 1031
1032 /* Allocate o of size pqlen, copy q to o */
a3412f52 1033 o = snewn(pqlen, BignumInt);
7cca0d81 1034 i = pqlen - q[0];
32874aea 1035 for (j = 0; j < i; j++)
1036 o[j] = 0;
62ddb51e 1037 for (j = 0; j < (int)q[0]; j++)
32874aea 1038 o[i + j] = q[q[0] - j];
7cca0d81 1039
1040 /* Allocate a of size 2*pqlen for result */
a3412f52 1041 a = snewn(2 * pqlen, BignumInt);
7cca0d81 1042
5a502a19 1043 /* Scratch space for multiplies */
1044 scratchlen = mul_compute_scratch(pqlen);
1045 scratch = snewn(scratchlen, BignumInt);
1046
7cca0d81 1047 /* Main computation */
5a502a19 1048 internal_mul(n, o, a, pqlen, scratch);
32874aea 1049 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
7cca0d81 1050
1051 /* Fixup result in case the modulus was shifted */
1052 if (mshift) {
32874aea 1053 for (i = 2 * pqlen - mlen - 1; i < 2 * pqlen - 1; i++)
a3412f52 1054 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
32874aea 1055 a[2 * pqlen - 1] = a[2 * pqlen - 1] << mshift;
1056 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
1057 for (i = 2 * pqlen - 1; i >= 2 * pqlen - mlen; i--)
a3412f52 1058 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
7cca0d81 1059 }
1060
1061 /* Copy result to buffer */
32874aea 1062 rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
80b10571 1063 result = newbn(rlen);
1064 for (i = 0; i < rlen; i++)
32874aea 1065 result[result[0] - i] = a[i + 2 * pqlen - rlen];
1066 while (result[0] > 1 && result[result[0]] == 0)
1067 result[0]--;
7cca0d81 1068
1069 /* Free temporary arrays */
16430000 1070 smemclr(scratch, scratchlen * sizeof(*scratch));
5a502a19 1071 sfree(scratch);
16430000 1072 smemclr(a, 2 * pqlen * sizeof(*a));
32874aea 1073 sfree(a);
16430000 1074 smemclr(m, mlen * sizeof(*m));
32874aea 1075 sfree(m);
16430000 1076 smemclr(n, pqlen * sizeof(*n));
32874aea 1077 sfree(n);
16430000 1078 smemclr(o, pqlen * sizeof(*o));
32874aea 1079 sfree(o);
59600f67 1080
1081 return result;
7cca0d81 1082}
1083
1084/*
9400cf6f 1085 * Compute p % mod.
1086 * The most significant word of mod MUST be non-zero.
1087 * We assume that the result array is the same size as the mod array.
5c72ca61 1088 * We optionally write out a quotient if `quotient' is non-NULL.
1089 * We can avoid writing out the result if `result' is NULL.
9400cf6f 1090 */
f28753ab 1091static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
9400cf6f 1092{
a3412f52 1093 BignumInt *n, *m;
9400cf6f 1094 int mshift;
1095 int plen, mlen, i, j;
1096
8bd9144b 1097 /*
1098 * The most significant word of mod needs to be non-zero. It
1099 * should already be, but let's make sure.
1100 */
1101 assert(mod[mod[0]] != 0);
1102
9400cf6f 1103 /* Allocate m of size mlen, copy mod to m */
1104 /* We use big endian internally */
1105 mlen = mod[0];
a3412f52 1106 m = snewn(mlen, BignumInt);
32874aea 1107 for (j = 0; j < mlen; j++)
1108 m[j] = mod[mod[0] - j];
9400cf6f 1109
1110 /* Shift m left to make msb bit set */
a3412f52 1111 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
1112 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
32874aea 1113 break;
9400cf6f 1114 if (mshift) {
1115 for (i = 0; i < mlen - 1; i++)
a3412f52 1116 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
32874aea 1117 m[mlen - 1] = m[mlen - 1] << mshift;
9400cf6f 1118 }
1119
1120 plen = p[0];
1121 /* Ensure plen > mlen */
32874aea 1122 if (plen <= mlen)
1123 plen = mlen + 1;
9400cf6f 1124
1125 /* Allocate n of size plen, copy p to n */
a3412f52 1126 n = snewn(plen, BignumInt);
32874aea 1127 for (j = 0; j < plen; j++)
1128 n[j] = 0;
62ddb51e 1129 for (j = 1; j <= (int)p[0]; j++)
32874aea 1130 n[plen - j] = p[j];
9400cf6f 1131
1132 /* Main computation */
1133 internal_mod(n, plen, m, mlen, quotient, mshift);
1134
1135 /* Fixup result in case the modulus was shifted */
1136 if (mshift) {
1137 for (i = plen - mlen - 1; i < plen - 1; i++)
a3412f52 1138 n[i] = (n[i] << mshift) | (n[i + 1] >> (BIGNUM_INT_BITS - mshift));
32874aea 1139 n[plen - 1] = n[plen - 1] << mshift;
9400cf6f 1140 internal_mod(n, plen, m, mlen, quotient, 0);
1141 for (i = plen - 1; i >= plen - mlen; i--)
a3412f52 1142 n[i] = (n[i] >> mshift) | (n[i - 1] << (BIGNUM_INT_BITS - mshift));
9400cf6f 1143 }
1144
1145 /* Copy result to buffer */
5c72ca61 1146 if (result) {
62ddb51e 1147 for (i = 1; i <= (int)result[0]; i++) {
5c72ca61 1148 int j = plen - i;
1149 result[i] = j >= 0 ? n[j] : 0;
1150 }
9400cf6f 1151 }
1152
1153 /* Free temporary arrays */
16430000 1154 smemclr(m, mlen * sizeof(*m));
32874aea 1155 sfree(m);
16430000 1156 smemclr(n, plen * sizeof(*n));
32874aea 1157 sfree(n);
9400cf6f 1158}
1159
1160/*
7cca0d81 1161 * Decrement a number.
1162 */
32874aea 1163void decbn(Bignum bn)
1164{
7cca0d81 1165 int i = 1;
62ddb51e 1166 while (i < (int)bn[0] && bn[i] == 0)
a3412f52 1167 bn[i++] = BIGNUM_INT_MASK;
7cca0d81 1168 bn[i]--;
1169}
1170
27cd7fc2 1171Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
32874aea 1172{
3709bfe9 1173 Bignum result;
1174 int w, i;
1175
a3412f52 1176 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
3709bfe9 1177
1178 result = newbn(w);
32874aea 1179 for (i = 1; i <= w; i++)
1180 result[i] = 0;
1181 for (i = nbytes; i--;) {
1182 unsigned char byte = *data++;
a3412f52 1183 result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);
3709bfe9 1184 }
1185
32874aea 1186 while (result[0] > 1 && result[result[0]] == 0)
1187 result[0]--;
3709bfe9 1188 return result;
1189}
1190
7cca0d81 1191/*
2e85c969 1192 * Read an SSH-1-format bignum from a data buffer. Return the number
0016d70b 1193 * of bytes consumed, or -1 if there wasn't enough data.
7cca0d81 1194 */
0016d70b 1195int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)
32874aea 1196{
27cd7fc2 1197 const unsigned char *p = data;
7cca0d81 1198 int i;
1199 int w, b;
1200
0016d70b 1201 if (len < 2)
1202 return -1;
1203
7cca0d81 1204 w = 0;
32874aea 1205 for (i = 0; i < 2; i++)
1206 w = (w << 8) + *p++;
1207 b = (w + 7) / 8; /* bits -> bytes */
7cca0d81 1208
0016d70b 1209 if (len < b+2)
1210 return -1;
1211
32874aea 1212 if (!result) /* just return length */
1213 return b + 2;
a52f067e 1214
3709bfe9 1215 *result = bignum_from_bytes(p, b);
7cca0d81 1216
3709bfe9 1217 return p + b - data;
7cca0d81 1218}
5c58ad2d 1219
1220/*
2e85c969 1221 * Return the bit count of a bignum, for SSH-1 encoding.
5c58ad2d 1222 */
32874aea 1223int bignum_bitcount(Bignum bn)
1224{
a3412f52 1225 int bitcount = bn[0] * BIGNUM_INT_BITS - 1;
32874aea 1226 while (bitcount >= 0
a3412f52 1227 && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;
5c58ad2d 1228 return bitcount + 1;
1229}
1230
1231/*
2e85c969 1232 * Return the byte length of a bignum when SSH-1 encoded.
5c58ad2d 1233 */
32874aea 1234int ssh1_bignum_length(Bignum bn)
1235{
1236 return 2 + (bignum_bitcount(bn) + 7) / 8;
ddecd643 1237}
1238
1239/*
2e85c969 1240 * Return the byte length of a bignum when SSH-2 encoded.
ddecd643 1241 */
32874aea 1242int ssh2_bignum_length(Bignum bn)
1243{
1244 return 4 + (bignum_bitcount(bn) + 8) / 8;
5c58ad2d 1245}
1246
1247/*
1248 * Return a byte from a bignum; 0 is least significant, etc.
1249 */
32874aea 1250int bignum_byte(Bignum bn, int i)
1251{
62ddb51e 1252 if (i >= (int)(BIGNUM_INT_BYTES * bn[0]))
32874aea 1253 return 0; /* beyond the end */
5c58ad2d 1254 else
a3412f52 1255 return (bn[i / BIGNUM_INT_BYTES + 1] >>
1256 ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;
5c58ad2d 1257}
1258
1259/*
9400cf6f 1260 * Return a bit from a bignum; 0 is least significant, etc.
1261 */
32874aea 1262int bignum_bit(Bignum bn, int i)
1263{
62ddb51e 1264 if (i >= (int)(BIGNUM_INT_BITS * bn[0]))
32874aea 1265 return 0; /* beyond the end */
9400cf6f 1266 else
a3412f52 1267 return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;
9400cf6f 1268}
1269
1270/*
1271 * Set a bit in a bignum; 0 is least significant, etc.
1272 */
32874aea 1273void bignum_set_bit(Bignum bn, int bitnum, int value)
1274{
62ddb51e 1275 if (bitnum >= (int)(BIGNUM_INT_BITS * bn[0]))
32874aea 1276 abort(); /* beyond the end */
9400cf6f 1277 else {
a3412f52 1278 int v = bitnum / BIGNUM_INT_BITS + 1;
1279 int mask = 1 << (bitnum % BIGNUM_INT_BITS);
32874aea 1280 if (value)
1281 bn[v] |= mask;
1282 else
1283 bn[v] &= ~mask;
9400cf6f 1284 }
1285}
1286
1287/*
2e85c969 1288 * Write a SSH-1-format bignum into a buffer. It is assumed the
5c58ad2d 1289 * buffer is big enough. Returns the number of bytes used.
1290 */
32874aea 1291int ssh1_write_bignum(void *data, Bignum bn)
1292{
5c58ad2d 1293 unsigned char *p = data;
1294 int len = ssh1_bignum_length(bn);
1295 int i;
ddecd643 1296 int bitc = bignum_bitcount(bn);
5c58ad2d 1297
1298 *p++ = (bitc >> 8) & 0xFF;
32874aea 1299 *p++ = (bitc) & 0xFF;
1300 for (i = len - 2; i--;)
1301 *p++ = bignum_byte(bn, i);
5c58ad2d 1302 return len;
1303}
9400cf6f 1304
1305/*
1306 * Compare two bignums. Returns like strcmp.
1307 */
32874aea 1308int bignum_cmp(Bignum a, Bignum b)
1309{
9400cf6f 1310 int amax = a[0], bmax = b[0];
1311 int i = (amax > bmax ? amax : bmax);
1312 while (i) {
a3412f52 1313 BignumInt aval = (i > amax ? 0 : a[i]);
1314 BignumInt bval = (i > bmax ? 0 : b[i]);
32874aea 1315 if (aval < bval)
1316 return -1;
1317 if (aval > bval)
1318 return +1;
1319 i--;
9400cf6f 1320 }
1321 return 0;
1322}
1323
1324/*
1325 * Right-shift one bignum to form another.
1326 */
32874aea 1327Bignum bignum_rshift(Bignum a, int shift)
1328{
9400cf6f 1329 Bignum ret;
1330 int i, shiftw, shiftb, shiftbb, bits;
a3412f52 1331 BignumInt ai, ai1;
9400cf6f 1332
ddecd643 1333 bits = bignum_bitcount(a) - shift;
a3412f52 1334 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
9400cf6f 1335
1336 if (ret) {
a3412f52 1337 shiftw = shift / BIGNUM_INT_BITS;
1338 shiftb = shift % BIGNUM_INT_BITS;
1339 shiftbb = BIGNUM_INT_BITS - shiftb;
32874aea 1340
1341 ai1 = a[shiftw + 1];
62ddb51e 1342 for (i = 1; i <= (int)ret[0]; i++) {
32874aea 1343 ai = ai1;
62ddb51e 1344 ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);
a3412f52 1345 ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;
32874aea 1346 }
9400cf6f 1347 }
1348
1349 return ret;
1350}
1351
1352/*
1353 * Non-modular multiplication and addition.
1354 */
32874aea 1355Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
1356{
9400cf6f 1357 int alen = a[0], blen = b[0];
1358 int mlen = (alen > blen ? alen : blen);
1359 int rlen, i, maxspot;
5a502a19 1360 int wslen;
a3412f52 1361 BignumInt *workspace;
9400cf6f 1362 Bignum ret;
1363
5a502a19 1364 /* mlen space for a, mlen space for b, 2*mlen for result,
1365 * plus scratch space for multiplication */
1366 wslen = mlen * 4 + mul_compute_scratch(mlen);
1367 workspace = snewn(wslen, BignumInt);
9400cf6f 1368 for (i = 0; i < mlen; i++) {
62ddb51e 1369 workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);
1370 workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);
9400cf6f 1371 }
1372
32874aea 1373 internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
5a502a19 1374 workspace + 2 * mlen, mlen, workspace + 4 * mlen);
9400cf6f 1375
1376 /* now just copy the result back */
1377 rlen = alen + blen + 1;
62ddb51e 1378 if (addend && rlen <= (int)addend[0])
32874aea 1379 rlen = addend[0] + 1;
9400cf6f 1380 ret = newbn(rlen);
1381 maxspot = 0;
62ddb51e 1382 for (i = 1; i <= (int)ret[0]; i++) {
32874aea 1383 ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
1384 if (ret[i] != 0)
1385 maxspot = i;
9400cf6f 1386 }
1387 ret[0] = maxspot;
1388
1389 /* now add in the addend, if any */
1390 if (addend) {
a3412f52 1391 BignumDblInt carry = 0;
32874aea 1392 for (i = 1; i <= rlen; i++) {
62ddb51e 1393 carry += (i <= (int)ret[0] ? ret[i] : 0);
1394 carry += (i <= (int)addend[0] ? addend[i] : 0);
a3412f52 1395 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1396 carry >>= BIGNUM_INT_BITS;
32874aea 1397 if (ret[i] != 0 && i > maxspot)
1398 maxspot = i;
1399 }
9400cf6f 1400 }
1401 ret[0] = maxspot;
1402
16430000 1403 smemclr(workspace, wslen * sizeof(*workspace));
c523f55f 1404 sfree(workspace);
9400cf6f 1405 return ret;
1406}
1407
1408/*
1409 * Non-modular multiplication.
1410 */
32874aea 1411Bignum bigmul(Bignum a, Bignum b)
1412{
9400cf6f 1413 return bigmuladd(a, b, NULL);
1414}
1415
1416/*
d737853b 1417 * Simple addition.
1418 */
1419Bignum bigadd(Bignum a, Bignum b)
1420{
1421 int alen = a[0], blen = b[0];
1422 int rlen = (alen > blen ? alen : blen) + 1;
1423 int i, maxspot;
1424 Bignum ret;
1425 BignumDblInt carry;
1426
1427 ret = newbn(rlen);
1428
1429 carry = 0;
1430 maxspot = 0;
1431 for (i = 1; i <= rlen; i++) {
1432 carry += (i <= (int)a[0] ? a[i] : 0);
1433 carry += (i <= (int)b[0] ? b[i] : 0);
1434 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1435 carry >>= BIGNUM_INT_BITS;
1436 if (ret[i] != 0 && i > maxspot)
1437 maxspot = i;
1438 }
1439 ret[0] = maxspot;
1440
1441 return ret;
1442}
1443
1444/*
1445 * Subtraction. Returns a-b, or NULL if the result would come out
1446 * negative (recall that this entire bignum module only handles
1447 * positive numbers).
1448 */
1449Bignum bigsub(Bignum a, Bignum b)
1450{
1451 int alen = a[0], blen = b[0];
1452 int rlen = (alen > blen ? alen : blen);
1453 int i, maxspot;
1454 Bignum ret;
1455 BignumDblInt carry;
1456
1457 ret = newbn(rlen);
1458
1459 carry = 1;
1460 maxspot = 0;
1461 for (i = 1; i <= rlen; i++) {
1462 carry += (i <= (int)a[0] ? a[i] : 0);
1463 carry += (i <= (int)b[0] ? b[i] ^ BIGNUM_INT_MASK : BIGNUM_INT_MASK);
1464 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1465 carry >>= BIGNUM_INT_BITS;
1466 if (ret[i] != 0 && i > maxspot)
1467 maxspot = i;
1468 }
1469 ret[0] = maxspot;
1470
1471 if (!carry) {
1472 freebn(ret);
1473 return NULL;
1474 }
1475
1476 return ret;
1477}
1478
1479/*
3709bfe9 1480 * Create a bignum which is the bitmask covering another one. That
1481 * is, the smallest integer which is >= N and is also one less than
1482 * a power of two.
1483 */
32874aea 1484Bignum bignum_bitmask(Bignum n)
1485{
3709bfe9 1486 Bignum ret = copybn(n);
1487 int i;
a3412f52 1488 BignumInt j;
3709bfe9 1489
1490 i = ret[0];
1491 while (n[i] == 0 && i > 0)
32874aea 1492 i--;
3709bfe9 1493 if (i <= 0)
32874aea 1494 return ret; /* input was zero */
3709bfe9 1495 j = 1;
1496 while (j < n[i])
32874aea 1497 j = 2 * j + 1;
3709bfe9 1498 ret[i] = j;
1499 while (--i > 0)
a3412f52 1500 ret[i] = BIGNUM_INT_MASK;
3709bfe9 1501 return ret;
1502}
1503
1504/*
5c72ca61 1505 * Convert a (max 32-bit) long into a bignum.
9400cf6f 1506 */
a3412f52 1507Bignum bignum_from_long(unsigned long nn)
32874aea 1508{
9400cf6f 1509 Bignum ret;
a3412f52 1510 BignumDblInt n = nn;
9400cf6f 1511
5c72ca61 1512 ret = newbn(3);
a3412f52 1513 ret[1] = (BignumInt)(n & BIGNUM_INT_MASK);
1514 ret[2] = (BignumInt)((n >> BIGNUM_INT_BITS) & BIGNUM_INT_MASK);
5c72ca61 1515 ret[3] = 0;
1516 ret[0] = (ret[2] ? 2 : 1);
32874aea 1517 return ret;
9400cf6f 1518}
1519
1520/*
1521 * Add a long to a bignum.
1522 */
a3412f52 1523Bignum bignum_add_long(Bignum number, unsigned long addendx)
32874aea 1524{
1525 Bignum ret = newbn(number[0] + 1);
9400cf6f 1526 int i, maxspot = 0;
a3412f52 1527 BignumDblInt carry = 0, addend = addendx;
9400cf6f 1528
62ddb51e 1529 for (i = 1; i <= (int)ret[0]; i++) {
a3412f52 1530 carry += addend & BIGNUM_INT_MASK;
62ddb51e 1531 carry += (i <= (int)number[0] ? number[i] : 0);
a3412f52 1532 addend >>= BIGNUM_INT_BITS;
1533 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1534 carry >>= BIGNUM_INT_BITS;
32874aea 1535 if (ret[i] != 0)
1536 maxspot = i;
9400cf6f 1537 }
1538 ret[0] = maxspot;
1539 return ret;
1540}
1541
1542/*
1543 * Compute the residue of a bignum, modulo a (max 16-bit) short.
1544 */
32874aea 1545unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
1546{
a3412f52 1547 BignumDblInt mod, r;
9400cf6f 1548 int i;
1549
1550 r = 0;
1551 mod = modulus;
1552 for (i = number[0]; i > 0; i--)
736cc6d1 1553 r = (r * (BIGNUM_TOP_BIT % mod) * 2 + number[i] % mod) % mod;
6e522441 1554 return (unsigned short) r;
9400cf6f 1555}
1556
a3412f52 1557#ifdef DEBUG
32874aea 1558void diagbn(char *prefix, Bignum md)
1559{
9400cf6f 1560 int i, nibbles, morenibbles;
1561 static const char hex[] = "0123456789ABCDEF";
1562
5c72ca61 1563 debug(("%s0x", prefix ? prefix : ""));
9400cf6f 1564
32874aea 1565 nibbles = (3 + bignum_bitcount(md)) / 4;
1566 if (nibbles < 1)
1567 nibbles = 1;
1568 morenibbles = 4 * md[0] - nibbles;
1569 for (i = 0; i < morenibbles; i++)
5c72ca61 1570 debug(("-"));
32874aea 1571 for (i = nibbles; i--;)
5c72ca61 1572 debug(("%c",
1573 hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
9400cf6f 1574
32874aea 1575 if (prefix)
5c72ca61 1576 debug(("\n"));
1577}
f28753ab 1578#endif
5c72ca61 1579
1580/*
1581 * Simple division.
1582 */
1583Bignum bigdiv(Bignum a, Bignum b)
1584{
1585 Bignum q = newbn(a[0]);
1586 bigdivmod(a, b, NULL, q);
1587 return q;
1588}
1589
1590/*
1591 * Simple remainder.
1592 */
1593Bignum bigmod(Bignum a, Bignum b)
1594{
1595 Bignum r = newbn(b[0]);
1596 bigdivmod(a, b, r, NULL);
1597 return r;
9400cf6f 1598}
1599
1600/*
1601 * Greatest common divisor.
1602 */
32874aea 1603Bignum biggcd(Bignum av, Bignum bv)
1604{
9400cf6f 1605 Bignum a = copybn(av);
1606 Bignum b = copybn(bv);
1607
9400cf6f 1608 while (bignum_cmp(b, Zero) != 0) {
32874aea 1609 Bignum t = newbn(b[0]);
5c72ca61 1610 bigdivmod(a, b, t, NULL);
32874aea 1611 while (t[0] > 1 && t[t[0]] == 0)
1612 t[0]--;
1613 freebn(a);
1614 a = b;
1615 b = t;
9400cf6f 1616 }
1617
1618 freebn(b);
1619 return a;
1620}
1621
1622/*
1623 * Modular inverse, using Euclid's extended algorithm.
1624 */
32874aea 1625Bignum modinv(Bignum number, Bignum modulus)
1626{
9400cf6f 1627 Bignum a = copybn(modulus);
1628 Bignum b = copybn(number);
1629 Bignum xp = copybn(Zero);
1630 Bignum x = copybn(One);
1631 int sign = +1;
1632
8bd9144b 1633 assert(number[number[0]] != 0);
1634 assert(modulus[modulus[0]] != 0);
1635
9400cf6f 1636 while (bignum_cmp(b, One) != 0) {
32874aea 1637 Bignum t = newbn(b[0]);
1638 Bignum q = newbn(a[0]);
5c72ca61 1639 bigdivmod(a, b, t, q);
32874aea 1640 while (t[0] > 1 && t[t[0]] == 0)
1641 t[0]--;
1642 freebn(a);
1643 a = b;
1644 b = t;
1645 t = xp;
1646 xp = x;
1647 x = bigmuladd(q, xp, t);
1648 sign = -sign;
1649 freebn(t);
75374b2f 1650 freebn(q);
9400cf6f 1651 }
1652
1653 freebn(b);
1654 freebn(a);
1655 freebn(xp);
1656
1657 /* now we know that sign * x == 1, and that x < modulus */
1658 if (sign < 0) {
32874aea 1659 /* set a new x to be modulus - x */
1660 Bignum newx = newbn(modulus[0]);
a3412f52 1661 BignumInt carry = 0;
32874aea 1662 int maxspot = 1;
1663 int i;
1664
62ddb51e 1665 for (i = 1; i <= (int)newx[0]; i++) {
1666 BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);
1667 BignumInt bword = (i <= (int)x[0] ? x[i] : 0);
32874aea 1668 newx[i] = aword - bword - carry;
1669 bword = ~bword;
1670 carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
1671 if (newx[i] != 0)
1672 maxspot = i;
1673 }
1674 newx[0] = maxspot;
1675 freebn(x);
1676 x = newx;
9400cf6f 1677 }
1678
1679 /* and return. */
1680 return x;
1681}
6e522441 1682
1683/*
1684 * Render a bignum into decimal. Return a malloced string holding
1685 * the decimal representation.
1686 */
32874aea 1687char *bignum_decimal(Bignum x)
1688{
6e522441 1689 int ndigits, ndigit;
1690 int i, iszero;
a3412f52 1691 BignumDblInt carry;
6e522441 1692 char *ret;
a3412f52 1693 BignumInt *workspace;
6e522441 1694
1695 /*
1696 * First, estimate the number of digits. Since log(10)/log(2)
1697 * is just greater than 93/28 (the joys of continued fraction
1698 * approximations...) we know that for every 93 bits, we need
1699 * at most 28 digits. This will tell us how much to malloc.
1700 *
1701 * Formally: if x has i bits, that means x is strictly less
1702 * than 2^i. Since 2 is less than 10^(28/93), this is less than
1703 * 10^(28i/93). We need an integer power of ten, so we must
1704 * round up (rounding down might make it less than x again).
1705 * Therefore if we multiply the bit count by 28/93, rounding
1706 * up, we will have enough digits.
74c79ce8 1707 *
1708 * i=0 (i.e., x=0) is an irritating special case.
6e522441 1709 */
ddecd643 1710 i = bignum_bitcount(x);
74c79ce8 1711 if (!i)
1712 ndigits = 1; /* x = 0 */
1713 else
1714 ndigits = (28 * i + 92) / 93; /* multiply by 28/93 and round up */
32874aea 1715 ndigits++; /* allow for trailing \0 */
3d88e64d 1716 ret = snewn(ndigits, char);
6e522441 1717
1718 /*
1719 * Now allocate some workspace to hold the binary form as we
1720 * repeatedly divide it by ten. Initialise this to the
1721 * big-endian form of the number.
1722 */
a3412f52 1723 workspace = snewn(x[0], BignumInt);
62ddb51e 1724 for (i = 0; i < (int)x[0]; i++)
32874aea 1725 workspace[i] = x[x[0] - i];
6e522441 1726
1727 /*
1728 * Next, write the decimal number starting with the last digit.
1729 * We use ordinary short division, dividing 10 into the
1730 * workspace.
1731 */
32874aea 1732 ndigit = ndigits - 1;
6e522441 1733 ret[ndigit] = '\0';
1734 do {
32874aea 1735 iszero = 1;
1736 carry = 0;
62ddb51e 1737 for (i = 0; i < (int)x[0]; i++) {
a3412f52 1738 carry = (carry << BIGNUM_INT_BITS) + workspace[i];
1739 workspace[i] = (BignumInt) (carry / 10);
32874aea 1740 if (workspace[i])
1741 iszero = 0;
1742 carry %= 10;
1743 }
1744 ret[--ndigit] = (char) (carry + '0');
6e522441 1745 } while (!iszero);
1746
1747 /*
1748 * There's a chance we've fallen short of the start of the
1749 * string. Correct if so.
1750 */
1751 if (ndigit > 0)
32874aea 1752 memmove(ret, ret + ndigit, ndigits - ndigit);
6e522441 1753
1754 /*
1755 * Done.
1756 */
16430000 1757 smemclr(workspace, x[0] * sizeof(*workspace));
c523f55f 1758 sfree(workspace);
6e522441 1759 return ret;
1760}
f3c29e34 1761
1762#ifdef TESTBN
1763
1764#include <stdio.h>
1765#include <stdlib.h>
1766#include <ctype.h>
1767
1768/*
4800a5e5 1769 * gcc -Wall -g -O0 -DTESTBN -o testbn sshbn.c misc.c conf.c tree234.c unix/uxmisc.c -I. -I unix -I charset
f84f1e46 1770 *
1771 * Then feed to this program's standard input the output of
1772 * testdata/bignum.py .
f3c29e34 1773 */
1774
1775void modalfatalbox(char *p, ...)
1776{
1777 va_list ap;
1778 fprintf(stderr, "FATAL ERROR: ");
1779 va_start(ap, p);
1780 vfprintf(stderr, p, ap);
1781 va_end(ap);
1782 fputc('\n', stderr);
1783 exit(1);
1784}
1785
1786#define fromxdigit(c) ( (c)>'9' ? ((c)&0xDF) - 'A' + 10 : (c) - '0' )
1787
1788int main(int argc, char **argv)
1789{
1790 char *buf;
1791 int line = 0;
1792 int passes = 0, fails = 0;
1793
1794 while ((buf = fgetline(stdin)) != NULL) {
1795 int maxlen = strlen(buf);
1796 unsigned char *data = snewn(maxlen, unsigned char);
f84f1e46 1797 unsigned char *ptrs[5], *q;
f3c29e34 1798 int ptrnum;
1799 char *bufp = buf;
1800
1801 line++;
1802
1803 q = data;
1804 ptrnum = 0;
1805
f84f1e46 1806 while (*bufp && !isspace((unsigned char)*bufp))
1807 bufp++;
1808 if (bufp)
1809 *bufp++ = '\0';
1810
f3c29e34 1811 while (*bufp) {
1812 char *start, *end;
1813 int i;
1814
1815 while (*bufp && !isxdigit((unsigned char)*bufp))
1816 bufp++;
1817 start = bufp;
1818
1819 if (!*bufp)
1820 break;
1821
1822 while (*bufp && isxdigit((unsigned char)*bufp))
1823 bufp++;
1824 end = bufp;
1825
1826 if (ptrnum >= lenof(ptrs))
1827 break;
1828 ptrs[ptrnum++] = q;
1829
1830 for (i = -((end - start) & 1); i < end-start; i += 2) {
1831 unsigned char val = (i < 0 ? 0 : fromxdigit(start[i]));
1832 val = val * 16 + fromxdigit(start[i+1]);
1833 *q++ = val;
1834 }
1835
1836 ptrs[ptrnum] = q;
1837 }
1838
f84f1e46 1839 if (!strcmp(buf, "mul")) {
1840 Bignum a, b, c, p;
1841
1842 if (ptrnum != 3) {
f6939e2b 1843 printf("%d: mul with %d parameters, expected 3\n", line, ptrnum);
f84f1e46 1844 exit(1);
1845 }
1846 a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1847 b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1848 c = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1849 p = bigmul(a, b);
f3c29e34 1850
1851 if (bignum_cmp(c, p) == 0) {
1852 passes++;
1853 } else {
1854 char *as = bignum_decimal(a);
1855 char *bs = bignum_decimal(b);
1856 char *cs = bignum_decimal(c);
1857 char *ps = bignum_decimal(p);
1858
1859 printf("%d: fail: %s * %s gave %s expected %s\n",
1860 line, as, bs, ps, cs);
1861 fails++;
1862
1863 sfree(as);
1864 sfree(bs);
1865 sfree(cs);
1866 sfree(ps);
1867 }
1868 freebn(a);
1869 freebn(b);
1870 freebn(c);
1871 freebn(p);
5064e5e6 1872 } else if (!strcmp(buf, "modmul")) {
1873 Bignum a, b, m, c, p;
1874
1875 if (ptrnum != 4) {
1876 printf("%d: modmul with %d parameters, expected 4\n",
1877 line, ptrnum);
1878 exit(1);
1879 }
1880 a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1881 b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1882 m = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1883 c = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);
1884 p = modmul(a, b, m);
1885
1886 if (bignum_cmp(c, p) == 0) {
1887 passes++;
1888 } else {
1889 char *as = bignum_decimal(a);
1890 char *bs = bignum_decimal(b);
1891 char *ms = bignum_decimal(m);
1892 char *cs = bignum_decimal(c);
1893 char *ps = bignum_decimal(p);
1894
1895 printf("%d: fail: %s * %s mod %s gave %s expected %s\n",
1896 line, as, bs, ms, ps, cs);
1897 fails++;
1898
1899 sfree(as);
1900 sfree(bs);
1901 sfree(ms);
1902 sfree(cs);
1903 sfree(ps);
1904 }
1905 freebn(a);
1906 freebn(b);
1907 freebn(m);
1908 freebn(c);
1909 freebn(p);
f84f1e46 1910 } else if (!strcmp(buf, "pow")) {
1911 Bignum base, expt, modulus, expected, answer;
1912
1913 if (ptrnum != 4) {
f6939e2b 1914 printf("%d: mul with %d parameters, expected 4\n", line, ptrnum);
f84f1e46 1915 exit(1);
1916 }
1917
1918 base = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1919 expt = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1920 modulus = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1921 expected = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);
1922 answer = modpow(base, expt, modulus);
1923
1924 if (bignum_cmp(expected, answer) == 0) {
1925 passes++;
1926 } else {
1927 char *as = bignum_decimal(base);
1928 char *bs = bignum_decimal(expt);
1929 char *cs = bignum_decimal(modulus);
1930 char *ds = bignum_decimal(answer);
1931 char *ps = bignum_decimal(expected);
1932
1933 printf("%d: fail: %s ^ %s mod %s gave %s expected %s\n",
1934 line, as, bs, cs, ds, ps);
1935 fails++;
1936
1937 sfree(as);
1938 sfree(bs);
1939 sfree(cs);
1940 sfree(ds);
1941 sfree(ps);
1942 }
1943 freebn(base);
1944 freebn(expt);
1945 freebn(modulus);
1946 freebn(expected);
1947 freebn(answer);
1948 } else {
1949 printf("%d: unrecognised test keyword: '%s'\n", line, buf);
1950 exit(1);
f3c29e34 1951 }
f84f1e46 1952
f3c29e34 1953 sfree(buf);
1954 sfree(data);
1955 }
1956
1957 printf("passed %d failed %d total %d\n", passes, fails, passes+fails);
1958 return fails != 0;
1959}
1960
1961#endif