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