0313071af536a880e16d991cb5e853982ca558c7
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 * little-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
= 0; i
< len
; 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 little-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
= 0; i
< len
; 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;
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
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
[len
- 1 - i
]);
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
[len
- 1 - i
]);
285 internal_mul(a
+ botlen
, b
+ botlen
, c
+ 2*botlen
, toplen
, scratch
);
288 for (i
= 0; i
< 2*toplen
; i
++) {
289 printf("%0*x", BIGNUM_INT_BITS
/4, c
[2*len
- 1 - i
]);
295 internal_mul(a
, b
, c
, botlen
, scratch
);
298 for (i
= 0; i
< 2*botlen
; i
++) {
299 printf("%0*x", BIGNUM_INT_BITS
/4, c
[2*botlen
- 1 - i
]);
304 /* Zero padding. botlen exceeds toplen by at most 1, and we'll set
305 * the extra carry explicitly below, so we only need to zero at most
306 * one of the top words here.
308 scratch
[midlen
- 2] = scratch
[2*midlen
- 2] = 0;
310 for (i
= 0; i
< toplen
; i
++) {
311 scratch
[i
] = a
[i
+ botlen
]; /* a_1 */
312 scratch
[midlen
+ i
] = b
[i
+ botlen
]; /* b_1 */
315 /* compute a_1 + a_0 */
316 scratch
[midlen
- 1] = internal_add(scratch
, a
, scratch
, botlen
);
318 printf("a1plusa0 = 0x");
319 for (i
= 0; i
< midlen
; i
++) {
320 printf("%0*x", BIGNUM_INT_BITS
/4, scratch
[midlen
- 1 - i
]);
324 /* compute b_1 + b_0 */
325 scratch
[2*midlen
- 1] = internal_add(scratch
+midlen
, b
,
326 scratch
+midlen
, botlen
);
328 printf("b1plusb0 = 0x");
329 for (i
= 0; i
< midlen
; i
++) {
330 printf("%0*x", BIGNUM_INT_BITS
/4, scratch
[2*midlen
- 1 - i
]);
336 * Now we can do the third multiplication.
338 internal_mul(scratch
, scratch
+ midlen
, scratch
+ 2*midlen
, midlen
,
341 printf("a1plusa0timesb1plusb0 = 0x");
342 for (i
= 0; i
< 2*midlen
; i
++) {
343 printf("%0*x", BIGNUM_INT_BITS
/4, scratch
[4*midlen
- 1 - i
]);
349 * Now we can reuse the first half of 'scratch' to compute the
350 * sum of the outer two coefficients, to subtract from that
351 * product to obtain the middle one.
353 scratch
[2*botlen
- 2] = scratch
[2*botlen
- 1] = 0;
354 for (i
= 0; i
< 2*toplen
; i
++)
355 scratch
[i
] = c
[2*botlen
+ i
];
356 scratch
[2*botlen
] = internal_add(scratch
, c
, scratch
, 2*botlen
);
357 scratch
[2*botlen
+ 1] = 0;
359 printf("a1b1plusa0b0 = 0x");
360 for (i
= 0; i
< 2*midlen
; i
++) {
361 printf("%0*x", BIGNUM_INT_BITS
/4, scratch
[2*midlen
- 1 - i
]);
366 internal_sub(scratch
+ 2*midlen
, scratch
, scratch
, 2*midlen
);
368 printf("a1b0plusa0b1 = 0x");
369 for (i
= 0; i
< 2*midlen
; i
++) {
370 printf("%0*x", BIGNUM_INT_BITS
/4, scratch
[4*midlen
- 1 - i
]);
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.
381 carry
= internal_add(c
+ botlen
, scratch
, c
+ botlen
, 2*midlen
);
382 i
= botlen
+ 2*midlen
;
386 c
[i
] = (BignumInt
)carry
;
387 carry
>>= BIGNUM_INT_BITS
;
392 for (i
= 0; i
< 2*len
; i
++) {
393 printf("%0*x", BIGNUM_INT_BITS
/4, c
[2*len
- i
]);
402 const BignumInt
*ap
, *alim
= a
+ len
, *bp
, *blim
= b
+ len
;
406 * Multiply in the ordinary O(N^2) way.
409 for (i
= 0; i
< 2 * len
; i
++)
412 for (cps
= c
, ap
= a
; ap
< alim
; ap
++, cps
++) {
414 for (cp
= cps
, bp
= b
, i
= blim
- bp
; i
--; bp
++, cp
++) {
415 t
= (MUL_WORD(*ap
, *bp
) + carry
) + *cp
;
417 carry
= (BignumInt
)(t
>> BIGNUM_INT_BITS
);
425 * Variant form of internal_mul used for the initial step of
426 * Montgomery reduction. Only bothers outputting 'len' words
427 * (everything above that is thrown away).
429 static void internal_mul_low(const BignumInt
*a
, const BignumInt
*b
,
430 BignumInt
*c
, int len
, BignumInt
*scratch
)
432 if (len
> KARATSUBA_THRESHOLD
) {
436 * Karatsuba-aware version of internal_mul_low. As before, we
437 * express each input value as a shifted combination of two
443 * Then the full product is, as before,
445 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
447 * Provided we choose D on the large side (so that a_0 and b_0
448 * are _at least_ as long as a_1 and b_1), we don't need the
449 * topmost term at all, and we only need half of the middle
450 * term. So there's no point in doing the proper Karatsuba
451 * optimisation which computes the middle term using the top
452 * one, because we'd take as long computing the top one as
453 * just computing the middle one directly.
455 * So instead, we do a much more obvious thing: we call the
456 * fully optimised internal_mul to compute a_0 b_0, and we
457 * recursively call ourself to compute the _bottom halves_ of
458 * a_1 b_0 and a_0 b_1, each of which we add into the result
459 * in the obvious way.
461 * In other words, there's no actual Karatsuba _optimisation_
462 * in this function; the only benefit in doing it this way is
463 * that we call internal_mul proper for a large part of the
464 * work, and _that_ can optimise its operation.
467 int toplen
= len
/2, botlen
= len
- toplen
; /* botlen is the bigger */
470 * Scratch space for the various bits and pieces we're going
471 * to be adding together: we need botlen*2 words for a_0 b_0
472 * (though we may end up throwing away its topmost word), and
473 * toplen words for each of a_1 b_0 and a_0 b_1. That adds up
478 internal_mul(a
, b
, scratch
+ 2*toplen
, botlen
, scratch
+ 2*len
);
481 internal_mul_low(a
+ botlen
, b
, scratch
+ toplen
, toplen
,
485 internal_mul_low(a
, b
+ botlen
, scratch
, toplen
, scratch
+ 2*len
);
487 /* Copy the bottom half of the big coefficient into place */
488 for (i
= 0; i
< botlen
; i
++)
489 c
[i
] = scratch
[2*toplen
+ i
];
491 /* Add the two small coefficients, throwing away the returned carry */
492 internal_add(scratch
, scratch
+ toplen
, scratch
, toplen
);
494 /* And add that to the large coefficient, leaving the result in c. */
495 internal_add(scratch
, scratch
+ 2*toplen
+ botlen
,
502 const BignumInt
*ap
, *alim
= a
+ len
, *bp
;
503 BignumInt
*cp
, *cps
, *clim
= c
+ len
;
506 * Multiply in the ordinary O(N^2) way.
509 for (i
= 0; i
< len
; i
++)
512 for (cps
= c
, ap
= a
; ap
< alim
; ap
++, cps
++) {
514 for (cp
= cps
, bp
= b
, i
= clim
- cp
; i
--; bp
++, cp
++) {
515 t
= (MUL_WORD(*ap
, *bp
) + carry
) + *cp
;
517 carry
= (BignumInt
)(t
>> BIGNUM_INT_BITS
);
524 * Montgomery reduction. Expects x to be a little-endian array of 2*len
525 * BignumInts whose value satisfies 0 <= x < rn (where r = 2^(len *
526 * BIGNUM_INT_BITS) is the Montgomery base). Returns in the same array
527 * a value x' which is congruent to xr^{-1} mod n, and satisfies 0 <=
530 * 'n' and 'mninv' should be little-endian arrays of 'len' BignumInts
531 * each, containing respectively n and the multiplicative inverse of
534 * 'tmp' is an array of BignumInt used as scratch space, of length at
535 * least 3*len + mul_compute_scratch(len).
537 static void monty_reduce(BignumInt
*x
, const BignumInt
*n
,
538 const BignumInt
*mninv
, BignumInt
*tmp
, int len
)
544 * Multiply x by (-n)^{-1} mod r. This gives us a value m such
545 * that mn is congruent to -x mod r. Hence, mn+x is an exact
546 * multiple of r, and is also (obviously) congruent to x mod n.
548 internal_mul_low(x
, mninv
, tmp
, len
, tmp
+ 3*len
);
551 * Compute t = (mn+x)/r in ordinary, non-modular, integer
552 * arithmetic. By construction this is exact, and is congruent mod
553 * n to x * r^{-1}, i.e. the answer we want.
555 * The following multiply leaves that answer in the _most_
556 * significant half of the 'x' array, so then we must shift it
559 internal_mul(tmp
, n
, tmp
+len
, len
, tmp
+ 3*len
);
560 carry
= internal_add(x
, tmp
+len
, x
, 2*len
);
561 for (i
= 0; i
< len
; i
++)
562 x
[i
] = x
[len
+ i
], x
[len
+ i
] = 0;
565 * Reduce t mod n. This doesn't require a full-on division by n,
566 * but merely a test and single optional subtraction, since we can
567 * show that 0 <= t < 2n.
570 * + we computed m mod r, so 0 <= m < r.
571 * + so 0 <= mn < rn, obviously
572 * + hence we only need 0 <= x < rn to guarantee that 0 <= mn+x < 2rn
573 * + yielding 0 <= (mn+x)/r < 2n as required.
576 for (i
= len
; i
-- > 0; )
580 if (carry
|| i
< 0 || x
[i
] > n
[i
])
581 internal_sub(x
, n
, x
, len
);
584 static void internal_add_shifted(BignumInt
*number
,
585 unsigned n
, int shift
)
587 int word
= 1 + (shift
/ BIGNUM_INT_BITS
);
588 int bshift
= shift
% BIGNUM_INT_BITS
;
591 addend
= (BignumDblInt
)n
<< bshift
;
594 addend
+= number
[word
];
595 number
[word
] = (BignumInt
) addend
& BIGNUM_INT_MASK
;
596 addend
>>= BIGNUM_INT_BITS
;
603 * Input in first alen words of a and first mlen words of m.
604 * Output in first alen words of a
605 * (of which last alen-mlen words will be zero).
606 * The MSW of m MUST have its high bit set.
607 * Quotient is accumulated in the `quotient' array. Quotient parts
608 * are shifted left by `qshift' before adding into quot.
610 static void internal_mod(BignumInt
*a
, int alen
,
611 BignumInt
*m
, int mlen
,
612 BignumInt
*quot
, int qshift
)
624 for (i
= alen
, h
= 0; i
-- >= mlen
; ) {
626 unsigned int q
, r
, c
, ai1
;
633 /* Find q = h:a[i] / m0 */
638 * To illustrate it, suppose a BignumInt is 8 bits, and
639 * we are dividing (say) A1:23:45:67 by A1:B2:C3. Then
640 * our initial division will be 0xA123 / 0xA1, which
641 * will give a quotient of 0x100 and a divide overflow.
642 * However, the invariants in this division algorithm
643 * are not violated, since the full number A1:23:... is
644 * _less_ than the quotient prefix A1:B2:... and so the
645 * following correction loop would have sorted it out.
647 * In this situation we set q to be the largest
648 * quotient we _can_ stomach (0xFF, of course).
652 /* Macro doesn't want an array subscript expression passed
653 * into it (see definition), so use a temporary. */
654 BignumInt tmplo
= a
[i
];
655 DIVMOD_WORD(q
, r
, h
, tmplo
, m0
);
657 /* Refine our estimate of q by looking at
658 h:a[i]:a[i-1] / m0:m1 */
660 if (t
> ((BignumDblInt
) r
<< BIGNUM_INT_BITS
) + ai1
) {
663 r
= (r
+ m0
) & BIGNUM_INT_MASK
; /* overflow? */
664 if (r
>= (BignumDblInt
) m0
&&
665 t
> ((BignumDblInt
) r
<< BIGNUM_INT_BITS
) + ai1
) q
--;
671 /* Subtract q * m from a[i...] */
673 for (k
= 0; k
< mlen
; k
++) {
674 t
= MUL_WORD(q
, m
[k
]);
676 c
= (unsigned)(t
>> BIGNUM_INT_BITS
);
677 if ((BignumInt
) t
> a
[j
+ k
])
679 a
[j
+ k
] -= (BignumInt
) t
;
682 /* Add back m in case of borrow */
685 for (k
= 0; k
< mlen
; k
++) {
688 a
[j
+ k
] = (BignumInt
) t
;
689 t
= t
>> BIGNUM_INT_BITS
;
695 internal_add_shifted(quot
, q
,
696 qshift
+ BIGNUM_INT_BITS
* (i
+ 1 - mlen
));
705 static void shift_left(BignumInt
*x
, int xlen
, int shift
)
711 for (i
= xlen
; --i
> 0; )
712 x
[i
] = (x
[i
] << shift
) | (x
[i
- 1] >> (BIGNUM_INT_BITS
- shift
));
713 x
[0] = x
[0] << shift
;
716 static void shift_right(BignumInt
*x
, int xlen
, int shift
)
723 for (i
= 0; i
< xlen
; i
++)
724 x
[i
] = (x
[i
] >> shift
) | (x
[i
+ 1] << (BIGNUM_INT_BITS
- shift
));
725 x
[i
] = x
[i
] >> shift
;
729 * Compute (base ^ exp) % mod, the pedestrian way.
731 Bignum
modpow_simple(Bignum base_in
, Bignum exp
, Bignum mod
)
733 BignumInt
*a
, *b
, *n
, *m
, *scratch
;
735 int mlen
, scratchlen
, i
, j
;
739 * The most significant word of mod needs to be non-zero. It
740 * should already be, but let's make sure.
742 assert(mod
[mod
[0]] != 0);
745 * Make sure the base is smaller than the modulus, by reducing
746 * it modulo the modulus if not.
748 base
= bigmod(base_in
, mod
);
750 /* Allocate m of size mlen, copy mod to m */
752 m
= snewn(mlen
, BignumInt
);
753 for (j
= 0; j
< mlen
; j
++)
756 /* Shift m left to make msb bit set */
757 for (mshift
= 0; mshift
< BIGNUM_INT_BITS
-1; mshift
++)
758 if ((m
[mlen
- 1] << mshift
) & BIGNUM_TOP_BIT
)
761 shift_left(m
, mlen
, mshift
);
763 /* Allocate n of size mlen, copy base to n */
764 n
= snewn(mlen
, BignumInt
);
765 for (i
= 0; i
< (int)base
[0]; i
++)
767 for (; i
< mlen
; i
++)
770 /* Allocate a and b of size 2*mlen. Set a = 1 */
771 a
= snewn(2 * mlen
, BignumInt
);
772 b
= snewn(2 * mlen
, BignumInt
);
774 for (i
= 1; i
< 2 * mlen
; i
++)
777 /* Scratch space for multiplies */
778 scratchlen
= mul_compute_scratch(mlen
);
779 scratch
= snewn(scratchlen
, BignumInt
);
781 /* Skip leading zero bits of exp. */
783 j
= BIGNUM_INT_BITS
-1;
784 while (i
< (int)exp
[0] && (exp
[exp
[0] - i
] & (1 << j
)) == 0) {
788 j
= BIGNUM_INT_BITS
-1;
792 /* Main computation */
793 while (i
< (int)exp
[0]) {
795 internal_mul(a
, a
, b
, mlen
, scratch
);
796 internal_mod(b
, mlen
* 2, m
, mlen
, NULL
, 0);
797 if ((exp
[exp
[0] - i
] & (1 << j
)) != 0) {
798 internal_mul(b
, n
, a
, mlen
, scratch
);
799 internal_mod(a
, mlen
* 2, m
, mlen
, NULL
, 0);
809 j
= BIGNUM_INT_BITS
-1;
812 /* Fixup result in case the modulus was shifted */
814 shift_left(a
, mlen
+ 1, mshift
);
815 internal_mod(a
, mlen
+ 1, m
, mlen
, NULL
, 0);
816 shift_right(a
, mlen
, mshift
);
819 /* Copy result to buffer */
820 result
= newbn(mod
[0]);
821 for (i
= 0; i
< mlen
; i
++)
822 result
[i
+ 1] = a
[i
];
823 while (result
[0] > 1 && result
[result
[0]] == 0)
826 /* Free temporary arrays */
827 for (i
= 0; i
< 2 * mlen
; i
++)
830 for (i
= 0; i
< scratchlen
; i
++)
833 for (i
= 0; i
< 2 * mlen
; i
++)
836 for (i
= 0; i
< mlen
; i
++)
839 for (i
= 0; i
< mlen
; i
++)
849 * Compute (base ^ exp) % mod. Uses the Montgomery multiplication
850 * technique where possible, falling back to modpow_simple otherwise.
852 Bignum
modpow(Bignum base_in
, Bignum exp
, Bignum mod
)
854 BignumInt
*a
, *b
, *x
, *n
, *mninv
, *scratch
;
855 int len
, scratchlen
, i
, j
;
856 Bignum base
, base2
, r
, rn
, inv
, result
;
859 * The most significant word of mod needs to be non-zero. It
860 * should already be, but let's make sure.
862 assert(mod
[mod
[0]] != 0);
865 * mod had better be odd, or we can't do Montgomery multiplication
866 * using a power of two at all.
869 return modpow_simple(base_in
, exp
, mod
);
872 * Make sure the base is smaller than the modulus, by reducing
873 * it modulo the modulus if not.
875 base
= bigmod(base_in
, mod
);
878 * Compute the inverse of n mod r, for monty_reduce. (In fact we
879 * want the inverse of _minus_ n mod r, but we'll sort that out
883 r
= bn_power_2(BIGNUM_INT_BITS
* len
);
884 inv
= modinv(mod
, r
);
887 * Multiply the base by r mod n, to get it into Montgomery
890 base2
= modmul(base
, r
, mod
);
894 rn
= bigmod(r
, mod
); /* r mod n, i.e. Montgomerified 1 */
896 freebn(r
); /* won't need this any more */
899 * Set up internal arrays of the right lengths containing the base,
900 * the modulus, and the modulus's inverse.
902 n
= snewn(len
, BignumInt
);
903 for (j
= 0; j
< len
; j
++)
906 mninv
= snewn(len
, BignumInt
);
907 for (j
= 0; j
< len
; j
++)
908 mninv
[j
] = (j
< (int)inv
[0] ? inv
[j
+ 1] : 0);
909 freebn(inv
); /* we don't need this copy of it any more */
910 /* Now negate mninv mod r, so it's the inverse of -n rather than +n. */
911 x
= snewn(len
, BignumInt
);
912 for (j
= 0; j
< len
; j
++)
914 internal_sub(x
, mninv
, mninv
, len
);
916 /* x = snewn(len, BignumInt); */ /* already done above */
917 for (j
= 0; j
< len
; j
++)
918 x
[j
] = (j
< (int)base
[0] ? base
[j
+ 1] : 0);
919 freebn(base
); /* we don't need this copy of it any more */
921 a
= snewn(2*len
, BignumInt
);
922 b
= snewn(2*len
, BignumInt
);
923 for (j
= 0; j
< len
; j
++)
924 a
[j
] = (j
< (int)rn
[0] ? rn
[j
+ 1] : 0);
927 /* Scratch space for multiplies */
928 scratchlen
= 3*len
+ mul_compute_scratch(len
);
929 scratch
= snewn(scratchlen
, BignumInt
);
931 /* Skip leading zero bits of exp. */
933 j
= BIGNUM_INT_BITS
-1;
934 while (i
< (int)exp
[0] && (exp
[exp
[0] - i
] & (1 << j
)) == 0) {
938 j
= BIGNUM_INT_BITS
-1;
942 /* Main computation */
943 while (i
< (int)exp
[0]) {
945 internal_mul(a
, a
, b
, len
, scratch
);
946 monty_reduce(b
, n
, mninv
, scratch
, len
);
947 if ((exp
[exp
[0] - i
] & (1 << j
)) != 0) {
948 internal_mul(b
, x
, a
, len
, scratch
);
949 monty_reduce(a
, n
, mninv
, scratch
, len
);
959 j
= BIGNUM_INT_BITS
-1;
963 * Final monty_reduce to get back from the adjusted Montgomery
966 monty_reduce(a
, n
, mninv
, scratch
, len
);
968 /* Copy result to buffer */
969 result
= newbn(mod
[0]);
970 for (i
= 0; i
< len
; i
++)
971 result
[i
+ 1] = a
[i
];
972 while (result
[0] > 1 && result
[result
[0]] == 0)
975 /* Free temporary arrays */
976 for (i
= 0; i
< scratchlen
; i
++)
979 for (i
= 0; i
< 2 * len
; i
++)
982 for (i
= 0; i
< 2 * len
; i
++)
985 for (i
= 0; i
< len
; i
++)
988 for (i
= 0; i
< len
; i
++)
991 for (i
= 0; i
< len
; i
++)
999 * Compute (p * q) % mod.
1000 * The most significant word of mod MUST be non-zero.
1001 * We assume that the result array is the same size as the mod array.
1003 Bignum
modmul(Bignum p
, Bignum q
, Bignum mod
)
1005 BignumInt
*a
, *n
, *m
, *o
, *scratch
;
1006 int mshift
, scratchlen
;
1007 int pqlen
, mlen
, rlen
, i
, j
;
1010 /* Allocate m of size mlen, copy mod to m */
1012 m
= snewn(mlen
, BignumInt
);
1013 for (j
= 0; j
< mlen
; j
++)
1016 /* Shift m left to make msb bit set */
1017 for (mshift
= 0; mshift
< BIGNUM_INT_BITS
-1; mshift
++)
1018 if ((m
[mlen
- 1] << mshift
) & BIGNUM_TOP_BIT
)
1021 shift_left(m
, mlen
, mshift
);
1023 pqlen
= (p
[0] > q
[0] ? p
[0] : q
[0]);
1025 /* Make sure that we're allowing enough space. The shifting below will
1026 * underflow the vectors we allocate if `pqlen' is too small.
1028 if (2*pqlen
<= mlen
)
1031 /* Allocate n of size pqlen, copy p to n */
1032 n
= snewn(pqlen
, BignumInt
);
1033 for (i
= 0; i
< (int)p
[0]; i
++)
1035 for (; i
< pqlen
; i
++)
1038 /* Allocate o of size pqlen, copy q to o */
1039 o
= snewn(pqlen
, BignumInt
);
1040 for (i
= 0; i
< (int)q
[0]; i
++)
1042 for (; i
< pqlen
; i
++)
1045 /* Allocate a of size 2*pqlen for result */
1046 a
= snewn(2 * pqlen
, BignumInt
);
1048 /* Scratch space for multiplies */
1049 scratchlen
= mul_compute_scratch(pqlen
);
1050 scratch
= snewn(scratchlen
, BignumInt
);
1052 /* Main computation */
1053 internal_mul(n
, o
, a
, pqlen
, scratch
);
1054 internal_mod(a
, pqlen
* 2, m
, mlen
, NULL
, 0);
1056 /* Fixup result in case the modulus was shifted */
1058 shift_left(a
, mlen
+ 1, mshift
);
1059 internal_mod(a
, mlen
+ 1, m
, mlen
, NULL
, 0);
1060 shift_right(a
, mlen
, mshift
);
1063 /* Copy result to buffer */
1064 rlen
= (mlen
< pqlen
* 2 ? mlen
: pqlen
* 2);
1065 result
= newbn(rlen
);
1066 for (i
= 0; i
< rlen
; i
++)
1067 result
[i
+ 1] = a
[i
];
1068 while (result
[0] > 1 && result
[result
[0]] == 0)
1071 /* Free temporary arrays */
1072 for (i
= 0; i
< scratchlen
; i
++)
1075 for (i
= 0; i
< 2 * pqlen
; i
++)
1078 for (i
= 0; i
< mlen
; i
++)
1081 for (i
= 0; i
< pqlen
; i
++)
1084 for (i
= 0; i
< pqlen
; i
++)
1093 * The most significant word of mod MUST be non-zero.
1094 * We assume that the result array is the same size as the mod array.
1095 * We optionally write out a quotient if `quotient' is non-NULL.
1096 * We can avoid writing out the result if `result' is NULL.
1098 static void bigdivmod(Bignum p
, Bignum mod
, Bignum result
, Bignum quotient
)
1102 int plen
, mlen
, i
, j
;
1104 /* Allocate m of size mlen, copy mod to m */
1106 m
= snewn(mlen
, BignumInt
);
1107 for (j
= 0; j
< mlen
; j
++)
1110 /* Shift m left to make msb bit set */
1111 for (mshift
= 0; mshift
< BIGNUM_INT_BITS
-1; mshift
++)
1112 if ((m
[mlen
- 1] << mshift
) & BIGNUM_TOP_BIT
)
1115 shift_left(m
, mlen
, mshift
);
1118 /* Ensure plen > mlen */
1122 /* Allocate n of size plen, copy p to n */
1123 n
= snewn(plen
, BignumInt
);
1124 for (i
= 0; i
< (int)p
[0]; i
++)
1126 for (; i
< plen
; i
++)
1129 /* Main computation */
1130 internal_mod(n
, plen
, m
, mlen
, quotient
, mshift
);
1132 /* Fixup result in case the modulus was shifted */
1134 shift_left(n
, mlen
+ 1, mshift
);
1135 internal_mod(n
, plen
, m
, mlen
, quotient
, 0);
1136 shift_right(n
, mlen
, mshift
);
1139 /* Copy result to buffer */
1141 for (i
= 0; i
< (int)result
[0]; i
++)
1142 result
[i
+ 1] = i
< plen ? n
[i
] : 0;
1143 bn_restore_invariant(result
);
1146 /* Free temporary arrays */
1147 for (i
= 0; i
< mlen
; i
++)
1150 for (i
= 0; i
< plen
; i
++)
1156 * Decrement a number.
1158 void decbn(Bignum bn
)
1161 while (i
< (int)bn
[0] && bn
[i
] == 0)
1162 bn
[i
++] = BIGNUM_INT_MASK
;
1166 Bignum
bignum_from_bytes(const unsigned char *data
, int nbytes
)
1171 w
= (nbytes
+ BIGNUM_INT_BYTES
- 1) / BIGNUM_INT_BYTES
; /* bytes->words */
1174 for (i
= 1; i
<= w
; i
++)
1176 for (i
= nbytes
; i
--;) {
1177 unsigned char byte
= *data
++;
1178 result
[1 + i
/ BIGNUM_INT_BYTES
] |= byte
<< (8*i
% BIGNUM_INT_BITS
);
1181 while (result
[0] > 1 && result
[result
[0]] == 0)
1187 * Read an SSH-1-format bignum from a data buffer. Return the number
1188 * of bytes consumed, or -1 if there wasn't enough data.
1190 int ssh1_read_bignum(const unsigned char *data
, int len
, Bignum
* result
)
1192 const unsigned char *p
= data
;
1200 for (i
= 0; i
< 2; i
++)
1201 w
= (w
<< 8) + *p
++;
1202 b
= (w
+ 7) / 8; /* bits -> bytes */
1207 if (!result
) /* just return length */
1210 *result
= bignum_from_bytes(p
, b
);
1212 return p
+ b
- data
;
1216 * Return the bit count of a bignum, for SSH-1 encoding.
1218 int bignum_bitcount(Bignum bn
)
1220 int bitcount
= bn
[0] * BIGNUM_INT_BITS
- 1;
1221 while (bitcount
>= 0
1222 && (bn
[bitcount
/ BIGNUM_INT_BITS
+ 1] >> (bitcount
% BIGNUM_INT_BITS
)) == 0) bitcount
--;
1223 return bitcount
+ 1;
1227 * Return the byte length of a bignum when SSH-1 encoded.
1229 int ssh1_bignum_length(Bignum bn
)
1231 return 2 + (bignum_bitcount(bn
) + 7) / 8;
1235 * Return the byte length of a bignum when SSH-2 encoded.
1237 int ssh2_bignum_length(Bignum bn
)
1239 return 4 + (bignum_bitcount(bn
) + 8) / 8;
1243 * Return a byte from a bignum; 0 is least significant, etc.
1245 int bignum_byte(Bignum bn
, int i
)
1247 if (i
>= (int)(BIGNUM_INT_BYTES
* bn
[0]))
1248 return 0; /* beyond the end */
1250 return (bn
[i
/ BIGNUM_INT_BYTES
+ 1] >>
1251 ((i
% BIGNUM_INT_BYTES
)*8)) & 0xFF;
1255 * Return a bit from a bignum; 0 is least significant, etc.
1257 int bignum_bit(Bignum bn
, int i
)
1259 if (i
>= (int)(BIGNUM_INT_BITS
* bn
[0]))
1260 return 0; /* beyond the end */
1262 return (bn
[i
/ BIGNUM_INT_BITS
+ 1] >> (i
% BIGNUM_INT_BITS
)) & 1;
1266 * Set a bit in a bignum; 0 is least significant, etc.
1268 void bignum_set_bit(Bignum bn
, int bitnum
, int value
)
1270 if (bitnum
>= (int)(BIGNUM_INT_BITS
* bn
[0]))
1271 abort(); /* beyond the end */
1273 int v
= bitnum
/ BIGNUM_INT_BITS
+ 1;
1274 int mask
= 1 << (bitnum
% BIGNUM_INT_BITS
);
1283 * Write a SSH-1-format bignum into a buffer. It is assumed the
1284 * buffer is big enough. Returns the number of bytes used.
1286 int ssh1_write_bignum(void *data
, Bignum bn
)
1288 unsigned char *p
= data
;
1289 int len
= ssh1_bignum_length(bn
);
1291 int bitc
= bignum_bitcount(bn
);
1293 *p
++ = (bitc
>> 8) & 0xFF;
1294 *p
++ = (bitc
) & 0xFF;
1295 for (i
= len
- 2; i
--;)
1296 *p
++ = bignum_byte(bn
, i
);
1301 * Compare two bignums. Returns like strcmp.
1303 int bignum_cmp(Bignum a
, Bignum b
)
1305 int amax
= a
[0], bmax
= b
[0];
1306 int i
= (amax
> bmax ? amax
: bmax
);
1308 BignumInt aval
= (i
> amax ?
0 : a
[i
]);
1309 BignumInt bval
= (i
> bmax ?
0 : b
[i
]);
1320 * Right-shift one bignum to form another.
1322 Bignum
bignum_rshift(Bignum a
, int shift
)
1325 int i
, shiftw
, shiftb
, shiftbb
, bits
;
1328 bits
= bignum_bitcount(a
) - shift
;
1329 ret
= newbn((bits
+ BIGNUM_INT_BITS
- 1) / BIGNUM_INT_BITS
);
1332 shiftw
= shift
/ BIGNUM_INT_BITS
;
1333 shiftb
= shift
% BIGNUM_INT_BITS
;
1334 shiftbb
= BIGNUM_INT_BITS
- shiftb
;
1336 ai1
= a
[shiftw
+ 1];
1337 for (i
= 1; i
<= (int)ret
[0]; i
++) {
1339 ai1
= (i
+ shiftw
+ 1 <= (int)a
[0] ? a
[i
+ shiftw
+ 1] : 0);
1340 ret
[i
] = ((ai
>> shiftb
) | (ai1
<< shiftbb
)) & BIGNUM_INT_MASK
;
1348 * Non-modular multiplication and addition.
1350 Bignum
bigmuladd(Bignum a
, Bignum b
, Bignum addend
)
1352 int alen
= a
[0], blen
= b
[0];
1353 int mlen
= (alen
> blen ? alen
: blen
);
1354 int rlen
, i
, maxspot
;
1356 BignumInt
*workspace
;
1359 /* mlen space for a, mlen space for b, 2*mlen for result,
1360 * plus scratch space for multiplication */
1361 wslen
= mlen
* 4 + mul_compute_scratch(mlen
);
1362 workspace
= snewn(wslen
, BignumInt
);
1363 for (i
= 0; i
< mlen
; i
++) {
1364 workspace
[0 * mlen
+ i
] = i
< (int)a
[0] ? a
[i
+ 1] : 0;
1365 workspace
[1 * mlen
+ i
] = i
< (int)b
[0] ? b
[i
+ 1] : 0;
1368 internal_mul(workspace
+ 0 * mlen
, workspace
+ 1 * mlen
,
1369 workspace
+ 2 * mlen
, mlen
, workspace
+ 4 * mlen
);
1371 /* now just copy the result back */
1372 rlen
= alen
+ blen
+ 1;
1373 if (addend
&& rlen
<= (int)addend
[0])
1374 rlen
= addend
[0] + 1;
1377 for (i
= 0; i
< (int)ret
[0]; i
++) {
1378 ret
[i
+ 1] = (i
< 2 * mlen ? workspace
[2 * mlen
+ i
] : 0);
1379 if (ret
[i
+ 1] != 0)
1384 /* now add in the addend, if any */
1386 BignumDblInt carry
= 0;
1387 for (i
= 1; i
<= rlen
; i
++) {
1388 carry
+= (i
<= (int)ret
[0] ? ret
[i
] : 0);
1389 carry
+= (i
<= (int)addend
[0] ? addend
[i
] : 0);
1390 ret
[i
] = (BignumInt
) carry
& BIGNUM_INT_MASK
;
1391 carry
>>= BIGNUM_INT_BITS
;
1392 if (ret
[i
] != 0 && i
> maxspot
)
1398 for (i
= 0; i
< wslen
; i
++)
1405 * Non-modular multiplication.
1407 Bignum
bigmul(Bignum a
, Bignum b
)
1409 return bigmuladd(a
, b
, NULL
);
1415 Bignum
bigadd(Bignum a
, Bignum b
)
1417 int alen
= a
[0], blen
= b
[0];
1418 int rlen
= (alen
> blen ? alen
: blen
) + 1;
1427 for (i
= 1; i
<= rlen
; i
++) {
1428 carry
+= (i
<= (int)a
[0] ? a
[i
] : 0);
1429 carry
+= (i
<= (int)b
[0] ? b
[i
] : 0);
1430 ret
[i
] = (BignumInt
) carry
& BIGNUM_INT_MASK
;
1431 carry
>>= BIGNUM_INT_BITS
;
1432 if (ret
[i
] != 0 && i
> maxspot
)
1441 * Subtraction. Returns a-b, or NULL if the result would come out
1442 * negative (recall that this entire bignum module only handles
1443 * positive numbers).
1445 Bignum
bigsub(Bignum a
, Bignum b
)
1447 int alen
= a
[0], blen
= b
[0];
1448 int rlen
= (alen
> blen ? alen
: blen
);
1457 for (i
= 1; i
<= rlen
; i
++) {
1458 carry
+= (i
<= (int)a
[0] ? a
[i
] : 0);
1459 carry
+= (i
<= (int)b
[0] ? b
[i
] ^ BIGNUM_INT_MASK
: BIGNUM_INT_MASK
);
1460 ret
[i
] = (BignumInt
) carry
& BIGNUM_INT_MASK
;
1461 carry
>>= BIGNUM_INT_BITS
;
1462 if (ret
[i
] != 0 && i
> maxspot
)
1476 * Create a bignum which is the bitmask covering another one. That
1477 * is, the smallest integer which is >= N and is also one less than
1480 Bignum
bignum_bitmask(Bignum n
)
1482 Bignum ret
= copybn(n
);
1487 while (n
[i
] == 0 && i
> 0)
1490 return ret
; /* input was zero */
1496 ret
[i
] = BIGNUM_INT_MASK
;
1501 * Convert a (max 32-bit) long into a bignum.
1503 Bignum
bignum_from_long(unsigned long nn
)
1506 BignumDblInt n
= nn
;
1509 ret
[1] = (BignumInt
)(n
& BIGNUM_INT_MASK
);
1510 ret
[2] = (BignumInt
)((n
>> BIGNUM_INT_BITS
) & BIGNUM_INT_MASK
);
1512 ret
[0] = (ret
[2] ?
2 : 1);
1517 * Add a long to a bignum.
1519 Bignum
bignum_add_long(Bignum number
, unsigned long addendx
)
1521 Bignum ret
= newbn(number
[0] + 1);
1523 BignumDblInt carry
= 0, addend
= addendx
;
1525 for (i
= 1; i
<= (int)ret
[0]; i
++) {
1526 carry
+= addend
& BIGNUM_INT_MASK
;
1527 carry
+= (i
<= (int)number
[0] ? number
[i
] : 0);
1528 addend
>>= BIGNUM_INT_BITS
;
1529 ret
[i
] = (BignumInt
) carry
& BIGNUM_INT_MASK
;
1530 carry
>>= BIGNUM_INT_BITS
;
1539 * Compute the residue of a bignum, modulo a (max 16-bit) short.
1541 unsigned short bignum_mod_short(Bignum number
, unsigned short modulus
)
1543 BignumDblInt mod
, r
;
1548 for (i
= number
[0]; i
> 0; i
--)
1549 r
= (r
* (BIGNUM_TOP_BIT
% mod
) * 2 + number
[i
] % mod
) % mod
;
1550 return (unsigned short) r
;
1554 void diagbn(char *prefix
, Bignum md
)
1556 int i
, nibbles
, morenibbles
;
1557 static const char hex
[] = "0123456789ABCDEF";
1559 debug(("%s0x", prefix ? prefix
: ""));
1561 nibbles
= (3 + bignum_bitcount(md
)) / 4;
1564 morenibbles
= 4 * md
[0] - nibbles
;
1565 for (i
= 0; i
< morenibbles
; i
++)
1567 for (i
= nibbles
; i
--;)
1569 hex
[(bignum_byte(md
, i
/ 2) >> (4 * (i
% 2))) & 0xF]));
1579 Bignum
bigdiv(Bignum a
, Bignum b
)
1581 Bignum q
= newbn(a
[0]);
1582 bigdivmod(a
, b
, NULL
, q
);
1589 Bignum
bigmod(Bignum a
, Bignum b
)
1591 Bignum r
= newbn(b
[0]);
1592 bigdivmod(a
, b
, r
, NULL
);
1597 * Greatest common divisor.
1599 Bignum
biggcd(Bignum av
, Bignum bv
)
1601 Bignum a
= copybn(av
);
1602 Bignum b
= copybn(bv
);
1604 while (bignum_cmp(b
, Zero
) != 0) {
1605 Bignum t
= newbn(b
[0]);
1606 bigdivmod(a
, b
, t
, NULL
);
1607 while (t
[0] > 1 && t
[t
[0]] == 0)
1619 * Modular inverse, using Euclid's extended algorithm.
1621 Bignum
modinv(Bignum number
, Bignum modulus
)
1623 Bignum a
= copybn(modulus
);
1624 Bignum b
= copybn(number
);
1625 Bignum xp
= copybn(Zero
);
1626 Bignum x
= copybn(One
);
1629 while (bignum_cmp(b
, One
) != 0) {
1630 Bignum t
= newbn(b
[0]);
1631 Bignum q
= newbn(a
[0]);
1632 bigdivmod(a
, b
, t
, q
);
1633 while (t
[0] > 1 && t
[t
[0]] == 0)
1640 x
= bigmuladd(q
, xp
, t
);
1650 /* now we know that sign * x == 1, and that x < modulus */
1652 /* set a new x to be modulus - x */
1653 Bignum newx
= newbn(modulus
[0]);
1654 BignumInt carry
= 0;
1658 for (i
= 1; i
<= (int)newx
[0]; i
++) {
1659 BignumInt aword
= (i
<= (int)modulus
[0] ? modulus
[i
] : 0);
1660 BignumInt bword
= (i
<= (int)x
[0] ? x
[i
] : 0);
1661 newx
[i
] = aword
- bword
- carry
;
1663 carry
= carry ?
(newx
[i
] >= bword
) : (newx
[i
] > bword
);
1677 * Extract the largest power of 2 dividing x, storing it in p2, and returning
1678 * the product of the remaining factors.
1680 static Bignum
extract_p2(Bignum x
, unsigned *p2
)
1682 unsigned i
, j
, k
, n
;
1685 /* If x is zero then the following won't work. And if x is odd then
1686 * there's nothing very useful to do.
1688 if (!x
[0] || (x
[1] & 1)) {
1693 /* Find the power of two. */
1694 for (i
= 0; !x
[i
+ 1]; i
++);
1695 for (j
= 0; !((x
[i
+ 1] >> j
) & 1); j
++);
1696 *p2
= i
*BIGNUM_INT_BITS
+ j
;
1698 /* Work out how big the copy should be. */
1700 if (x
[x
[0]] >> j
) n
++;
1702 /* Copy and shift down. */
1704 for (k
= 1; k
<= n
; k
++) {
1705 y
[k
] = x
[k
+ i
] >> j
;
1706 if (j
&& k
< x
[0]) y
[k
] |= x
[k
+ i
+ 1] << (BIGNUM_INT_BITS
- j
);
1714 * Kronecker symbol (a|n). The result is always in { -1, 0, +1 }, and is
1715 * zero if and only if a and n have a nontrivial common factor. Most
1716 * usefully, if n is prime, this is the Legendre symbol, taking the value +1
1717 * if a is a quadratic residue mod n, and -1 otherwise; i.e., (a|p) ==
1718 * a^{(p-1)/2} (mod p).
1720 int kronecker(Bignum a
, Bignum n
)
1726 /* Special case for n = 0. This is the same convention PARI uses,
1727 * except that we can't represent negative numbers.
1729 if (bignum_cmp(n
, Zero
) == 0) {
1730 if (bignum_cmp(a
, One
) == 0) return +1;
1734 /* Write n = 2^s t, with t odd. If s > 0 and a is even, then the answer
1735 * is zero; otherwise throw in a factor of (-1)^s if a == 3 or 5 (mod 8).
1737 * At this point, we have a copy of n, and must remember to free it when
1738 * we're done. It's convenient to take a copy of a at the same time.
1741 n
= extract_p2(n
, &s
);
1743 if (s
&& (!a
[0] || !(a
[1] & 1))) { r
= 0; goto done
; }
1744 else if ((s
& 1) && ((a
[1] & 7) == 3 || (a
[1] & 7) == 5)) r
= -r
;
1746 /* If n is (now) a unit then we're done. */
1747 if (bignum_cmp(n
, One
) == 0) goto done
;
1749 /* Reduce a modulo n before we go any further. */
1750 if (bignum_cmp(a
, n
) >= 0) { t
= bigmod(a
, n
); freebn(a
); a
= t
; }
1754 if (bignum_cmp(a
, Zero
) == 0) { r
= 0; goto done
; }
1756 /* Strip out and handle powers of two from a. */
1757 t
= extract_p2(a
, &s
); freebn(a
); a
= t
;
1759 if ((s
& 1) && (nn
== 3 || nn
== 5)) r
= -r
;
1760 if (bignum_cmp(a
, One
) == 0) break;
1762 /* Swap, applying quadratic reciprocity. */
1763 if ((nn
& 3) == 3 && (a
[1] & 3) == 3) r
= -r
;
1764 t
= bigmod(n
, a
); freebn(n
); n
= a
; a
= t
;
1767 /* Tidy up: we're done. */
1769 freebn(a
); freebn(n
);
1774 * Modular square root. We must have p prime: extracting square roots modulo
1775 * composites is equivalent to factoring (but we don't check: you'll just get
1776 * the wrong answer). Returns NULL if x is not a quadratic residue mod p.
1778 Bignum
modsqrt(Bignum x
, Bignum p
)
1780 Bignum xinv
, b
, c
, r
, t
, z
, X
, mone
;
1783 /* If x is not a quadratic residue then we will not go to space today. */
1784 if (kronecker(x
, p
) != +1) return NULL
;
1786 /* We need a quadratic nonresidue from somewhere. Exactly half of all
1787 * units mod p are quadratic residues, but no efficient deterministic
1788 * algorithm for finding one is known. So pick at random: we don't
1789 * expect this to take long.
1793 for (i
= 1; i
<= p
[0]; i
++) z
[i
] = rand();
1794 z
[0] = p
[0]; bn_restore_invariant(z
);
1795 } while (kronecker(z
, p
) != -1);
1796 b
= bigmod(z
, p
); freebn(z
);
1798 /* We need to compute a few things before we really get started. */
1799 xinv
= modinv(x
, p
); /* x^{-1} mod p */
1800 mone
= bigsub(p
, One
); /* p - 1 == -1 (mod p) */
1801 t
= extract_p2(mone
, &s
); /* 2^s t = p - 1 */
1802 c
= modpow(b
, t
, p
); /* b^t (mod p) */
1803 z
= bigadd(t
, One
); freebn(t
); t
= z
; /* (t + 1) */
1804 shift_right(t
+ 1, t
[0], 1); if (!t
[t
[0]]) t
[0]--;
1805 r
= modpow(x
, t
, p
); /* x^{(t+1)/2} (mod p) */
1806 freebn(b
); freebn(mone
); freebn(t
);
1808 /* OK, so how does this work anyway?
1810 * We know that x^t is somewhere in the order-2^s subgroup of GF(p)^*;
1811 * and g = c^{-1} is a generator for this subgroup (since we know that
1812 * g^{2^{s-1}} = b^{(p-1)/2} = (b|p) = -1); so x^t = g^m for some m. In
1813 * fact, we know that m is even because x is a square. Suppose we can
1814 * determine m; then we know that x^t/g^m = 1, so x^{t+1}/c^m = x -- but
1815 * both t + 1 and m are even, so x^{(t+1)/2}/g^{m/2} is a square root of
1818 * Conveniently, finding the discrete log of an element X in a group of
1819 * order 2^s is easy. Write X = g^m = g^{m_0+2k'}; then X^{2^{s-1}} =
1820 * g^{m_0 2^{s-1}} c^{m' 2^s} = g^{m_0 2^{s-1}} is either -1 or +1,
1821 * telling us that m_0 is 1 or 0 respectively. Then X/g^{m_0} =
1822 * (g^2)^{m'} has order 2^{s-1} so we can continue inductively. What we
1823 * end up with at the end is X/g^m.
1825 * There are a few wrinkles. As we proceed through the induction, the
1826 * generator for the subgroup will be c^{-2}, since we know that m is
1827 * even. While we want the discrete log of X = x^t, we're actually going
1828 * to keep track of r, which will eventually be x^{(t+1)/2}/g^{m/2} =
1829 * x^{(t+1)/2} c^m, recovering X/g^m = r^2/x as we go. We don't actually
1830 * form the discrete log explicitly, because the final result will
1831 * actually be the square root we want.
1833 for (i
= 1; i
< s
; i
++) {
1835 /* Determine X. We could optimize this, only recomputing it when
1836 * it's been invalidated, but that's fiddlier and this isn't
1837 * performance critical.
1839 z
= modmul(r
, r
, p
);
1840 X
= modmul(z
, xinv
, p
);
1843 /* Determine X^{2^{s-1-i}}. */
1844 for (j
= i
+ 1; j
< s
; j
++)
1845 z
= modmul(X
, X
, p
), freebn(X
), X
= z
;
1847 /* Maybe accumulate a factor of c. */
1848 if (bignum_cmp(X
, One
) != 0)
1849 z
= modmul(r
, c
, p
), freebn(r
), r
= z
;
1851 /* Move on to the next smaller subgroup. */
1852 z
= modmul(c
, c
, p
), freebn(c
), c
= z
;
1856 /* Of course, there are two square roots of x. For predictability's sake
1857 * we'll always return the one in [1..(p - 1)/2]. The other is, of
1861 if (bignum_cmp(r
, z
) < 0)
1869 freebn(xinv
); freebn(c
);
1874 * Render a bignum into decimal. Return a malloced string holding
1875 * the decimal representation.
1877 char *bignum_decimal(Bignum x
)
1879 int ndigits
, ndigit
;
1883 BignumInt
*workspace
;
1886 * First, estimate the number of digits. Since log(10)/log(2)
1887 * is just greater than 93/28 (the joys of continued fraction
1888 * approximations...) we know that for every 93 bits, we need
1889 * at most 28 digits. This will tell us how much to malloc.
1891 * Formally: if x has i bits, that means x is strictly less
1892 * than 2^i. Since 2 is less than 10^(28/93), this is less than
1893 * 10^(28i/93). We need an integer power of ten, so we must
1894 * round up (rounding down might make it less than x again).
1895 * Therefore if we multiply the bit count by 28/93, rounding
1896 * up, we will have enough digits.
1898 * i=0 (i.e., x=0) is an irritating special case.
1900 i
= bignum_bitcount(x
);
1902 ndigits
= 1; /* x = 0 */
1904 ndigits
= (28 * i
+ 92) / 93; /* multiply by 28/93 and round up */
1905 ndigits
++; /* allow for trailing \0 */
1906 ret
= snewn(ndigits
, char);
1909 * Now allocate some workspace to hold the binary form as we
1910 * repeatedly divide it by ten. Initialise this to the
1911 * big-endian form of the number.
1913 workspace
= snewn(x
[0], BignumInt
);
1914 for (i
= 0; i
< (int)x
[0]; i
++)
1915 workspace
[i
] = x
[x
[0] - i
];
1918 * Next, write the decimal number starting with the last digit.
1919 * We use ordinary short division, dividing 10 into the
1922 ndigit
= ndigits
- 1;
1927 for (i
= 0; i
< (int)x
[0]; i
++) {
1928 carry
= (carry
<< BIGNUM_INT_BITS
) + workspace
[i
];
1929 workspace
[i
] = (BignumInt
) (carry
/ 10);
1934 ret
[--ndigit
] = (char) (carry
+ '0');
1938 * There's a chance we've fallen short of the start of the
1939 * string. Correct if so.
1942 memmove(ret
, ret
+ ndigit
, ndigits
- ndigit
);
1958 * gcc -Wall -g -O0 -DTESTBN -o testbn sshbn.c misc.c conf.c tree234.c unix/uxmisc.c -I. -I unix -I charset
1960 * Then feed to this program's standard input the output of
1961 * testdata/bignum.py .
1964 void modalfatalbox(char *p
, ...)
1967 fprintf(stderr
, "FATAL ERROR: ");
1969 vfprintf(stderr
, p
, ap
);
1971 fputc('\n', stderr
);
1975 #define fromxdigit(c) ( (c)>'9' ? ((c)&0xDF) - 'A' + 10 : (c) - '0' )
1977 int main(int argc
, char **argv
)
1981 int passes
= 0, fails
= 0;
1983 while ((buf
= fgetline(stdin
)) != NULL
) {
1984 int maxlen
= strlen(buf
);
1985 unsigned char *data
= snewn(maxlen
, unsigned char);
1986 unsigned char *ptrs
[5], *q
;
1995 while (*bufp
&& !isspace((unsigned char)*bufp
))
2004 while (*bufp
&& !isxdigit((unsigned char)*bufp
))
2011 while (*bufp
&& isxdigit((unsigned char)*bufp
))
2015 if (ptrnum
>= lenof(ptrs
))
2019 for (i
= -((end
- start
) & 1); i
< end
-start
; i
+= 2) {
2020 unsigned char val
= (i
< 0 ?
0 : fromxdigit(start
[i
]));
2021 val
= val
* 16 + fromxdigit(start
[i
+1]);
2028 if (!strcmp(buf
, "mul")) {
2032 printf("%d: mul with %d parameters, expected 3\n", line
, ptrnum
);
2035 a
= bignum_from_bytes(ptrs
[0], ptrs
[1]-ptrs
[0]);
2036 b
= bignum_from_bytes(ptrs
[1], ptrs
[2]-ptrs
[1]);
2037 c
= bignum_from_bytes(ptrs
[2], ptrs
[3]-ptrs
[2]);
2040 if (bignum_cmp(c
, p
) == 0) {
2043 char *as
= bignum_decimal(a
);
2044 char *bs
= bignum_decimal(b
);
2045 char *cs
= bignum_decimal(c
);
2046 char *ps
= bignum_decimal(p
);
2048 printf("%d: fail: %s * %s gave %s expected %s\n",
2049 line
, as
, bs
, ps
, cs
);
2061 } else if (!strcmp(buf
, "pow")) {
2062 Bignum base
, expt
, modulus
, expected
, answer
;
2065 printf("%d: mul with %d parameters, expected 4\n", line
, ptrnum
);
2069 base
= bignum_from_bytes(ptrs
[0], ptrs
[1]-ptrs
[0]);
2070 expt
= bignum_from_bytes(ptrs
[1], ptrs
[2]-ptrs
[1]);
2071 modulus
= bignum_from_bytes(ptrs
[2], ptrs
[3]-ptrs
[2]);
2072 expected
= bignum_from_bytes(ptrs
[3], ptrs
[4]-ptrs
[3]);
2073 answer
= modpow(base
, expt
, modulus
);
2075 if (bignum_cmp(expected
, answer
) == 0) {
2078 char *as
= bignum_decimal(base
);
2079 char *bs
= bignum_decimal(expt
);
2080 char *cs
= bignum_decimal(modulus
);
2081 char *ds
= bignum_decimal(answer
);
2082 char *ps
= bignum_decimal(expected
);
2084 printf("%d: fail: %s ^ %s mod %s gave %s expected %s\n",
2085 line
, as
, bs
, cs
, ds
, ps
);
2099 } else if (!strcmp(buf
, "modsqrt")) {
2100 Bignum x
, p
, expected
, answer
;
2103 printf("%d: modsqrt with %d parameters, expected 3\n", line
, ptrnum
);
2107 x
= bignum_from_bytes(ptrs
[0], ptrs
[1]-ptrs
[0]);
2108 p
= bignum_from_bytes(ptrs
[1], ptrs
[2]-ptrs
[1]);
2109 expected
= bignum_from_bytes(ptrs
[2], ptrs
[3]-ptrs
[2]);
2110 answer
= modsqrt(x
, p
);
2112 answer
= copybn(Zero
);
2114 if (bignum_cmp(expected
, answer
) == 0) {
2117 char *xs
= bignum_decimal(x
);
2118 char *ps
= bignum_decimal(p
);
2119 char *qs
= bignum_decimal(answer
);
2120 char *ws
= bignum_decimal(expected
);
2122 printf("%d: fail: sqrt(%s) mod %s gave %s expected %s\n",
2123 line
, xs
, ps
, qs
, ws
);
2136 printf("%d: unrecognised test keyword: '%s'\n", line
, buf
);
2144 printf("passed %d failed %d total %d\n", passes
, fails
, passes
+fails
);