2 * Bignum routines for RSA and DH and stuff.
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
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.
26 #if defined __GNUC__ && defined __i386__
27 typedef unsigned long BignumInt
;
28 typedef unsigned long long BignumDblInt
;
29 #define BIGNUM_INT_MASK 0xFFFFFFFFUL
30 #define BIGNUM_TOP_BIT 0x80000000UL
31 #define BIGNUM_INT_BITS 32
32 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
33 #define DIVMOD_WORD(q, r, hi, lo, w) \
35 "=d" (r), "=a" (q) : \
36 "r" (w), "d" (hi), "a" (lo))
37 #elif defined _MSC_VER && defined _M_IX86
38 typedef unsigned __int32 BignumInt
;
39 typedef unsigned __int64 BignumDblInt
;
40 #define BIGNUM_INT_MASK 0xFFFFFFFFUL
41 #define BIGNUM_TOP_BIT 0x80000000UL
42 #define BIGNUM_INT_BITS 32
43 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
44 /* Note: MASM interprets array subscripts in the macro arguments as
45 * assembler syntax, which gives the wrong answer. Don't supply them.
46 * <http://msdn2.microsoft.com/en-us/library/bf1dw62z.aspx> */
47 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
55 /* 64-bit architectures can do 32x32->64 chunks at a time */
56 typedef unsigned int BignumInt
;
57 typedef unsigned long BignumDblInt
;
58 #define BIGNUM_INT_MASK 0xFFFFFFFFU
59 #define BIGNUM_TOP_BIT 0x80000000U
60 #define BIGNUM_INT_BITS 32
61 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
62 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
63 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
68 /* 64-bit architectures in which unsigned long is 32 bits, not 64 */
69 typedef unsigned long BignumInt
;
70 typedef unsigned long long BignumDblInt
;
71 #define BIGNUM_INT_MASK 0xFFFFFFFFUL
72 #define BIGNUM_TOP_BIT 0x80000000UL
73 #define BIGNUM_INT_BITS 32
74 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
75 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
76 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
81 /* Fallback for all other cases */
82 typedef unsigned short BignumInt
;
83 typedef unsigned long BignumDblInt
;
84 #define BIGNUM_INT_MASK 0xFFFFU
85 #define BIGNUM_TOP_BIT 0x8000U
86 #define BIGNUM_INT_BITS 16
87 #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
88 #define DIVMOD_WORD(q, r, hi, lo, w) do { \
89 BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
95 #define BIGNUM_INT_BYTES (BIGNUM_INT_BITS / 8)
97 #define BIGNUM_INTERNAL
98 typedef BignumInt
*Bignum
;
102 BignumInt bnZero
[1] = { 0 };
103 BignumInt bnOne
[2] = { 1, 1 };
106 * The Bignum format is an array of `BignumInt'. The first
107 * element of the array counts the remaining elements. The
108 * remaining elements express the actual number, base 2^BIGNUM_INT_BITS, _least_
109 * significant digit first. (So it's trivial to extract the bit
110 * with value 2^n for any n.)
112 * All Bignums in this module are positive. Negative numbers must
113 * be dealt with outside it.
115 * INVARIANT: the most significant word of any Bignum must be
119 Bignum Zero
= bnZero
, One
= bnOne
;
121 static Bignum
newbn(int length
)
123 Bignum b
= snewn(length
+ 1, BignumInt
);
126 memset(b
, 0, (length
+ 1) * sizeof(*b
));
131 void bn_restore_invariant(Bignum b
)
133 while (b
[0] > 1 && b
[b
[0]] == 0)
137 Bignum
copybn(Bignum orig
)
139 Bignum b
= snewn(orig
[0] + 1, BignumInt
);
142 memcpy(b
, orig
, (orig
[0] + 1) * sizeof(*b
));
146 void freebn(Bignum b
)
149 * Burn the evidence, just in case.
151 smemclr(b
, sizeof(b
[0]) * (b
[0] + 1));
155 Bignum
bn_power_2(int n
)
157 Bignum ret
= newbn(n
/ BIGNUM_INT_BITS
+ 1);
158 bignum_set_bit(ret
, n
, 1);
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
167 static BignumInt
internal_add(const BignumInt
*a
, const BignumInt
*b
,
168 BignumInt
*c
, int len
)
171 BignumDblInt carry
= 0;
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
;
179 return (BignumInt
)carry
;
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
187 static void internal_sub(const BignumInt
*a
, const BignumInt
*b
,
188 BignumInt
*c
, int len
)
191 BignumDblInt carry
= 1;
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
;
202 * Input is in the first len words of a and b.
203 * Result is returned in the first 2*len words of c.
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.)
209 #define KARATSUBA_THRESHOLD 50
210 static int mul_compute_scratch(int len
)
213 while (len
> KARATSUBA_THRESHOLD
) {
214 int toplen
= len
/2, botlen
= len
- toplen
; /* botlen is the bigger */
215 int midlen
= botlen
+ 1;
221 static void internal_mul(const BignumInt
*a
, const BignumInt
*b
,
222 BignumInt
*c
, int len
, BignumInt
*scratch
)
224 if (len
> KARATSUBA_THRESHOLD
) {
228 * Karatsuba divide-and-conquer algorithm. Cut each input in
229 * half, so that it's expressed as two big 'digits' in a giant
235 * Then the product is of course
237 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
239 * and we compute the three coefficients by recursively
240 * calling ourself to do half-length multiplications.
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
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
249 * and then we subtract the other two coefficients (a_1 b_1
250 * and a_0 b_0) which we were computing anyway.
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.
259 int toplen
= len
/2, botlen
= len
- toplen
; /* botlen is the bigger */
260 int midlen
= botlen
+ 1;
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
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
]);
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
]);
288 internal_mul(a
, b
, c
, toplen
, scratch
);
291 for (i
= 0; i
< 2*toplen
; i
++) {
292 printf("%0*x", BIGNUM_INT_BITS
/4, c
[i
]);
298 internal_mul(a
+ toplen
, b
+ toplen
, c
+ 2*toplen
, botlen
, scratch
);
301 for (i
= 0; i
< 2*botlen
; i
++) {
302 printf("%0*x", BIGNUM_INT_BITS
/4, c
[2*toplen
+i
]);
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
310 scratch
[0] = scratch
[1] = scratch
[midlen
] = scratch
[midlen
+1] = 0;
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 */
317 /* compute a_1 + a_0 */
318 scratch
[0] = internal_add(scratch
+1, a
+toplen
, scratch
+1, botlen
);
320 printf("a1plusa0 = 0x");
321 for (i
= 0; i
< midlen
; i
++) {
322 printf("%0*x", BIGNUM_INT_BITS
/4, scratch
[i
]);
326 /* compute b_1 + b_0 */
327 scratch
[midlen
] = internal_add(scratch
+midlen
+1, b
+toplen
,
328 scratch
+midlen
+1, botlen
);
330 printf("b1plusb0 = 0x");
331 for (i
= 0; i
< midlen
; i
++) {
332 printf("%0*x", BIGNUM_INT_BITS
/4, scratch
[midlen
+i
]);
338 * Now we can do the third multiplication.
340 internal_mul(scratch
, scratch
+ midlen
, scratch
+ 2*midlen
, midlen
,
343 printf("a1plusa0timesb1plusb0 = 0x");
344 for (i
= 0; i
< 2*midlen
; i
++) {
345 printf("%0*x", BIGNUM_INT_BITS
/4, scratch
[2*midlen
+i
]);
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.
355 scratch
[0] = scratch
[1] = scratch
[2] = scratch
[3] = 0;
356 for (i
= 0; i
< 2*toplen
; i
++)
357 scratch
[2*midlen
- 2*toplen
+ i
] = c
[i
];
358 scratch
[1] = internal_add(scratch
+2, c
+ 2*toplen
,
359 scratch
+2, 2*botlen
);
361 printf("a1b1plusa0b0 = 0x");
362 for (i
= 0; i
< 2*midlen
; i
++) {
363 printf("%0*x", BIGNUM_INT_BITS
/4, scratch
[i
]);
368 internal_sub(scratch
+ 2*midlen
, scratch
,
369 scratch
+ 2*midlen
, 2*midlen
);
371 printf("a1b0plusa0b1 = 0x");
372 for (i
= 0; i
< 2*midlen
; i
++) {
373 printf("%0*x", BIGNUM_INT_BITS
/4, scratch
[2*midlen
+i
]);
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.
384 carry
= internal_add(c
+ 2*len
- botlen
- 2*midlen
,
386 c
+ 2*len
- botlen
- 2*midlen
, 2*midlen
);
387 i
= 2*len
- botlen
- 2*midlen
- 1;
391 c
[i
] = (BignumInt
)carry
;
392 carry
>>= BIGNUM_INT_BITS
;
397 for (i
= 0; i
< 2*len
; i
++) {
398 printf("%0*x", BIGNUM_INT_BITS
/4, c
[i
]);
407 const BignumInt
*ap
, *bp
;
411 * Multiply in the ordinary O(N^2) way.
414 for (i
= 0; i
< 2 * len
; i
++)
417 for (cps
= c
+ 2*len
, ap
= a
+ len
; ap
-- > a
; cps
--) {
419 for (cp
= cps
, bp
= b
+ len
; cp
--, bp
-- > b
;) {
420 t
= (MUL_WORD(*ap
, *bp
) + carry
) + *cp
;
422 carry
= (BignumInt
)(t
>> BIGNUM_INT_BITS
);
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).
434 static void internal_mul_low(const BignumInt
*a
, const BignumInt
*b
,
435 BignumInt
*c
, int len
, BignumInt
*scratch
)
437 if (len
> KARATSUBA_THRESHOLD
) {
441 * Karatsuba-aware version of internal_mul_low. As before, we
442 * express each input value as a shifted combination of two
448 * Then the full product is, as before,
450 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
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.
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.
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.
472 int toplen
= len
/2, botlen
= len
- toplen
; /* botlen is the bigger */
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
483 internal_mul(a
+ toplen
, b
+ toplen
, scratch
+ 2*toplen
, botlen
,
487 internal_mul_low(a
, b
+ len
- toplen
, scratch
+ toplen
, toplen
,
491 internal_mul_low(a
+ len
- toplen
, b
, scratch
, toplen
,
494 /* Copy the bottom half of the big coefficient into place */
495 for (i
= 0; i
< botlen
; i
++)
496 c
[toplen
+ i
] = scratch
[2*toplen
+ botlen
+ i
];
498 /* Add the two small coefficients, throwing away the returned carry */
499 internal_add(scratch
, scratch
+ toplen
, scratch
, toplen
);
501 /* And add that to the large coefficient, leaving the result in c. */
502 internal_add(scratch
, scratch
+ 2*toplen
+ botlen
- toplen
,
509 const BignumInt
*ap
, *bp
;
513 * Multiply in the ordinary O(N^2) way.
516 for (i
= 0; i
< len
; i
++)
519 for (cps
= c
+ len
, ap
= a
+ len
; ap
-- > a
; cps
--) {
521 for (cp
= cps
, bp
= b
+ len
; bp
--, cp
-- > c
;) {
522 t
= (MUL_WORD(*ap
, *bp
) + carry
) + *cp
;
524 carry
= (BignumInt
)(t
>> BIGNUM_INT_BITS
);
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 <=
537 * 'n' and 'mninv' should be big-endian arrays of 'len' BignumInts
538 * each, containing respectively n and the multiplicative inverse of
541 * 'tmp' is an array of BignumInt used as scratch space, of length at
542 * least 3*len + mul_compute_scratch(len).
544 static void monty_reduce(BignumInt
*x
, const BignumInt
*n
,
545 const BignumInt
*mninv
, BignumInt
*tmp
, int len
)
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.
555 internal_mul_low(x
+ len
, mninv
, tmp
, len
, tmp
+ 3*len
);
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.
562 * The following multiply leaves that answer in the _most_
563 * significant half of the 'x' array, so then we must shift it
566 internal_mul(tmp
, n
, tmp
+len
, len
, tmp
+ 3*len
);
567 carry
= internal_add(x
, tmp
+len
, x
, 2*len
);
568 for (i
= 0; i
< len
; i
++)
569 x
[len
+ i
] = x
[i
], x
[i
] = 0;
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.
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.
583 for (i
= 0; i
< len
; i
++)
584 if (x
[len
+ i
] != n
[i
])
587 if (carry
|| i
>= len
|| x
[len
+ i
] > n
[i
])
588 internal_sub(x
+len
, n
, x
+len
, len
);
591 static void internal_add_shifted(BignumInt
*number
,
592 unsigned n
, int shift
)
594 int word
= 1 + (shift
/ BIGNUM_INT_BITS
);
595 int bshift
= shift
% BIGNUM_INT_BITS
;
598 addend
= (BignumDblInt
)n
<< bshift
;
601 addend
+= number
[word
];
602 number
[word
] = (BignumInt
) addend
& BIGNUM_INT_MASK
;
603 addend
>>= BIGNUM_INT_BITS
;
610 * Input in first alen words of a and first mlen words of m.
611 * Output in first alen words of a
612 * (of which first alen-mlen words will be zero).
613 * The MSW of m MUST have its high bit set.
614 * Quotient is accumulated in the `quotient' array, which is a Bignum
615 * rather than the internal bigendian format. Quotient parts are shifted
616 * left by `qshift' before adding into quot.
618 static void internal_mod(BignumInt
*a
, int alen
,
619 BignumInt
*m
, int mlen
,
620 BignumInt
*quot
, int qshift
)
632 for (i
= 0; i
<= alen
- mlen
; i
++) {
634 unsigned int q
, r
, c
, ai1
;
648 /* Find q = h:a[i] / m0 */
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.
662 * In this situation we set q to be the largest
663 * quotient we _can_ stomach (0xFF, of course).
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
);
672 /* Refine our estimate of q by looking at
673 h:a[i]:a[i+1] / m0:m1 */
675 if (t
> ((BignumDblInt
) r
<< BIGNUM_INT_BITS
) + ai1
) {
678 r
= (r
+ m0
) & BIGNUM_INT_MASK
; /* overflow? */
679 if (r
>= (BignumDblInt
) m0
&&
680 t
> ((BignumDblInt
) r
<< BIGNUM_INT_BITS
) + ai1
) q
--;
684 /* Subtract q * m from a[i...] */
686 for (k
= mlen
- 1; k
>= 0; k
--) {
687 t
= MUL_WORD(q
, m
[k
]);
689 c
= (unsigned)(t
>> BIGNUM_INT_BITS
);
690 if ((BignumInt
) t
> a
[i
+ k
])
692 a
[i
+ k
] -= (BignumInt
) t
;
695 /* Add back m in case of borrow */
698 for (k
= mlen
- 1; k
>= 0; k
--) {
701 a
[i
+ k
] = (BignumInt
) t
;
702 t
= t
>> BIGNUM_INT_BITS
;
707 internal_add_shifted(quot
, q
, qshift
+ BIGNUM_INT_BITS
* (alen
- mlen
- i
));
712 * Compute (base ^ exp) % mod, the pedestrian way.
714 Bignum
modpow_simple(Bignum base_in
, Bignum exp
, Bignum mod
)
716 BignumInt
*a
, *b
, *n
, *m
, *scratch
;
718 int mlen
, scratchlen
, i
, j
;
722 * The most significant word of mod needs to be non-zero. It
723 * should already be, but let's make sure.
725 assert(mod
[mod
[0]] != 0);
728 * Make sure the base is smaller than the modulus, by reducing
729 * it modulo the modulus if not.
731 base
= bigmod(base_in
, mod
);
733 /* Allocate m of size mlen, copy mod to m */
734 /* We use big endian internally */
736 m
= snewn(mlen
, BignumInt
);
737 for (j
= 0; j
< mlen
; j
++)
738 m
[j
] = mod
[mod
[0] - j
];
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
)
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
;
750 /* Allocate n of size mlen, copy base to n */
751 n
= snewn(mlen
, BignumInt
);
753 for (j
= 0; j
< i
; j
++)
755 for (j
= 0; j
< (int)base
[0]; j
++)
756 n
[i
+ j
] = base
[base
[0] - j
];
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
++)
765 /* Scratch space for multiplies */
766 scratchlen
= mul_compute_scratch(mlen
);
767 scratch
= snewn(scratchlen
, BignumInt
);
769 /* Skip leading zero bits of exp. */
771 j
= BIGNUM_INT_BITS
-1;
772 while (i
< (int)exp
[0] && (exp
[exp
[0] - i
] & (1 << j
)) == 0) {
776 j
= BIGNUM_INT_BITS
-1;
780 /* Main computation */
781 while (i
< (int)exp
[0]) {
783 internal_mul(a
+ mlen
, a
+ mlen
, b
, mlen
, scratch
);
784 internal_mod(b
, mlen
* 2, m
, mlen
, NULL
, 0);
785 if ((exp
[exp
[0] - i
] & (1 << j
)) != 0) {
786 internal_mul(b
+ mlen
, n
, a
, mlen
, scratch
);
787 internal_mod(a
, mlen
* 2, m
, mlen
, NULL
, 0);
797 j
= BIGNUM_INT_BITS
-1;
800 /* Fixup result in case the modulus was shifted */
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
));
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)
817 /* Free temporary arrays */
818 for (i
= 0; i
< 2 * mlen
; i
++)
821 for (i
= 0; i
< scratchlen
; i
++)
824 for (i
= 0; i
< 2 * mlen
; i
++)
827 for (i
= 0; i
< mlen
; i
++)
830 for (i
= 0; i
< mlen
; i
++)
840 * Compute (base ^ exp) % mod. Uses the Montgomery multiplication
841 * technique where possible, falling back to modpow_simple otherwise.
843 Bignum
modpow(Bignum base_in
, Bignum exp
, Bignum mod
)
845 BignumInt
*a
, *b
, *x
, *n
, *mninv
, *scratch
;
846 int len
, scratchlen
, i
, j
;
847 Bignum base
, base2
, r
, rn
, inv
, result
;
850 * The most significant word of mod needs to be non-zero. It
851 * should already be, but let's make sure.
853 assert(mod
[mod
[0]] != 0);
856 * mod had better be odd, or we can't do Montgomery multiplication
857 * using a power of two at all.
860 return modpow_simple(base_in
, exp
, mod
);
863 * Make sure the base is smaller than the modulus, by reducing
864 * it modulo the modulus if not.
866 base
= bigmod(base_in
, mod
);
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
874 r
= bn_power_2(BIGNUM_INT_BITS
* len
);
875 inv
= modinv(mod
, r
);
878 * Multiply the base by r mod n, to get it into Montgomery
881 base2
= modmul(base
, r
, mod
);
885 rn
= bigmod(r
, mod
); /* r mod n, i.e. Montgomerified 1 */
887 freebn(r
); /* won't need this any more */
890 * Set up internal arrays of the right lengths, in big-endian
891 * format, containing the base, the modulus, and the modulus's
894 n
= snewn(len
, BignumInt
);
895 for (j
= 0; j
< len
; j
++)
896 n
[len
- 1 - j
] = mod
[j
+ 1];
898 mninv
= snewn(len
, BignumInt
);
899 for (j
= 0; j
< len
; j
++)
900 mninv
[len
- 1 - j
] = (j
< (int)inv
[0] ? inv
[j
+ 1] : 0);
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
++)
906 internal_sub(x
, mninv
, mninv
, len
);
908 /* x = snewn(len, BignumInt); */ /* already done above */
909 for (j
= 0; j
< len
; j
++)
910 x
[len
- 1 - j
] = (j
< (int)base
[0] ? base
[j
+ 1] : 0);
911 freebn(base
); /* we don't need this copy of it any more */
913 a
= snewn(2*len
, BignumInt
);
914 b
= snewn(2*len
, BignumInt
);
915 for (j
= 0; j
< len
; j
++)
916 a
[2*len
- 1 - j
] = (j
< (int)rn
[0] ? rn
[j
+ 1] : 0);
919 /* Scratch space for multiplies */
920 scratchlen
= 3*len
+ mul_compute_scratch(len
);
921 scratch
= snewn(scratchlen
, BignumInt
);
923 /* Skip leading zero bits of exp. */
925 j
= BIGNUM_INT_BITS
-1;
926 while (i
< (int)exp
[0] && (exp
[exp
[0] - i
] & (1 << j
)) == 0) {
930 j
= BIGNUM_INT_BITS
-1;
934 /* Main computation */
935 while (i
< (int)exp
[0]) {
937 internal_mul(a
+ len
, a
+ len
, b
, len
, scratch
);
938 monty_reduce(b
, n
, mninv
, scratch
, len
);
939 if ((exp
[exp
[0] - i
] & (1 << j
)) != 0) {
940 internal_mul(b
+ len
, x
, a
, len
, scratch
);
941 monty_reduce(a
, n
, mninv
, scratch
, len
);
951 j
= BIGNUM_INT_BITS
-1;
955 * Final monty_reduce to get back from the adjusted Montgomery
958 monty_reduce(a
, n
, mninv
, scratch
, len
);
960 /* Copy result to buffer */
961 result
= newbn(mod
[0]);
962 for (i
= 0; i
< len
; i
++)
963 result
[result
[0] - i
] = a
[i
+ len
];
964 while (result
[0] > 1 && result
[result
[0]] == 0)
967 /* Free temporary arrays */
968 for (i
= 0; i
< scratchlen
; i
++)
971 for (i
= 0; i
< 2 * len
; i
++)
974 for (i
= 0; i
< 2 * len
; i
++)
977 for (i
= 0; i
< len
; i
++)
980 for (i
= 0; i
< len
; i
++)
983 for (i
= 0; i
< len
; i
++)
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.
995 Bignum
modmul(Bignum p
, Bignum q
, Bignum mod
)
997 BignumInt
*a
, *n
, *m
, *o
, *scratch
;
998 int mshift
, scratchlen
;
999 int pqlen
, mlen
, rlen
, i
, j
;
1002 /* Allocate m of size mlen, copy mod to m */
1003 /* We use big endian internally */
1005 m
= snewn(mlen
, BignumInt
);
1006 for (j
= 0; j
< mlen
; j
++)
1007 m
[j
] = mod
[mod
[0] - j
];
1009 /* Shift m left to make msb bit set */
1010 for (mshift
= 0; mshift
< BIGNUM_INT_BITS
-1; mshift
++)
1011 if ((m
[0] << mshift
) & BIGNUM_TOP_BIT
)
1014 for (i
= 0; i
< mlen
- 1; i
++)
1015 m
[i
] = (m
[i
] << mshift
) | (m
[i
+ 1] >> (BIGNUM_INT_BITS
- mshift
));
1016 m
[mlen
- 1] = m
[mlen
- 1] << mshift
;
1019 pqlen
= (p
[0] > q
[0] ? p
[0] : q
[0]);
1022 * Make sure that we're allowing enough space. The shifting below
1023 * will underflow the vectors we allocate if pqlen is too small.
1025 if (2*pqlen
<= mlen
)
1028 /* Allocate n of size pqlen, copy p to n */
1029 n
= snewn(pqlen
, BignumInt
);
1031 for (j
= 0; j
< i
; j
++)
1033 for (j
= 0; j
< (int)p
[0]; j
++)
1034 n
[i
+ j
] = p
[p
[0] - j
];
1036 /* Allocate o of size pqlen, copy q to o */
1037 o
= snewn(pqlen
, BignumInt
);
1039 for (j
= 0; j
< i
; j
++)
1041 for (j
= 0; j
< (int)q
[0]; j
++)
1042 o
[i
+ j
] = q
[q
[0] - j
];
1044 /* Allocate a of size 2*pqlen for result */
1045 a
= snewn(2 * pqlen
, BignumInt
);
1047 /* Scratch space for multiplies */
1048 scratchlen
= mul_compute_scratch(pqlen
);
1049 scratch
= snewn(scratchlen
, BignumInt
);
1051 /* Main computation */
1052 internal_mul(n
, o
, a
, pqlen
, scratch
);
1053 internal_mod(a
, pqlen
* 2, m
, mlen
, NULL
, 0);
1055 /* Fixup result in case the modulus was shifted */
1057 for (i
= 2 * pqlen
- mlen
- 1; i
< 2 * pqlen
- 1; i
++)
1058 a
[i
] = (a
[i
] << mshift
) | (a
[i
+ 1] >> (BIGNUM_INT_BITS
- mshift
));
1059 a
[2 * pqlen
- 1] = a
[2 * pqlen
- 1] << mshift
;
1060 internal_mod(a
, pqlen
* 2, m
, mlen
, NULL
, 0);
1061 for (i
= 2 * pqlen
- 1; i
>= 2 * pqlen
- mlen
; i
--)
1062 a
[i
] = (a
[i
] >> mshift
) | (a
[i
- 1] << (BIGNUM_INT_BITS
- mshift
));
1065 /* Copy result to buffer */
1066 rlen
= (mlen
< pqlen
* 2 ? mlen
: pqlen
* 2);
1067 result
= newbn(rlen
);
1068 for (i
= 0; i
< rlen
; i
++)
1069 result
[result
[0] - i
] = a
[i
+ 2 * pqlen
- rlen
];
1070 while (result
[0] > 1 && result
[result
[0]] == 0)
1073 /* Free temporary arrays */
1074 for (i
= 0; i
< scratchlen
; i
++)
1077 for (i
= 0; i
< 2 * pqlen
; i
++)
1080 for (i
= 0; i
< mlen
; i
++)
1083 for (i
= 0; i
< pqlen
; i
++)
1086 for (i
= 0; i
< pqlen
; i
++)
1095 * The most significant word of mod MUST be non-zero.
1096 * We assume that the result array is the same size as the mod array.
1097 * We optionally write out a quotient if `quotient' is non-NULL.
1098 * We can avoid writing out the result if `result' is NULL.
1100 static void bigdivmod(Bignum p
, Bignum mod
, Bignum result
, Bignum quotient
)
1104 int plen
, mlen
, i
, j
;
1106 /* Allocate m of size mlen, copy mod to m */
1107 /* We use big endian internally */
1109 m
= snewn(mlen
, BignumInt
);
1110 for (j
= 0; j
< mlen
; j
++)
1111 m
[j
] = mod
[mod
[0] - j
];
1113 /* Shift m left to make msb bit set */
1114 for (mshift
= 0; mshift
< BIGNUM_INT_BITS
-1; mshift
++)
1115 if ((m
[0] << mshift
) & BIGNUM_TOP_BIT
)
1118 for (i
= 0; i
< mlen
- 1; i
++)
1119 m
[i
] = (m
[i
] << mshift
) | (m
[i
+ 1] >> (BIGNUM_INT_BITS
- mshift
));
1120 m
[mlen
- 1] = m
[mlen
- 1] << mshift
;
1124 /* Ensure plen > mlen */
1128 /* Allocate n of size plen, copy p to n */
1129 n
= snewn(plen
, BignumInt
);
1130 for (j
= 0; j
< plen
; j
++)
1132 for (j
= 1; j
<= (int)p
[0]; j
++)
1135 /* Main computation */
1136 internal_mod(n
, plen
, m
, mlen
, quotient
, mshift
);
1138 /* Fixup result in case the modulus was shifted */
1140 for (i
= plen
- mlen
- 1; i
< plen
- 1; i
++)
1141 n
[i
] = (n
[i
] << mshift
) | (n
[i
+ 1] >> (BIGNUM_INT_BITS
- mshift
));
1142 n
[plen
- 1] = n
[plen
- 1] << mshift
;
1143 internal_mod(n
, plen
, m
, mlen
, quotient
, 0);
1144 for (i
= plen
- 1; i
>= plen
- mlen
; i
--)
1145 n
[i
] = (n
[i
] >> mshift
) | (n
[i
- 1] << (BIGNUM_INT_BITS
- mshift
));
1148 /* Copy result to buffer */
1150 for (i
= 1; i
<= (int)result
[0]; i
++) {
1152 result
[i
] = j
>= 0 ? n
[j
] : 0;
1156 /* Free temporary arrays */
1157 for (i
= 0; i
< mlen
; i
++)
1160 for (i
= 0; i
< plen
; i
++)
1166 * Decrement a number.
1168 void decbn(Bignum bn
)
1171 while (i
< (int)bn
[0] && bn
[i
] == 0)
1172 bn
[i
++] = BIGNUM_INT_MASK
;
1176 Bignum
bignum_from_bytes(const unsigned char *data
, int nbytes
)
1181 w
= (nbytes
+ BIGNUM_INT_BYTES
- 1) / BIGNUM_INT_BYTES
; /* bytes->words */
1184 for (i
= 1; i
<= w
; i
++)
1186 for (i
= nbytes
; i
--;) {
1187 unsigned char byte
= *data
++;
1188 result
[1 + i
/ BIGNUM_INT_BYTES
] |= byte
<< (8*i
% BIGNUM_INT_BITS
);
1191 while (result
[0] > 1 && result
[result
[0]] == 0)
1197 * Read an SSH-1-format bignum from a data buffer. Return the number
1198 * of bytes consumed, or -1 if there wasn't enough data.
1200 int ssh1_read_bignum(const unsigned char *data
, int len
, Bignum
* result
)
1202 const unsigned char *p
= data
;
1210 for (i
= 0; i
< 2; i
++)
1211 w
= (w
<< 8) + *p
++;
1212 b
= (w
+ 7) / 8; /* bits -> bytes */
1217 if (!result
) /* just return length */
1220 *result
= bignum_from_bytes(p
, b
);
1222 return p
+ b
- data
;
1226 * Return the bit count of a bignum, for SSH-1 encoding.
1228 int bignum_bitcount(Bignum bn
)
1230 int bitcount
= bn
[0] * BIGNUM_INT_BITS
- 1;
1231 while (bitcount
>= 0
1232 && (bn
[bitcount
/ BIGNUM_INT_BITS
+ 1] >> (bitcount
% BIGNUM_INT_BITS
)) == 0) bitcount
--;
1233 return bitcount
+ 1;
1237 * Return the byte length of a bignum when SSH-1 encoded.
1239 int ssh1_bignum_length(Bignum bn
)
1241 return 2 + (bignum_bitcount(bn
) + 7) / 8;
1245 * Return the byte length of a bignum when SSH-2 encoded.
1247 int ssh2_bignum_length(Bignum bn
)
1249 return 4 + (bignum_bitcount(bn
) + 8) / 8;
1253 * Return a byte from a bignum; 0 is least significant, etc.
1255 int bignum_byte(Bignum bn
, int i
)
1257 if (i
>= (int)(BIGNUM_INT_BYTES
* bn
[0]))
1258 return 0; /* beyond the end */
1260 return (bn
[i
/ BIGNUM_INT_BYTES
+ 1] >>
1261 ((i
% BIGNUM_INT_BYTES
)*8)) & 0xFF;
1265 * Return a bit from a bignum; 0 is least significant, etc.
1267 int bignum_bit(Bignum bn
, int i
)
1269 if (i
>= (int)(BIGNUM_INT_BITS
* bn
[0]))
1270 return 0; /* beyond the end */
1272 return (bn
[i
/ BIGNUM_INT_BITS
+ 1] >> (i
% BIGNUM_INT_BITS
)) & 1;
1276 * Set a bit in a bignum; 0 is least significant, etc.
1278 void bignum_set_bit(Bignum bn
, int bitnum
, int value
)
1280 if (bitnum
>= (int)(BIGNUM_INT_BITS
* bn
[0]))
1281 abort(); /* beyond the end */
1283 int v
= bitnum
/ BIGNUM_INT_BITS
+ 1;
1284 int mask
= 1 << (bitnum
% BIGNUM_INT_BITS
);
1293 * Write a SSH-1-format bignum into a buffer. It is assumed the
1294 * buffer is big enough. Returns the number of bytes used.
1296 int ssh1_write_bignum(void *data
, Bignum bn
)
1298 unsigned char *p
= data
;
1299 int len
= ssh1_bignum_length(bn
);
1301 int bitc
= bignum_bitcount(bn
);
1303 *p
++ = (bitc
>> 8) & 0xFF;
1304 *p
++ = (bitc
) & 0xFF;
1305 for (i
= len
- 2; i
--;)
1306 *p
++ = bignum_byte(bn
, i
);
1311 * Compare two bignums. Returns like strcmp.
1313 int bignum_cmp(Bignum a
, Bignum b
)
1315 int amax
= a
[0], bmax
= b
[0];
1316 int i
= (amax
> bmax ? amax
: bmax
);
1318 BignumInt aval
= (i
> amax ?
0 : a
[i
]);
1319 BignumInt bval
= (i
> bmax ?
0 : b
[i
]);
1330 * Right-shift one bignum to form another.
1332 Bignum
bignum_rshift(Bignum a
, int shift
)
1335 int i
, shiftw
, shiftb
, shiftbb
, bits
;
1338 bits
= bignum_bitcount(a
) - shift
;
1339 ret
= newbn((bits
+ BIGNUM_INT_BITS
- 1) / BIGNUM_INT_BITS
);
1342 shiftw
= shift
/ BIGNUM_INT_BITS
;
1343 shiftb
= shift
% BIGNUM_INT_BITS
;
1344 shiftbb
= BIGNUM_INT_BITS
- shiftb
;
1346 ai1
= a
[shiftw
+ 1];
1347 for (i
= 1; i
<= (int)ret
[0]; i
++) {
1349 ai1
= (i
+ shiftw
+ 1 <= (int)a
[0] ? a
[i
+ shiftw
+ 1] : 0);
1350 ret
[i
] = ((ai
>> shiftb
) | (ai1
<< shiftbb
)) & BIGNUM_INT_MASK
;
1358 * Non-modular multiplication and addition.
1360 Bignum
bigmuladd(Bignum a
, Bignum b
, Bignum addend
)
1362 int alen
= a
[0], blen
= b
[0];
1363 int mlen
= (alen
> blen ? alen
: blen
);
1364 int rlen
, i
, maxspot
;
1366 BignumInt
*workspace
;
1369 /* mlen space for a, mlen space for b, 2*mlen for result,
1370 * plus scratch space for multiplication */
1371 wslen
= mlen
* 4 + mul_compute_scratch(mlen
);
1372 workspace
= snewn(wslen
, BignumInt
);
1373 for (i
= 0; i
< mlen
; i
++) {
1374 workspace
[0 * mlen
+ i
] = (mlen
- i
<= (int)a
[0] ? a
[mlen
- i
] : 0);
1375 workspace
[1 * mlen
+ i
] = (mlen
- i
<= (int)b
[0] ? b
[mlen
- i
] : 0);
1378 internal_mul(workspace
+ 0 * mlen
, workspace
+ 1 * mlen
,
1379 workspace
+ 2 * mlen
, mlen
, workspace
+ 4 * mlen
);
1381 /* now just copy the result back */
1382 rlen
= alen
+ blen
+ 1;
1383 if (addend
&& rlen
<= (int)addend
[0])
1384 rlen
= addend
[0] + 1;
1387 for (i
= 1; i
<= (int)ret
[0]; i
++) {
1388 ret
[i
] = (i
<= 2 * mlen ? workspace
[4 * mlen
- i
] : 0);
1394 /* now add in the addend, if any */
1396 BignumDblInt carry
= 0;
1397 for (i
= 1; i
<= rlen
; i
++) {
1398 carry
+= (i
<= (int)ret
[0] ? ret
[i
] : 0);
1399 carry
+= (i
<= (int)addend
[0] ? addend
[i
] : 0);
1400 ret
[i
] = (BignumInt
) carry
& BIGNUM_INT_MASK
;
1401 carry
>>= BIGNUM_INT_BITS
;
1402 if (ret
[i
] != 0 && i
> maxspot
)
1408 for (i
= 0; i
< wslen
; i
++)
1415 * Non-modular multiplication.
1417 Bignum
bigmul(Bignum a
, Bignum b
)
1419 return bigmuladd(a
, b
, NULL
);
1425 Bignum
bigadd(Bignum a
, Bignum b
)
1427 int alen
= a
[0], blen
= b
[0];
1428 int rlen
= (alen
> blen ? alen
: blen
) + 1;
1437 for (i
= 1; i
<= rlen
; i
++) {
1438 carry
+= (i
<= (int)a
[0] ? a
[i
] : 0);
1439 carry
+= (i
<= (int)b
[0] ? b
[i
] : 0);
1440 ret
[i
] = (BignumInt
) carry
& BIGNUM_INT_MASK
;
1441 carry
>>= BIGNUM_INT_BITS
;
1442 if (ret
[i
] != 0 && i
> maxspot
)
1451 * Subtraction. Returns a-b, or NULL if the result would come out
1452 * negative (recall that this entire bignum module only handles
1453 * positive numbers).
1455 Bignum
bigsub(Bignum a
, Bignum b
)
1457 int alen
= a
[0], blen
= b
[0];
1458 int rlen
= (alen
> blen ? alen
: blen
);
1467 for (i
= 1; i
<= rlen
; i
++) {
1468 carry
+= (i
<= (int)a
[0] ? a
[i
] : 0);
1469 carry
+= (i
<= (int)b
[0] ? b
[i
] ^ BIGNUM_INT_MASK
: BIGNUM_INT_MASK
);
1470 ret
[i
] = (BignumInt
) carry
& BIGNUM_INT_MASK
;
1471 carry
>>= BIGNUM_INT_BITS
;
1472 if (ret
[i
] != 0 && i
> maxspot
)
1486 * Create a bignum which is the bitmask covering another one. That
1487 * is, the smallest integer which is >= N and is also one less than
1490 Bignum
bignum_bitmask(Bignum n
)
1492 Bignum ret
= copybn(n
);
1497 while (n
[i
] == 0 && i
> 0)
1500 return ret
; /* input was zero */
1506 ret
[i
] = BIGNUM_INT_MASK
;
1511 * Convert a (max 32-bit) long into a bignum.
1513 Bignum
bignum_from_long(unsigned long nn
)
1516 BignumDblInt n
= nn
;
1519 ret
[1] = (BignumInt
)(n
& BIGNUM_INT_MASK
);
1520 ret
[2] = (BignumInt
)((n
>> BIGNUM_INT_BITS
) & BIGNUM_INT_MASK
);
1522 ret
[0] = (ret
[2] ?
2 : 1);
1527 * Add a long to a bignum.
1529 Bignum
bignum_add_long(Bignum number
, unsigned long addendx
)
1531 Bignum ret
= newbn(number
[0] + 1);
1533 BignumDblInt carry
= 0, addend
= addendx
;
1535 for (i
= 1; i
<= (int)ret
[0]; i
++) {
1536 carry
+= addend
& BIGNUM_INT_MASK
;
1537 carry
+= (i
<= (int)number
[0] ? number
[i
] : 0);
1538 addend
>>= BIGNUM_INT_BITS
;
1539 ret
[i
] = (BignumInt
) carry
& BIGNUM_INT_MASK
;
1540 carry
>>= BIGNUM_INT_BITS
;
1549 * Compute the residue of a bignum, modulo a (max 16-bit) short.
1551 unsigned short bignum_mod_short(Bignum number
, unsigned short modulus
)
1553 BignumDblInt mod
, r
;
1558 for (i
= number
[0]; i
> 0; i
--)
1559 r
= (r
* (BIGNUM_TOP_BIT
% mod
) * 2 + number
[i
] % mod
) % mod
;
1560 return (unsigned short) r
;
1564 void diagbn(char *prefix
, Bignum md
)
1566 int i
, nibbles
, morenibbles
;
1567 static const char hex
[] = "0123456789ABCDEF";
1569 debug(("%s0x", prefix ? prefix
: ""));
1571 nibbles
= (3 + bignum_bitcount(md
)) / 4;
1574 morenibbles
= 4 * md
[0] - nibbles
;
1575 for (i
= 0; i
< morenibbles
; i
++)
1577 for (i
= nibbles
; i
--;)
1579 hex
[(bignum_byte(md
, i
/ 2) >> (4 * (i
% 2))) & 0xF]));
1589 Bignum
bigdiv(Bignum a
, Bignum b
)
1591 Bignum q
= newbn(a
[0]);
1592 bigdivmod(a
, b
, NULL
, q
);
1599 Bignum
bigmod(Bignum a
, Bignum b
)
1601 Bignum r
= newbn(b
[0]);
1602 bigdivmod(a
, b
, r
, NULL
);
1607 * Greatest common divisor.
1609 Bignum
biggcd(Bignum av
, Bignum bv
)
1611 Bignum a
= copybn(av
);
1612 Bignum b
= copybn(bv
);
1614 while (bignum_cmp(b
, Zero
) != 0) {
1615 Bignum t
= newbn(b
[0]);
1616 bigdivmod(a
, b
, t
, NULL
);
1617 while (t
[0] > 1 && t
[t
[0]] == 0)
1629 * Modular inverse, using Euclid's extended algorithm.
1631 Bignum
modinv(Bignum number
, Bignum modulus
)
1633 Bignum a
= copybn(modulus
);
1634 Bignum b
= copybn(number
);
1635 Bignum xp
= copybn(Zero
);
1636 Bignum x
= copybn(One
);
1639 while (bignum_cmp(b
, One
) != 0) {
1640 Bignum t
= newbn(b
[0]);
1641 Bignum q
= newbn(a
[0]);
1642 bigdivmod(a
, b
, t
, q
);
1643 while (t
[0] > 1 && t
[t
[0]] == 0)
1650 x
= bigmuladd(q
, xp
, t
);
1660 /* now we know that sign * x == 1, and that x < modulus */
1662 /* set a new x to be modulus - x */
1663 Bignum newx
= newbn(modulus
[0]);
1664 BignumInt carry
= 0;
1668 for (i
= 1; i
<= (int)newx
[0]; i
++) {
1669 BignumInt aword
= (i
<= (int)modulus
[0] ? modulus
[i
] : 0);
1670 BignumInt bword
= (i
<= (int)x
[0] ? x
[i
] : 0);
1671 newx
[i
] = aword
- bword
- carry
;
1673 carry
= carry ?
(newx
[i
] >= bword
) : (newx
[i
] > bword
);
1687 * Render a bignum into decimal. Return a malloced string holding
1688 * the decimal representation.
1690 char *bignum_decimal(Bignum x
)
1692 int ndigits
, ndigit
;
1696 BignumInt
*workspace
;
1699 * First, estimate the number of digits. Since log(10)/log(2)
1700 * is just greater than 93/28 (the joys of continued fraction
1701 * approximations...) we know that for every 93 bits, we need
1702 * at most 28 digits. This will tell us how much to malloc.
1704 * Formally: if x has i bits, that means x is strictly less
1705 * than 2^i. Since 2 is less than 10^(28/93), this is less than
1706 * 10^(28i/93). We need an integer power of ten, so we must
1707 * round up (rounding down might make it less than x again).
1708 * Therefore if we multiply the bit count by 28/93, rounding
1709 * up, we will have enough digits.
1711 * i=0 (i.e., x=0) is an irritating special case.
1713 i
= bignum_bitcount(x
);
1715 ndigits
= 1; /* x = 0 */
1717 ndigits
= (28 * i
+ 92) / 93; /* multiply by 28/93 and round up */
1718 ndigits
++; /* allow for trailing \0 */
1719 ret
= snewn(ndigits
, char);
1722 * Now allocate some workspace to hold the binary form as we
1723 * repeatedly divide it by ten. Initialise this to the
1724 * big-endian form of the number.
1726 workspace
= snewn(x
[0], BignumInt
);
1727 for (i
= 0; i
< (int)x
[0]; i
++)
1728 workspace
[i
] = x
[x
[0] - i
];
1731 * Next, write the decimal number starting with the last digit.
1732 * We use ordinary short division, dividing 10 into the
1735 ndigit
= ndigits
- 1;
1740 for (i
= 0; i
< (int)x
[0]; i
++) {
1741 carry
= (carry
<< BIGNUM_INT_BITS
) + workspace
[i
];
1742 workspace
[i
] = (BignumInt
) (carry
/ 10);
1747 ret
[--ndigit
] = (char) (carry
+ '0');
1751 * There's a chance we've fallen short of the start of the
1752 * string. Correct if so.
1755 memmove(ret
, ret
+ ndigit
, ndigits
- ndigit
);
1771 * gcc -Wall -g -O0 -DTESTBN -o testbn sshbn.c misc.c conf.c tree234.c unix/uxmisc.c -I. -I unix -I charset
1773 * Then feed to this program's standard input the output of
1774 * testdata/bignum.py .
1777 void modalfatalbox(char *p
, ...)
1780 fprintf(stderr
, "FATAL ERROR: ");
1782 vfprintf(stderr
, p
, ap
);
1784 fputc('\n', stderr
);
1788 #define fromxdigit(c) ( (c)>'9' ? ((c)&0xDF) - 'A' + 10 : (c) - '0' )
1790 int main(int argc
, char **argv
)
1794 int passes
= 0, fails
= 0;
1796 while ((buf
= fgetline(stdin
)) != NULL
) {
1797 int maxlen
= strlen(buf
);
1798 unsigned char *data
= snewn(maxlen
, unsigned char);
1799 unsigned char *ptrs
[5], *q
;
1808 while (*bufp
&& !isspace((unsigned char)*bufp
))
1817 while (*bufp
&& !isxdigit((unsigned char)*bufp
))
1824 while (*bufp
&& isxdigit((unsigned char)*bufp
))
1828 if (ptrnum
>= lenof(ptrs
))
1832 for (i
= -((end
- start
) & 1); i
< end
-start
; i
+= 2) {
1833 unsigned char val
= (i
< 0 ?
0 : fromxdigit(start
[i
]));
1834 val
= val
* 16 + fromxdigit(start
[i
+1]);
1841 if (!strcmp(buf
, "mul")) {
1845 printf("%d: mul with %d parameters, expected 3\n", line
, ptrnum
);
1848 a
= bignum_from_bytes(ptrs
[0], ptrs
[1]-ptrs
[0]);
1849 b
= bignum_from_bytes(ptrs
[1], ptrs
[2]-ptrs
[1]);
1850 c
= bignum_from_bytes(ptrs
[2], ptrs
[3]-ptrs
[2]);
1853 if (bignum_cmp(c
, p
) == 0) {
1856 char *as
= bignum_decimal(a
);
1857 char *bs
= bignum_decimal(b
);
1858 char *cs
= bignum_decimal(c
);
1859 char *ps
= bignum_decimal(p
);
1861 printf("%d: fail: %s * %s gave %s expected %s\n",
1862 line
, as
, bs
, ps
, cs
);
1874 } else if (!strcmp(buf
, "modmul")) {
1875 Bignum a
, b
, m
, c
, p
;
1878 printf("%d: modmul with %d parameters, expected 4\n",
1882 a
= bignum_from_bytes(ptrs
[0], ptrs
[1]-ptrs
[0]);
1883 b
= bignum_from_bytes(ptrs
[1], ptrs
[2]-ptrs
[1]);
1884 m
= bignum_from_bytes(ptrs
[2], ptrs
[3]-ptrs
[2]);
1885 c
= bignum_from_bytes(ptrs
[3], ptrs
[4]-ptrs
[3]);
1886 p
= modmul(a
, b
, m
);
1888 if (bignum_cmp(c
, p
) == 0) {
1891 char *as
= bignum_decimal(a
);
1892 char *bs
= bignum_decimal(b
);
1893 char *ms
= bignum_decimal(m
);
1894 char *cs
= bignum_decimal(c
);
1895 char *ps
= bignum_decimal(p
);
1897 printf("%d: fail: %s * %s mod %s gave %s expected %s\n",
1898 line
, as
, bs
, ms
, ps
, cs
);
1912 } else if (!strcmp(buf
, "pow")) {
1913 Bignum base
, expt
, modulus
, expected
, answer
;
1916 printf("%d: mul with %d parameters, expected 4\n", line
, ptrnum
);
1920 base
= bignum_from_bytes(ptrs
[0], ptrs
[1]-ptrs
[0]);
1921 expt
= bignum_from_bytes(ptrs
[1], ptrs
[2]-ptrs
[1]);
1922 modulus
= bignum_from_bytes(ptrs
[2], ptrs
[3]-ptrs
[2]);
1923 expected
= bignum_from_bytes(ptrs
[3], ptrs
[4]-ptrs
[3]);
1924 answer
= modpow(base
, expt
, modulus
);
1926 if (bignum_cmp(expected
, answer
) == 0) {
1929 char *as
= bignum_decimal(base
);
1930 char *bs
= bignum_decimal(expt
);
1931 char *cs
= bignum_decimal(modulus
);
1932 char *ds
= bignum_decimal(answer
);
1933 char *ps
= bignum_decimal(expected
);
1935 printf("%d: fail: %s ^ %s mod %s gave %s expected %s\n",
1936 line
, as
, bs
, cs
, ds
, ps
);
1951 printf("%d: unrecognised test keyword: '%s'\n", line
, buf
);
1959 printf("passed %d failed %d total %d\n", passes
, fails
, passes
+fails
);