Initialise 'psa' to NULL on every code path in the Pageant client
[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];
9400cf6f 627 if (mlen > 1)
32874aea 628 m1 = m[1];
9400cf6f 629 else
32874aea 630 m1 = 0;
e5574168 631
32874aea 632 for (i = 0; i <= alen - mlen; i++) {
a3412f52 633 BignumDblInt t;
9400cf6f 634 unsigned int q, r, c, ai1;
e5574168 635
636 if (i == 0) {
637 h = 0;
638 } else {
32874aea 639 h = a[i - 1];
640 a[i - 1] = 0;
e5574168 641 }
642
32874aea 643 if (i == alen - 1)
644 ai1 = 0;
645 else
646 ai1 = a[i + 1];
9400cf6f 647
e5574168 648 /* Find q = h:a[i] / m0 */
62ef3d44 649 if (h >= m0) {
650 /*
651 * Special case.
652 *
653 * To illustrate it, suppose a BignumInt is 8 bits, and
654 * we are dividing (say) A1:23:45:67 by A1:B2:C3. Then
655 * our initial division will be 0xA123 / 0xA1, which
656 * will give a quotient of 0x100 and a divide overflow.
657 * However, the invariants in this division algorithm
658 * are not violated, since the full number A1:23:... is
659 * _less_ than the quotient prefix A1:B2:... and so the
660 * following correction loop would have sorted it out.
661 *
662 * In this situation we set q to be the largest
663 * quotient we _can_ stomach (0xFF, of course).
664 */
665 q = BIGNUM_INT_MASK;
666 } else {
819a22b3 667 /* Macro doesn't want an array subscript expression passed
668 * into it (see definition), so use a temporary. */
669 BignumInt tmplo = a[i];
670 DIVMOD_WORD(q, r, h, tmplo, m0);
62ef3d44 671
672 /* Refine our estimate of q by looking at
673 h:a[i]:a[i+1] / m0:m1 */
674 t = MUL_WORD(m1, q);
675 if (t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) {
676 q--;
677 t -= m1;
678 r = (r + m0) & BIGNUM_INT_MASK; /* overflow? */
679 if (r >= (BignumDblInt) m0 &&
680 t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) q--;
681 }
e5574168 682 }
683
9400cf6f 684 /* Subtract q * m from a[i...] */
e5574168 685 c = 0;
9400cf6f 686 for (k = mlen - 1; k >= 0; k--) {
a47e8bba 687 t = MUL_WORD(q, m[k]);
e5574168 688 t += c;
62ddb51e 689 c = (unsigned)(t >> BIGNUM_INT_BITS);
a3412f52 690 if ((BignumInt) t > a[i + k])
32874aea 691 c++;
a3412f52 692 a[i + k] -= (BignumInt) t;
e5574168 693 }
694
695 /* Add back m in case of borrow */
696 if (c != h) {
697 t = 0;
9400cf6f 698 for (k = mlen - 1; k >= 0; k--) {
e5574168 699 t += m[k];
32874aea 700 t += a[i + k];
a3412f52 701 a[i + k] = (BignumInt) t;
702 t = t >> BIGNUM_INT_BITS;
e5574168 703 }
32874aea 704 q--;
e5574168 705 }
32874aea 706 if (quot)
a3412f52 707 internal_add_shifted(quot, q, qshift + BIGNUM_INT_BITS * (alen - mlen - i));
e5574168 708 }
709}
710
711/*
09095ac5 712 * Compute (base ^ exp) % mod, the pedestrian way.
e5574168 713 */
09095ac5 714Bignum modpow_simple(Bignum base_in, Bignum exp, Bignum mod)
e5574168 715{
5a502a19 716 BignumInt *a, *b, *n, *m, *scratch;
09095ac5 717 int mshift;
5a502a19 718 int mlen, scratchlen, i, j;
09095ac5 719 Bignum base, result;
ed953b91 720
721 /*
722 * The most significant word of mod needs to be non-zero. It
723 * should already be, but let's make sure.
724 */
725 assert(mod[mod[0]] != 0);
726
727 /*
728 * Make sure the base is smaller than the modulus, by reducing
729 * it modulo the modulus if not.
730 */
731 base = bigmod(base_in, mod);
e5574168 732
09095ac5 733 /* Allocate m of size mlen, copy mod to m */
734 /* We use big endian internally */
735 mlen = mod[0];
736 m = snewn(mlen, BignumInt);
737 for (j = 0; j < mlen; j++)
738 m[j] = mod[mod[0] - j];
739
740 /* Shift m left to make msb bit set */
741 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
742 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
743 break;
744 if (mshift) {
745 for (i = 0; i < mlen - 1; i++)
746 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
747 m[mlen - 1] = m[mlen - 1] << mshift;
748 }
749
750 /* Allocate n of size mlen, copy base to n */
751 n = snewn(mlen, BignumInt);
752 i = mlen - base[0];
753 for (j = 0; j < i; j++)
754 n[j] = 0;
755 for (j = 0; j < (int)base[0]; j++)
756 n[i + j] = base[base[0] - j];
757
758 /* Allocate a and b of size 2*mlen. Set a = 1 */
759 a = snewn(2 * mlen, BignumInt);
760 b = snewn(2 * mlen, BignumInt);
761 for (i = 0; i < 2 * mlen; i++)
762 a[i] = 0;
763 a[2 * mlen - 1] = 1;
764
5a502a19 765 /* Scratch space for multiplies */
766 scratchlen = mul_compute_scratch(mlen);
767 scratch = snewn(scratchlen, BignumInt);
768
09095ac5 769 /* Skip leading zero bits of exp. */
770 i = 0;
771 j = BIGNUM_INT_BITS-1;
772 while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
773 j--;
774 if (j < 0) {
775 i++;
776 j = BIGNUM_INT_BITS-1;
777 }
778 }
779
780 /* Main computation */
781 while (i < (int)exp[0]) {
782 while (j >= 0) {
5a502a19 783 internal_mul(a + mlen, a + mlen, b, mlen, scratch);
09095ac5 784 internal_mod(b, mlen * 2, m, mlen, NULL, 0);
785 if ((exp[exp[0] - i] & (1 << j)) != 0) {
5a502a19 786 internal_mul(b + mlen, n, a, mlen, scratch);
09095ac5 787 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
788 } else {
789 BignumInt *t;
790 t = a;
791 a = b;
792 b = t;
793 }
794 j--;
795 }
796 i++;
797 j = BIGNUM_INT_BITS-1;
798 }
799
800 /* Fixup result in case the modulus was shifted */
801 if (mshift) {
802 for (i = mlen - 1; i < 2 * mlen - 1; i++)
803 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
804 a[2 * mlen - 1] = a[2 * mlen - 1] << mshift;
805 internal_mod(a, mlen * 2, m, mlen, NULL, 0);
806 for (i = 2 * mlen - 1; i >= mlen; i--)
807 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
808 }
809
810 /* Copy result to buffer */
811 result = newbn(mod[0]);
812 for (i = 0; i < mlen; i++)
813 result[result[0] - i] = a[i + mlen];
814 while (result[0] > 1 && result[result[0]] == 0)
815 result[0]--;
816
817 /* Free temporary arrays */
818 for (i = 0; i < 2 * mlen; i++)
819 a[i] = 0;
820 sfree(a);
5a502a19 821 for (i = 0; i < scratchlen; i++)
822 scratch[i] = 0;
823 sfree(scratch);
09095ac5 824 for (i = 0; i < 2 * mlen; i++)
825 b[i] = 0;
826 sfree(b);
827 for (i = 0; i < mlen; i++)
828 m[i] = 0;
829 sfree(m);
830 for (i = 0; i < mlen; i++)
831 n[i] = 0;
832 sfree(n);
833
834 freebn(base);
835
836 return result;
837}
838
839/*
840 * Compute (base ^ exp) % mod. Uses the Montgomery multiplication
841 * technique where possible, falling back to modpow_simple otherwise.
842 */
843Bignum modpow(Bignum base_in, Bignum exp, Bignum mod)
844{
5a502a19 845 BignumInt *a, *b, *x, *n, *mninv, *scratch;
846 int len, scratchlen, i, j;
09095ac5 847 Bignum base, base2, r, rn, inv, result;
848
849 /*
850 * The most significant word of mod needs to be non-zero. It
851 * should already be, but let's make sure.
852 */
853 assert(mod[mod[0]] != 0);
854
132c534f 855 /*
856 * mod had better be odd, or we can't do Montgomery multiplication
857 * using a power of two at all.
858 */
09095ac5 859 if (!(mod[1] & 1))
860 return modpow_simple(base_in, exp, mod);
861
862 /*
863 * Make sure the base is smaller than the modulus, by reducing
864 * it modulo the modulus if not.
865 */
866 base = bigmod(base_in, mod);
e5574168 867
132c534f 868 /*
869 * Compute the inverse of n mod r, for monty_reduce. (In fact we
870 * want the inverse of _minus_ n mod r, but we'll sort that out
871 * below.)
872 */
873 len = mod[0];
874 r = bn_power_2(BIGNUM_INT_BITS * len);
875 inv = modinv(mod, r);
e5574168 876
132c534f 877 /*
878 * Multiply the base by r mod n, to get it into Montgomery
879 * representation.
880 */
881 base2 = modmul(base, r, mod);
882 freebn(base);
883 base = base2;
884
885 rn = bigmod(r, mod); /* r mod n, i.e. Montgomerified 1 */
886
887 freebn(r); /* won't need this any more */
888
889 /*
890 * Set up internal arrays of the right lengths, in big-endian
891 * format, containing the base, the modulus, and the modulus's
892 * inverse.
893 */
894 n = snewn(len, BignumInt);
895 for (j = 0; j < len; j++)
896 n[len - 1 - j] = mod[j + 1];
897
898 mninv = snewn(len, BignumInt);
899 for (j = 0; j < len; j++)
08b5c9a2 900 mninv[len - 1 - j] = (j < (int)inv[0] ? inv[j + 1] : 0);
132c534f 901 freebn(inv); /* we don't need this copy of it any more */
902 /* Now negate mninv mod r, so it's the inverse of -n rather than +n. */
903 x = snewn(len, BignumInt);
904 for (j = 0; j < len; j++)
905 x[j] = 0;
906 internal_sub(x, mninv, mninv, len);
907
908 /* x = snewn(len, BignumInt); */ /* already done above */
909 for (j = 0; j < len; j++)
08b5c9a2 910 x[len - 1 - j] = (j < (int)base[0] ? base[j + 1] : 0);
132c534f 911 freebn(base); /* we don't need this copy of it any more */
912
913 a = snewn(2*len, BignumInt);
914 b = snewn(2*len, BignumInt);
915 for (j = 0; j < len; j++)
08b5c9a2 916 a[2*len - 1 - j] = (j < (int)rn[0] ? rn[j + 1] : 0);
132c534f 917 freebn(rn);
918
5a502a19 919 /* Scratch space for multiplies */
920 scratchlen = 3*len + mul_compute_scratch(len);
921 scratch = snewn(scratchlen, BignumInt);
e5574168 922
923 /* Skip leading zero bits of exp. */
32874aea 924 i = 0;
a3412f52 925 j = BIGNUM_INT_BITS-1;
62ddb51e 926 while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
e5574168 927 j--;
32874aea 928 if (j < 0) {
929 i++;
a3412f52 930 j = BIGNUM_INT_BITS-1;
32874aea 931 }
e5574168 932 }
933
934 /* Main computation */
62ddb51e 935 while (i < (int)exp[0]) {
e5574168 936 while (j >= 0) {
5a502a19 937 internal_mul(a + len, a + len, b, len, scratch);
938 monty_reduce(b, n, mninv, scratch, len);
e5574168 939 if ((exp[exp[0] - i] & (1 << j)) != 0) {
5a502a19 940 internal_mul(b + len, x, a, len, scratch);
941 monty_reduce(a, n, mninv, scratch, len);
e5574168 942 } else {
a3412f52 943 BignumInt *t;
32874aea 944 t = a;
945 a = b;
946 b = t;
e5574168 947 }
948 j--;
949 }
32874aea 950 i++;
a3412f52 951 j = BIGNUM_INT_BITS-1;
e5574168 952 }
953
132c534f 954 /*
955 * Final monty_reduce to get back from the adjusted Montgomery
956 * representation.
957 */
5a502a19 958 monty_reduce(a, n, mninv, scratch, len);
e5574168 959
960 /* Copy result to buffer */
59600f67 961 result = newbn(mod[0]);
132c534f 962 for (i = 0; i < len; i++)
963 result[result[0] - i] = a[i + len];
32874aea 964 while (result[0] > 1 && result[result[0]] == 0)
965 result[0]--;
e5574168 966
967 /* Free temporary arrays */
5a502a19 968 for (i = 0; i < scratchlen; i++)
969 scratch[i] = 0;
970 sfree(scratch);
132c534f 971 for (i = 0; i < 2 * len; i++)
32874aea 972 a[i] = 0;
973 sfree(a);
132c534f 974 for (i = 0; i < 2 * len; i++)
32874aea 975 b[i] = 0;
976 sfree(b);
132c534f 977 for (i = 0; i < len; i++)
978 mninv[i] = 0;
979 sfree(mninv);
980 for (i = 0; i < len; i++)
32874aea 981 n[i] = 0;
982 sfree(n);
132c534f 983 for (i = 0; i < len; i++)
984 x[i] = 0;
985 sfree(x);
ed953b91 986
59600f67 987 return result;
e5574168 988}
7cca0d81 989
990/*
991 * Compute (p * q) % mod.
992 * The most significant word of mod MUST be non-zero.
993 * We assume that the result array is the same size as the mod array.
994 */
59600f67 995Bignum modmul(Bignum p, Bignum q, Bignum mod)
7cca0d81 996{
5a502a19 997 BignumInt *a, *n, *m, *o, *scratch;
998 int mshift, scratchlen;
80b10571 999 int pqlen, mlen, rlen, i, j;
59600f67 1000 Bignum result;
7cca0d81 1001
1002 /* Allocate m of size mlen, copy mod to m */
1003 /* We use big endian internally */
1004 mlen = mod[0];
a3412f52 1005 m = snewn(mlen, BignumInt);
32874aea 1006 for (j = 0; j < mlen; j++)
1007 m[j] = mod[mod[0] - j];
7cca0d81 1008
1009 /* Shift m left to make msb bit set */
a3412f52 1010 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
1011 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
32874aea 1012 break;
7cca0d81 1013 if (mshift) {
1014 for (i = 0; i < mlen - 1; i++)
a3412f52 1015 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
32874aea 1016 m[mlen - 1] = m[mlen - 1] << mshift;
7cca0d81 1017 }
1018
1019 pqlen = (p[0] > q[0] ? p[0] : q[0]);
1020
1021 /* Allocate n of size pqlen, copy p to n */
a3412f52 1022 n = snewn(pqlen, BignumInt);
7cca0d81 1023 i = pqlen - p[0];
32874aea 1024 for (j = 0; j < i; j++)
1025 n[j] = 0;
62ddb51e 1026 for (j = 0; j < (int)p[0]; j++)
32874aea 1027 n[i + j] = p[p[0] - j];
7cca0d81 1028
1029 /* Allocate o of size pqlen, copy q to o */
a3412f52 1030 o = snewn(pqlen, BignumInt);
7cca0d81 1031 i = pqlen - q[0];
32874aea 1032 for (j = 0; j < i; j++)
1033 o[j] = 0;
62ddb51e 1034 for (j = 0; j < (int)q[0]; j++)
32874aea 1035 o[i + j] = q[q[0] - j];
7cca0d81 1036
1037 /* Allocate a of size 2*pqlen for result */
a3412f52 1038 a = snewn(2 * pqlen, BignumInt);
7cca0d81 1039
5a502a19 1040 /* Scratch space for multiplies */
1041 scratchlen = mul_compute_scratch(pqlen);
1042 scratch = snewn(scratchlen, BignumInt);
1043
7cca0d81 1044 /* Main computation */
5a502a19 1045 internal_mul(n, o, a, pqlen, scratch);
32874aea 1046 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
7cca0d81 1047
1048 /* Fixup result in case the modulus was shifted */
1049 if (mshift) {
32874aea 1050 for (i = 2 * pqlen - mlen - 1; i < 2 * pqlen - 1; i++)
a3412f52 1051 a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
32874aea 1052 a[2 * pqlen - 1] = a[2 * pqlen - 1] << mshift;
1053 internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
1054 for (i = 2 * pqlen - 1; i >= 2 * pqlen - mlen; i--)
a3412f52 1055 a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
7cca0d81 1056 }
1057
1058 /* Copy result to buffer */
32874aea 1059 rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
80b10571 1060 result = newbn(rlen);
1061 for (i = 0; i < rlen; i++)
32874aea 1062 result[result[0] - i] = a[i + 2 * pqlen - rlen];
1063 while (result[0] > 1 && result[result[0]] == 0)
1064 result[0]--;
7cca0d81 1065
1066 /* Free temporary arrays */
5a502a19 1067 for (i = 0; i < scratchlen; i++)
1068 scratch[i] = 0;
1069 sfree(scratch);
32874aea 1070 for (i = 0; i < 2 * pqlen; i++)
1071 a[i] = 0;
1072 sfree(a);
1073 for (i = 0; i < mlen; i++)
1074 m[i] = 0;
1075 sfree(m);
1076 for (i = 0; i < pqlen; i++)
1077 n[i] = 0;
1078 sfree(n);
1079 for (i = 0; i < pqlen; i++)
1080 o[i] = 0;
1081 sfree(o);
59600f67 1082
1083 return result;
7cca0d81 1084}
1085
1086/*
9400cf6f 1087 * Compute p % mod.
1088 * The most significant word of mod MUST be non-zero.
1089 * We assume that the result array is the same size as the mod array.
5c72ca61 1090 * We optionally write out a quotient if `quotient' is non-NULL.
1091 * We can avoid writing out the result if `result' is NULL.
9400cf6f 1092 */
f28753ab 1093static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
9400cf6f 1094{
a3412f52 1095 BignumInt *n, *m;
9400cf6f 1096 int mshift;
1097 int plen, mlen, i, j;
1098
1099 /* Allocate m of size mlen, copy mod to m */
1100 /* We use big endian internally */
1101 mlen = mod[0];
a3412f52 1102 m = snewn(mlen, BignumInt);
32874aea 1103 for (j = 0; j < mlen; j++)
1104 m[j] = mod[mod[0] - j];
9400cf6f 1105
1106 /* Shift m left to make msb bit set */
a3412f52 1107 for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
1108 if ((m[0] << mshift) & BIGNUM_TOP_BIT)
32874aea 1109 break;
9400cf6f 1110 if (mshift) {
1111 for (i = 0; i < mlen - 1; i++)
a3412f52 1112 m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
32874aea 1113 m[mlen - 1] = m[mlen - 1] << mshift;
9400cf6f 1114 }
1115
1116 plen = p[0];
1117 /* Ensure plen > mlen */
32874aea 1118 if (plen <= mlen)
1119 plen = mlen + 1;
9400cf6f 1120
1121 /* Allocate n of size plen, copy p to n */
a3412f52 1122 n = snewn(plen, BignumInt);
32874aea 1123 for (j = 0; j < plen; j++)
1124 n[j] = 0;
62ddb51e 1125 for (j = 1; j <= (int)p[0]; j++)
32874aea 1126 n[plen - j] = p[j];
9400cf6f 1127
1128 /* Main computation */
1129 internal_mod(n, plen, m, mlen, quotient, mshift);
1130
1131 /* Fixup result in case the modulus was shifted */
1132 if (mshift) {
1133 for (i = plen - mlen - 1; i < plen - 1; i++)
a3412f52 1134 n[i] = (n[i] << mshift) | (n[i + 1] >> (BIGNUM_INT_BITS - mshift));
32874aea 1135 n[plen - 1] = n[plen - 1] << mshift;
9400cf6f 1136 internal_mod(n, plen, m, mlen, quotient, 0);
1137 for (i = plen - 1; i >= plen - mlen; i--)
a3412f52 1138 n[i] = (n[i] >> mshift) | (n[i - 1] << (BIGNUM_INT_BITS - mshift));
9400cf6f 1139 }
1140
1141 /* Copy result to buffer */
5c72ca61 1142 if (result) {
62ddb51e 1143 for (i = 1; i <= (int)result[0]; i++) {
5c72ca61 1144 int j = plen - i;
1145 result[i] = j >= 0 ? n[j] : 0;
1146 }
9400cf6f 1147 }
1148
1149 /* Free temporary arrays */
32874aea 1150 for (i = 0; i < mlen; i++)
1151 m[i] = 0;
1152 sfree(m);
1153 for (i = 0; i < plen; i++)
1154 n[i] = 0;
1155 sfree(n);
9400cf6f 1156}
1157
1158/*
7cca0d81 1159 * Decrement a number.
1160 */
32874aea 1161void decbn(Bignum bn)
1162{
7cca0d81 1163 int i = 1;
62ddb51e 1164 while (i < (int)bn[0] && bn[i] == 0)
a3412f52 1165 bn[i++] = BIGNUM_INT_MASK;
7cca0d81 1166 bn[i]--;
1167}
1168
27cd7fc2 1169Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
32874aea 1170{
3709bfe9 1171 Bignum result;
1172 int w, i;
1173
a3412f52 1174 w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
3709bfe9 1175
1176 result = newbn(w);
32874aea 1177 for (i = 1; i <= w; i++)
1178 result[i] = 0;
1179 for (i = nbytes; i--;) {
1180 unsigned char byte = *data++;
a3412f52 1181 result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);
3709bfe9 1182 }
1183
32874aea 1184 while (result[0] > 1 && result[result[0]] == 0)
1185 result[0]--;
3709bfe9 1186 return result;
1187}
1188
7cca0d81 1189/*
2e85c969 1190 * Read an SSH-1-format bignum from a data buffer. Return the number
0016d70b 1191 * of bytes consumed, or -1 if there wasn't enough data.
7cca0d81 1192 */
0016d70b 1193int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)
32874aea 1194{
27cd7fc2 1195 const unsigned char *p = data;
7cca0d81 1196 int i;
1197 int w, b;
1198
0016d70b 1199 if (len < 2)
1200 return -1;
1201
7cca0d81 1202 w = 0;
32874aea 1203 for (i = 0; i < 2; i++)
1204 w = (w << 8) + *p++;
1205 b = (w + 7) / 8; /* bits -> bytes */
7cca0d81 1206
0016d70b 1207 if (len < b+2)
1208 return -1;
1209
32874aea 1210 if (!result) /* just return length */
1211 return b + 2;
a52f067e 1212
3709bfe9 1213 *result = bignum_from_bytes(p, b);
7cca0d81 1214
3709bfe9 1215 return p + b - data;
7cca0d81 1216}
5c58ad2d 1217
1218/*
2e85c969 1219 * Return the bit count of a bignum, for SSH-1 encoding.
5c58ad2d 1220 */
32874aea 1221int bignum_bitcount(Bignum bn)
1222{
a3412f52 1223 int bitcount = bn[0] * BIGNUM_INT_BITS - 1;
32874aea 1224 while (bitcount >= 0
a3412f52 1225 && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;
5c58ad2d 1226 return bitcount + 1;
1227}
1228
1229/*
2e85c969 1230 * Return the byte length of a bignum when SSH-1 encoded.
5c58ad2d 1231 */
32874aea 1232int ssh1_bignum_length(Bignum bn)
1233{
1234 return 2 + (bignum_bitcount(bn) + 7) / 8;
ddecd643 1235}
1236
1237/*
2e85c969 1238 * Return the byte length of a bignum when SSH-2 encoded.
ddecd643 1239 */
32874aea 1240int ssh2_bignum_length(Bignum bn)
1241{
1242 return 4 + (bignum_bitcount(bn) + 8) / 8;
5c58ad2d 1243}
1244
1245/*
1246 * Return a byte from a bignum; 0 is least significant, etc.
1247 */
32874aea 1248int bignum_byte(Bignum bn, int i)
1249{
62ddb51e 1250 if (i >= (int)(BIGNUM_INT_BYTES * bn[0]))
32874aea 1251 return 0; /* beyond the end */
5c58ad2d 1252 else
a3412f52 1253 return (bn[i / BIGNUM_INT_BYTES + 1] >>
1254 ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;
5c58ad2d 1255}
1256
1257/*
9400cf6f 1258 * Return a bit from a bignum; 0 is least significant, etc.
1259 */
32874aea 1260int bignum_bit(Bignum bn, int i)
1261{
62ddb51e 1262 if (i >= (int)(BIGNUM_INT_BITS * bn[0]))
32874aea 1263 return 0; /* beyond the end */
9400cf6f 1264 else
a3412f52 1265 return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;
9400cf6f 1266}
1267
1268/*
1269 * Set a bit in a bignum; 0 is least significant, etc.
1270 */
32874aea 1271void bignum_set_bit(Bignum bn, int bitnum, int value)
1272{
62ddb51e 1273 if (bitnum >= (int)(BIGNUM_INT_BITS * bn[0]))
32874aea 1274 abort(); /* beyond the end */
9400cf6f 1275 else {
a3412f52 1276 int v = bitnum / BIGNUM_INT_BITS + 1;
1277 int mask = 1 << (bitnum % BIGNUM_INT_BITS);
32874aea 1278 if (value)
1279 bn[v] |= mask;
1280 else
1281 bn[v] &= ~mask;
9400cf6f 1282 }
1283}
1284
1285/*
2e85c969 1286 * Write a SSH-1-format bignum into a buffer. It is assumed the
5c58ad2d 1287 * buffer is big enough. Returns the number of bytes used.
1288 */
32874aea 1289int ssh1_write_bignum(void *data, Bignum bn)
1290{
5c58ad2d 1291 unsigned char *p = data;
1292 int len = ssh1_bignum_length(bn);
1293 int i;
ddecd643 1294 int bitc = bignum_bitcount(bn);
5c58ad2d 1295
1296 *p++ = (bitc >> 8) & 0xFF;
32874aea 1297 *p++ = (bitc) & 0xFF;
1298 for (i = len - 2; i--;)
1299 *p++ = bignum_byte(bn, i);
5c58ad2d 1300 return len;
1301}
9400cf6f 1302
1303/*
1304 * Compare two bignums. Returns like strcmp.
1305 */
32874aea 1306int bignum_cmp(Bignum a, Bignum b)
1307{
9400cf6f 1308 int amax = a[0], bmax = b[0];
1309 int i = (amax > bmax ? amax : bmax);
1310 while (i) {
a3412f52 1311 BignumInt aval = (i > amax ? 0 : a[i]);
1312 BignumInt bval = (i > bmax ? 0 : b[i]);
32874aea 1313 if (aval < bval)
1314 return -1;
1315 if (aval > bval)
1316 return +1;
1317 i--;
9400cf6f 1318 }
1319 return 0;
1320}
1321
1322/*
1323 * Right-shift one bignum to form another.
1324 */
32874aea 1325Bignum bignum_rshift(Bignum a, int shift)
1326{
9400cf6f 1327 Bignum ret;
1328 int i, shiftw, shiftb, shiftbb, bits;
a3412f52 1329 BignumInt ai, ai1;
9400cf6f 1330
ddecd643 1331 bits = bignum_bitcount(a) - shift;
a3412f52 1332 ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
9400cf6f 1333
1334 if (ret) {
a3412f52 1335 shiftw = shift / BIGNUM_INT_BITS;
1336 shiftb = shift % BIGNUM_INT_BITS;
1337 shiftbb = BIGNUM_INT_BITS - shiftb;
32874aea 1338
1339 ai1 = a[shiftw + 1];
62ddb51e 1340 for (i = 1; i <= (int)ret[0]; i++) {
32874aea 1341 ai = ai1;
62ddb51e 1342 ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);
a3412f52 1343 ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;
32874aea 1344 }
9400cf6f 1345 }
1346
1347 return ret;
1348}
1349
1350/*
1351 * Non-modular multiplication and addition.
1352 */
32874aea 1353Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
1354{
9400cf6f 1355 int alen = a[0], blen = b[0];
1356 int mlen = (alen > blen ? alen : blen);
1357 int rlen, i, maxspot;
5a502a19 1358 int wslen;
a3412f52 1359 BignumInt *workspace;
9400cf6f 1360 Bignum ret;
1361
5a502a19 1362 /* mlen space for a, mlen space for b, 2*mlen for result,
1363 * plus scratch space for multiplication */
1364 wslen = mlen * 4 + mul_compute_scratch(mlen);
1365 workspace = snewn(wslen, BignumInt);
9400cf6f 1366 for (i = 0; i < mlen; i++) {
62ddb51e 1367 workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);
1368 workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);
9400cf6f 1369 }
1370
32874aea 1371 internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
5a502a19 1372 workspace + 2 * mlen, mlen, workspace + 4 * mlen);
9400cf6f 1373
1374 /* now just copy the result back */
1375 rlen = alen + blen + 1;
62ddb51e 1376 if (addend && rlen <= (int)addend[0])
32874aea 1377 rlen = addend[0] + 1;
9400cf6f 1378 ret = newbn(rlen);
1379 maxspot = 0;
62ddb51e 1380 for (i = 1; i <= (int)ret[0]; i++) {
32874aea 1381 ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
1382 if (ret[i] != 0)
1383 maxspot = i;
9400cf6f 1384 }
1385 ret[0] = maxspot;
1386
1387 /* now add in the addend, if any */
1388 if (addend) {
a3412f52 1389 BignumDblInt carry = 0;
32874aea 1390 for (i = 1; i <= rlen; i++) {
62ddb51e 1391 carry += (i <= (int)ret[0] ? ret[i] : 0);
1392 carry += (i <= (int)addend[0] ? addend[i] : 0);
a3412f52 1393 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1394 carry >>= BIGNUM_INT_BITS;
32874aea 1395 if (ret[i] != 0 && i > maxspot)
1396 maxspot = i;
1397 }
9400cf6f 1398 }
1399 ret[0] = maxspot;
1400
5a502a19 1401 for (i = 0; i < wslen; i++)
1402 workspace[i] = 0;
c523f55f 1403 sfree(workspace);
9400cf6f 1404 return ret;
1405}
1406
1407/*
1408 * Non-modular multiplication.
1409 */
32874aea 1410Bignum bigmul(Bignum a, Bignum b)
1411{
9400cf6f 1412 return bigmuladd(a, b, NULL);
1413}
1414
1415/*
d737853b 1416 * Simple addition.
1417 */
1418Bignum bigadd(Bignum a, Bignum b)
1419{
1420 int alen = a[0], blen = b[0];
1421 int rlen = (alen > blen ? alen : blen) + 1;
1422 int i, maxspot;
1423 Bignum ret;
1424 BignumDblInt carry;
1425
1426 ret = newbn(rlen);
1427
1428 carry = 0;
1429 maxspot = 0;
1430 for (i = 1; i <= rlen; i++) {
1431 carry += (i <= (int)a[0] ? a[i] : 0);
1432 carry += (i <= (int)b[0] ? b[i] : 0);
1433 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1434 carry >>= BIGNUM_INT_BITS;
1435 if (ret[i] != 0 && i > maxspot)
1436 maxspot = i;
1437 }
1438 ret[0] = maxspot;
1439
1440 return ret;
1441}
1442
1443/*
1444 * Subtraction. Returns a-b, or NULL if the result would come out
1445 * negative (recall that this entire bignum module only handles
1446 * positive numbers).
1447 */
1448Bignum bigsub(Bignum a, Bignum b)
1449{
1450 int alen = a[0], blen = b[0];
1451 int rlen = (alen > blen ? alen : blen);
1452 int i, maxspot;
1453 Bignum ret;
1454 BignumDblInt carry;
1455
1456 ret = newbn(rlen);
1457
1458 carry = 1;
1459 maxspot = 0;
1460 for (i = 1; i <= rlen; i++) {
1461 carry += (i <= (int)a[0] ? a[i] : 0);
1462 carry += (i <= (int)b[0] ? b[i] ^ BIGNUM_INT_MASK : BIGNUM_INT_MASK);
1463 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1464 carry >>= BIGNUM_INT_BITS;
1465 if (ret[i] != 0 && i > maxspot)
1466 maxspot = i;
1467 }
1468 ret[0] = maxspot;
1469
1470 if (!carry) {
1471 freebn(ret);
1472 return NULL;
1473 }
1474
1475 return ret;
1476}
1477
1478/*
3709bfe9 1479 * Create a bignum which is the bitmask covering another one. That
1480 * is, the smallest integer which is >= N and is also one less than
1481 * a power of two.
1482 */
32874aea 1483Bignum bignum_bitmask(Bignum n)
1484{
3709bfe9 1485 Bignum ret = copybn(n);
1486 int i;
a3412f52 1487 BignumInt j;
3709bfe9 1488
1489 i = ret[0];
1490 while (n[i] == 0 && i > 0)
32874aea 1491 i--;
3709bfe9 1492 if (i <= 0)
32874aea 1493 return ret; /* input was zero */
3709bfe9 1494 j = 1;
1495 while (j < n[i])
32874aea 1496 j = 2 * j + 1;
3709bfe9 1497 ret[i] = j;
1498 while (--i > 0)
a3412f52 1499 ret[i] = BIGNUM_INT_MASK;
3709bfe9 1500 return ret;
1501}
1502
1503/*
5c72ca61 1504 * Convert a (max 32-bit) long into a bignum.
9400cf6f 1505 */
a3412f52 1506Bignum bignum_from_long(unsigned long nn)
32874aea 1507{
9400cf6f 1508 Bignum ret;
a3412f52 1509 BignumDblInt n = nn;
9400cf6f 1510
5c72ca61 1511 ret = newbn(3);
a3412f52 1512 ret[1] = (BignumInt)(n & BIGNUM_INT_MASK);
1513 ret[2] = (BignumInt)((n >> BIGNUM_INT_BITS) & BIGNUM_INT_MASK);
5c72ca61 1514 ret[3] = 0;
1515 ret[0] = (ret[2] ? 2 : 1);
32874aea 1516 return ret;
9400cf6f 1517}
1518
1519/*
1520 * Add a long to a bignum.
1521 */
a3412f52 1522Bignum bignum_add_long(Bignum number, unsigned long addendx)
32874aea 1523{
1524 Bignum ret = newbn(number[0] + 1);
9400cf6f 1525 int i, maxspot = 0;
a3412f52 1526 BignumDblInt carry = 0, addend = addendx;
9400cf6f 1527
62ddb51e 1528 for (i = 1; i <= (int)ret[0]; i++) {
a3412f52 1529 carry += addend & BIGNUM_INT_MASK;
62ddb51e 1530 carry += (i <= (int)number[0] ? number[i] : 0);
a3412f52 1531 addend >>= BIGNUM_INT_BITS;
1532 ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
1533 carry >>= BIGNUM_INT_BITS;
32874aea 1534 if (ret[i] != 0)
1535 maxspot = i;
9400cf6f 1536 }
1537 ret[0] = maxspot;
1538 return ret;
1539}
1540
1541/*
1542 * Compute the residue of a bignum, modulo a (max 16-bit) short.
1543 */
32874aea 1544unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
1545{
a3412f52 1546 BignumDblInt mod, r;
9400cf6f 1547 int i;
1548
1549 r = 0;
1550 mod = modulus;
1551 for (i = number[0]; i > 0; i--)
736cc6d1 1552 r = (r * (BIGNUM_TOP_BIT % mod) * 2 + number[i] % mod) % mod;
6e522441 1553 return (unsigned short) r;
9400cf6f 1554}
1555
a3412f52 1556#ifdef DEBUG
32874aea 1557void diagbn(char *prefix, Bignum md)
1558{
9400cf6f 1559 int i, nibbles, morenibbles;
1560 static const char hex[] = "0123456789ABCDEF";
1561
5c72ca61 1562 debug(("%s0x", prefix ? prefix : ""));
9400cf6f 1563
32874aea 1564 nibbles = (3 + bignum_bitcount(md)) / 4;
1565 if (nibbles < 1)
1566 nibbles = 1;
1567 morenibbles = 4 * md[0] - nibbles;
1568 for (i = 0; i < morenibbles; i++)
5c72ca61 1569 debug(("-"));
32874aea 1570 for (i = nibbles; i--;)
5c72ca61 1571 debug(("%c",
1572 hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
9400cf6f 1573
32874aea 1574 if (prefix)
5c72ca61 1575 debug(("\n"));
1576}
f28753ab 1577#endif
5c72ca61 1578
1579/*
1580 * Simple division.
1581 */
1582Bignum bigdiv(Bignum a, Bignum b)
1583{
1584 Bignum q = newbn(a[0]);
1585 bigdivmod(a, b, NULL, q);
1586 return q;
1587}
1588
1589/*
1590 * Simple remainder.
1591 */
1592Bignum bigmod(Bignum a, Bignum b)
1593{
1594 Bignum r = newbn(b[0]);
1595 bigdivmod(a, b, r, NULL);
1596 return r;
9400cf6f 1597}
1598
1599/*
1600 * Greatest common divisor.
1601 */
32874aea 1602Bignum biggcd(Bignum av, Bignum bv)
1603{
9400cf6f 1604 Bignum a = copybn(av);
1605 Bignum b = copybn(bv);
1606
9400cf6f 1607 while (bignum_cmp(b, Zero) != 0) {
32874aea 1608 Bignum t = newbn(b[0]);
5c72ca61 1609 bigdivmod(a, b, t, NULL);
32874aea 1610 while (t[0] > 1 && t[t[0]] == 0)
1611 t[0]--;
1612 freebn(a);
1613 a = b;
1614 b = t;
9400cf6f 1615 }
1616
1617 freebn(b);
1618 return a;
1619}
1620
1621/*
1622 * Modular inverse, using Euclid's extended algorithm.
1623 */
32874aea 1624Bignum modinv(Bignum number, Bignum modulus)
1625{
9400cf6f 1626 Bignum a = copybn(modulus);
1627 Bignum b = copybn(number);
1628 Bignum xp = copybn(Zero);
1629 Bignum x = copybn(One);
1630 int sign = +1;
1631
1632 while (bignum_cmp(b, One) != 0) {
32874aea 1633 Bignum t = newbn(b[0]);
1634 Bignum q = newbn(a[0]);
5c72ca61 1635 bigdivmod(a, b, t, q);
32874aea 1636 while (t[0] > 1 && t[t[0]] == 0)
1637 t[0]--;
1638 freebn(a);
1639 a = b;
1640 b = t;
1641 t = xp;
1642 xp = x;
1643 x = bigmuladd(q, xp, t);
1644 sign = -sign;
1645 freebn(t);
75374b2f 1646 freebn(q);
9400cf6f 1647 }
1648
1649 freebn(b);
1650 freebn(a);
1651 freebn(xp);
1652
1653 /* now we know that sign * x == 1, and that x < modulus */
1654 if (sign < 0) {
32874aea 1655 /* set a new x to be modulus - x */
1656 Bignum newx = newbn(modulus[0]);
a3412f52 1657 BignumInt carry = 0;
32874aea 1658 int maxspot = 1;
1659 int i;
1660
62ddb51e 1661 for (i = 1; i <= (int)newx[0]; i++) {
1662 BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);
1663 BignumInt bword = (i <= (int)x[0] ? x[i] : 0);
32874aea 1664 newx[i] = aword - bword - carry;
1665 bword = ~bword;
1666 carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
1667 if (newx[i] != 0)
1668 maxspot = i;
1669 }
1670 newx[0] = maxspot;
1671 freebn(x);
1672 x = newx;
9400cf6f 1673 }
1674
1675 /* and return. */
1676 return x;
1677}
6e522441 1678
1679/*
1680 * Render a bignum into decimal. Return a malloced string holding
1681 * the decimal representation.
1682 */
32874aea 1683char *bignum_decimal(Bignum x)
1684{
6e522441 1685 int ndigits, ndigit;
1686 int i, iszero;
a3412f52 1687 BignumDblInt carry;
6e522441 1688 char *ret;
a3412f52 1689 BignumInt *workspace;
6e522441 1690
1691 /*
1692 * First, estimate the number of digits. Since log(10)/log(2)
1693 * is just greater than 93/28 (the joys of continued fraction
1694 * approximations...) we know that for every 93 bits, we need
1695 * at most 28 digits. This will tell us how much to malloc.
1696 *
1697 * Formally: if x has i bits, that means x is strictly less
1698 * than 2^i. Since 2 is less than 10^(28/93), this is less than
1699 * 10^(28i/93). We need an integer power of ten, so we must
1700 * round up (rounding down might make it less than x again).
1701 * Therefore if we multiply the bit count by 28/93, rounding
1702 * up, we will have enough digits.
74c79ce8 1703 *
1704 * i=0 (i.e., x=0) is an irritating special case.
6e522441 1705 */
ddecd643 1706 i = bignum_bitcount(x);
74c79ce8 1707 if (!i)
1708 ndigits = 1; /* x = 0 */
1709 else
1710 ndigits = (28 * i + 92) / 93; /* multiply by 28/93 and round up */
32874aea 1711 ndigits++; /* allow for trailing \0 */
3d88e64d 1712 ret = snewn(ndigits, char);
6e522441 1713
1714 /*
1715 * Now allocate some workspace to hold the binary form as we
1716 * repeatedly divide it by ten. Initialise this to the
1717 * big-endian form of the number.
1718 */
a3412f52 1719 workspace = snewn(x[0], BignumInt);
62ddb51e 1720 for (i = 0; i < (int)x[0]; i++)
32874aea 1721 workspace[i] = x[x[0] - i];
6e522441 1722
1723 /*
1724 * Next, write the decimal number starting with the last digit.
1725 * We use ordinary short division, dividing 10 into the
1726 * workspace.
1727 */
32874aea 1728 ndigit = ndigits - 1;
6e522441 1729 ret[ndigit] = '\0';
1730 do {
32874aea 1731 iszero = 1;
1732 carry = 0;
62ddb51e 1733 for (i = 0; i < (int)x[0]; i++) {
a3412f52 1734 carry = (carry << BIGNUM_INT_BITS) + workspace[i];
1735 workspace[i] = (BignumInt) (carry / 10);
32874aea 1736 if (workspace[i])
1737 iszero = 0;
1738 carry %= 10;
1739 }
1740 ret[--ndigit] = (char) (carry + '0');
6e522441 1741 } while (!iszero);
1742
1743 /*
1744 * There's a chance we've fallen short of the start of the
1745 * string. Correct if so.
1746 */
1747 if (ndigit > 0)
32874aea 1748 memmove(ret, ret + ndigit, ndigits - ndigit);
6e522441 1749
1750 /*
1751 * Done.
1752 */
c523f55f 1753 sfree(workspace);
6e522441 1754 return ret;
1755}
f3c29e34 1756
1757#ifdef TESTBN
1758
1759#include <stdio.h>
1760#include <stdlib.h>
1761#include <ctype.h>
1762
1763/*
4800a5e5 1764 * gcc -Wall -g -O0 -DTESTBN -o testbn sshbn.c misc.c conf.c tree234.c unix/uxmisc.c -I. -I unix -I charset
f84f1e46 1765 *
1766 * Then feed to this program's standard input the output of
1767 * testdata/bignum.py .
f3c29e34 1768 */
1769
1770void modalfatalbox(char *p, ...)
1771{
1772 va_list ap;
1773 fprintf(stderr, "FATAL ERROR: ");
1774 va_start(ap, p);
1775 vfprintf(stderr, p, ap);
1776 va_end(ap);
1777 fputc('\n', stderr);
1778 exit(1);
1779}
1780
1781#define fromxdigit(c) ( (c)>'9' ? ((c)&0xDF) - 'A' + 10 : (c) - '0' )
1782
1783int main(int argc, char **argv)
1784{
1785 char *buf;
1786 int line = 0;
1787 int passes = 0, fails = 0;
1788
1789 while ((buf = fgetline(stdin)) != NULL) {
1790 int maxlen = strlen(buf);
1791 unsigned char *data = snewn(maxlen, unsigned char);
f84f1e46 1792 unsigned char *ptrs[5], *q;
f3c29e34 1793 int ptrnum;
1794 char *bufp = buf;
1795
1796 line++;
1797
1798 q = data;
1799 ptrnum = 0;
1800
f84f1e46 1801 while (*bufp && !isspace((unsigned char)*bufp))
1802 bufp++;
1803 if (bufp)
1804 *bufp++ = '\0';
1805
f3c29e34 1806 while (*bufp) {
1807 char *start, *end;
1808 int i;
1809
1810 while (*bufp && !isxdigit((unsigned char)*bufp))
1811 bufp++;
1812 start = bufp;
1813
1814 if (!*bufp)
1815 break;
1816
1817 while (*bufp && isxdigit((unsigned char)*bufp))
1818 bufp++;
1819 end = bufp;
1820
1821 if (ptrnum >= lenof(ptrs))
1822 break;
1823 ptrs[ptrnum++] = q;
1824
1825 for (i = -((end - start) & 1); i < end-start; i += 2) {
1826 unsigned char val = (i < 0 ? 0 : fromxdigit(start[i]));
1827 val = val * 16 + fromxdigit(start[i+1]);
1828 *q++ = val;
1829 }
1830
1831 ptrs[ptrnum] = q;
1832 }
1833
f84f1e46 1834 if (!strcmp(buf, "mul")) {
1835 Bignum a, b, c, p;
1836
1837 if (ptrnum != 3) {
f6939e2b 1838 printf("%d: mul with %d parameters, expected 3\n", line, ptrnum);
f84f1e46 1839 exit(1);
1840 }
1841 a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1842 b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1843 c = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1844 p = bigmul(a, b);
f3c29e34 1845
1846 if (bignum_cmp(c, p) == 0) {
1847 passes++;
1848 } else {
1849 char *as = bignum_decimal(a);
1850 char *bs = bignum_decimal(b);
1851 char *cs = bignum_decimal(c);
1852 char *ps = bignum_decimal(p);
1853
1854 printf("%d: fail: %s * %s gave %s expected %s\n",
1855 line, as, bs, ps, cs);
1856 fails++;
1857
1858 sfree(as);
1859 sfree(bs);
1860 sfree(cs);
1861 sfree(ps);
1862 }
1863 freebn(a);
1864 freebn(b);
1865 freebn(c);
1866 freebn(p);
f84f1e46 1867 } else if (!strcmp(buf, "pow")) {
1868 Bignum base, expt, modulus, expected, answer;
1869
1870 if (ptrnum != 4) {
f6939e2b 1871 printf("%d: mul with %d parameters, expected 4\n", line, ptrnum);
f84f1e46 1872 exit(1);
1873 }
1874
1875 base = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);
1876 expt = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);
1877 modulus = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);
1878 expected = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);
1879 answer = modpow(base, expt, modulus);
1880
1881 if (bignum_cmp(expected, answer) == 0) {
1882 passes++;
1883 } else {
1884 char *as = bignum_decimal(base);
1885 char *bs = bignum_decimal(expt);
1886 char *cs = bignum_decimal(modulus);
1887 char *ds = bignum_decimal(answer);
1888 char *ps = bignum_decimal(expected);
1889
1890 printf("%d: fail: %s ^ %s mod %s gave %s expected %s\n",
1891 line, as, bs, cs, ds, ps);
1892 fails++;
1893
1894 sfree(as);
1895 sfree(bs);
1896 sfree(cs);
1897 sfree(ds);
1898 sfree(ps);
1899 }
1900 freebn(base);
1901 freebn(expt);
1902 freebn(modulus);
1903 freebn(expected);
1904 freebn(answer);
1905 } else {
1906 printf("%d: unrecognised test keyword: '%s'\n", line, buf);
1907 exit(1);
f3c29e34 1908 }
f84f1e46 1909
f3c29e34 1910 sfree(buf);
1911 sfree(data);
1912 }
1913
1914 printf("passed %d failed %d total %d\n", passes, fails, passes+fails);
1915 return fails != 0;
1916}
1917
1918#endif