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 memset(b
, 0, 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 #define KARATSUBA_THRESHOLD 50
206 static void internal_mul(BignumInt
*a
, BignumInt
*b
,
207 BignumInt
*c
, int len
)
212 if (len
> KARATSUBA_THRESHOLD
) {
215 * Karatsuba divide-and-conquer algorithm. Cut each input in
216 * half, so that it's expressed as two big 'digits' in a giant
222 * Then the product is of course
224 * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
226 * and we compute the three coefficients by recursively
227 * calling ourself to do half-length multiplications.
229 * The clever bit that makes this worth doing is that we only
230 * need _one_ half-length multiplication for the central
231 * coefficient rather than the two that it obviouly looks
232 * like, because we can use a single multiplication to compute
234 * (a_1 + a_0) (b_1 + b_0) = a_1 b_1 + a_1 b_0 + a_0 b_1 + a_0 b_0
236 * and then we subtract the other two coefficients (a_1 b_1
237 * and a_0 b_0) which we were computing anyway.
239 * Hence we get to multiply two numbers of length N in about
240 * three times as much work as it takes to multiply numbers of
241 * length N/2, which is obviously better than the four times
242 * as much work it would take if we just did a long
243 * conventional multiply.
246 int toplen
= len
/2, botlen
= len
- toplen
; /* botlen is the bigger */
247 int midlen
= botlen
+ 1;
252 * The coefficients a_1 b_1 and a_0 b_0 just avoid overlapping
253 * in the output array, so we can compute them immediately in
258 internal_mul(a
, b
, c
, toplen
);
261 internal_mul(a
+ toplen
, b
+ toplen
, c
+ 2*toplen
, botlen
);
264 * We must allocate scratch space for the central coefficient,
265 * and also for the two input values that we multiply when
266 * computing it. Since either or both may carry into the
267 * (botlen+1)th word, we must use a slightly longer length
270 scratch
= snewn(4 * midlen
, BignumInt
);
272 /* Zero padding. midlen exceeds toplen by at most 2, so just
273 * zero the first two words of each input and the rest will be
275 scratch
[0] = scratch
[1] = scratch
[midlen
] = scratch
[midlen
+1] = 0;
277 for (j
= 0; j
< toplen
; j
++) {
278 scratch
[midlen
- toplen
+ j
] = a
[j
]; /* a_1 */
279 scratch
[2*midlen
- toplen
+ j
] = b
[j
]; /* b_1 */
282 /* compute a_1 + a_0 */
283 scratch
[0] = internal_add(scratch
+1, a
+toplen
, scratch
+1, botlen
);
284 /* compute b_1 + b_0 */
285 scratch
[midlen
] = internal_add(scratch
+midlen
+1, b
+toplen
,
286 scratch
+midlen
+1, botlen
);
289 * Now we can do the third multiplication.
291 internal_mul(scratch
, scratch
+ midlen
, scratch
+ 2*midlen
, midlen
);
294 * Now we can reuse the first half of 'scratch' to compute the
295 * sum of the outer two coefficients, to subtract from that
296 * product to obtain the middle one.
298 scratch
[0] = scratch
[1] = scratch
[2] = scratch
[3] = 0;
299 for (j
= 0; j
< 2*toplen
; j
++)
300 scratch
[2*midlen
- 2*toplen
+ j
] = c
[j
];
301 scratch
[1] = internal_add(scratch
+2, c
+ 2*toplen
,
302 scratch
+2, 2*botlen
);
304 internal_sub(scratch
+ 2*midlen
, scratch
,
305 scratch
+ 2*midlen
, 2*midlen
);
308 * And now all we need to do is to add that middle coefficient
309 * back into the output. We may have to propagate a carry
310 * further up the output, but we can be sure it won't
311 * propagate right the way off the top.
313 carry
= internal_add(c
+ 2*len
- botlen
- 2*midlen
,
315 c
+ 2*len
- botlen
- 2*midlen
, 2*midlen
);
316 j
= 2*len
- botlen
- 2*midlen
- 1;
320 c
[j
] = (BignumInt
)carry
;
321 carry
>>= BIGNUM_INT_BITS
;
325 for (j
= 0; j
< 4 * midlen
; j
++)
332 * Multiply in the ordinary O(N^2) way.
335 for (j
= 0; j
< 2 * len
; j
++)
338 for (i
= len
- 1; i
>= 0; i
--) {
340 for (j
= len
- 1; j
>= 0; j
--) {
341 t
+= MUL_WORD(a
[i
], (BignumDblInt
) b
[j
]);
342 t
+= (BignumDblInt
) c
[i
+ j
+ 1];
343 c
[i
+ j
+ 1] = (BignumInt
) t
;
344 t
= t
>> BIGNUM_INT_BITS
;
346 c
[i
] = (BignumInt
) t
;
351 static void internal_add_shifted(BignumInt
*number
,
352 unsigned n
, int shift
)
354 int word
= 1 + (shift
/ BIGNUM_INT_BITS
);
355 int bshift
= shift
% BIGNUM_INT_BITS
;
358 addend
= (BignumDblInt
)n
<< bshift
;
361 addend
+= number
[word
];
362 number
[word
] = (BignumInt
) addend
& BIGNUM_INT_MASK
;
363 addend
>>= BIGNUM_INT_BITS
;
370 * Input in first alen words of a and first mlen words of m.
371 * Output in first alen words of a
372 * (of which first alen-mlen words will be zero).
373 * The MSW of m MUST have its high bit set.
374 * Quotient is accumulated in the `quotient' array, which is a Bignum
375 * rather than the internal bigendian format. Quotient parts are shifted
376 * left by `qshift' before adding into quot.
378 static void internal_mod(BignumInt
*a
, int alen
,
379 BignumInt
*m
, int mlen
,
380 BignumInt
*quot
, int qshift
)
392 for (i
= 0; i
<= alen
- mlen
; i
++) {
394 unsigned int q
, r
, c
, ai1
;
408 /* Find q = h:a[i] / m0 */
413 * To illustrate it, suppose a BignumInt is 8 bits, and
414 * we are dividing (say) A1:23:45:67 by A1:B2:C3. Then
415 * our initial division will be 0xA123 / 0xA1, which
416 * will give a quotient of 0x100 and a divide overflow.
417 * However, the invariants in this division algorithm
418 * are not violated, since the full number A1:23:... is
419 * _less_ than the quotient prefix A1:B2:... and so the
420 * following correction loop would have sorted it out.
422 * In this situation we set q to be the largest
423 * quotient we _can_ stomach (0xFF, of course).
427 /* Macro doesn't want an array subscript expression passed
428 * into it (see definition), so use a temporary. */
429 BignumInt tmplo
= a
[i
];
430 DIVMOD_WORD(q
, r
, h
, tmplo
, m0
);
432 /* Refine our estimate of q by looking at
433 h:a[i]:a[i+1] / m0:m1 */
435 if (t
> ((BignumDblInt
) r
<< BIGNUM_INT_BITS
) + ai1
) {
438 r
= (r
+ m0
) & BIGNUM_INT_MASK
; /* overflow? */
439 if (r
>= (BignumDblInt
) m0
&&
440 t
> ((BignumDblInt
) r
<< BIGNUM_INT_BITS
) + ai1
) q
--;
444 /* Subtract q * m from a[i...] */
446 for (k
= mlen
- 1; k
>= 0; k
--) {
447 t
= MUL_WORD(q
, m
[k
]);
449 c
= (unsigned)(t
>> BIGNUM_INT_BITS
);
450 if ((BignumInt
) t
> a
[i
+ k
])
452 a
[i
+ k
] -= (BignumInt
) t
;
455 /* Add back m in case of borrow */
458 for (k
= mlen
- 1; k
>= 0; k
--) {
461 a
[i
+ k
] = (BignumInt
) t
;
462 t
= t
>> BIGNUM_INT_BITS
;
467 internal_add_shifted(quot
, q
, qshift
+ BIGNUM_INT_BITS
* (alen
- mlen
- i
));
472 * Compute (base ^ exp) % mod.
474 Bignum
modpow(Bignum base_in
, Bignum exp
, Bignum mod
)
476 BignumInt
*a
, *b
, *n
, *m
;
482 * The most significant word of mod needs to be non-zero. It
483 * should already be, but let's make sure.
485 assert(mod
[mod
[0]] != 0);
488 * Make sure the base is smaller than the modulus, by reducing
489 * it modulo the modulus if not.
491 base
= bigmod(base_in
, mod
);
493 /* Allocate m of size mlen, copy mod to m */
494 /* We use big endian internally */
496 m
= snewn(mlen
, BignumInt
);
497 for (j
= 0; j
< mlen
; j
++)
498 m
[j
] = mod
[mod
[0] - j
];
500 /* Shift m left to make msb bit set */
501 for (mshift
= 0; mshift
< BIGNUM_INT_BITS
-1; mshift
++)
502 if ((m
[0] << mshift
) & BIGNUM_TOP_BIT
)
505 for (i
= 0; i
< mlen
- 1; i
++)
506 m
[i
] = (m
[i
] << mshift
) | (m
[i
+ 1] >> (BIGNUM_INT_BITS
- mshift
));
507 m
[mlen
- 1] = m
[mlen
- 1] << mshift
;
510 /* Allocate n of size mlen, copy base to n */
511 n
= snewn(mlen
, BignumInt
);
513 for (j
= 0; j
< i
; j
++)
515 for (j
= 0; j
< (int)base
[0]; j
++)
516 n
[i
+ j
] = base
[base
[0] - j
];
518 /* Allocate a and b of size 2*mlen. Set a = 1 */
519 a
= snewn(2 * mlen
, BignumInt
);
520 b
= snewn(2 * mlen
, BignumInt
);
521 for (i
= 0; i
< 2 * mlen
; i
++)
525 /* Skip leading zero bits of exp. */
527 j
= BIGNUM_INT_BITS
-1;
528 while (i
< (int)exp
[0] && (exp
[exp
[0] - i
] & (1 << j
)) == 0) {
532 j
= BIGNUM_INT_BITS
-1;
536 /* Main computation */
537 while (i
< (int)exp
[0]) {
539 internal_mul(a
+ mlen
, a
+ mlen
, b
, mlen
);
540 internal_mod(b
, mlen
* 2, m
, mlen
, NULL
, 0);
541 if ((exp
[exp
[0] - i
] & (1 << j
)) != 0) {
542 internal_mul(b
+ mlen
, n
, a
, mlen
);
543 internal_mod(a
, mlen
* 2, m
, mlen
, NULL
, 0);
553 j
= BIGNUM_INT_BITS
-1;
556 /* Fixup result in case the modulus was shifted */
558 for (i
= mlen
- 1; i
< 2 * mlen
- 1; i
++)
559 a
[i
] = (a
[i
] << mshift
) | (a
[i
+ 1] >> (BIGNUM_INT_BITS
- mshift
));
560 a
[2 * mlen
- 1] = a
[2 * mlen
- 1] << mshift
;
561 internal_mod(a
, mlen
* 2, m
, mlen
, NULL
, 0);
562 for (i
= 2 * mlen
- 1; i
>= mlen
; i
--)
563 a
[i
] = (a
[i
] >> mshift
) | (a
[i
- 1] << (BIGNUM_INT_BITS
- mshift
));
566 /* Copy result to buffer */
567 result
= newbn(mod
[0]);
568 for (i
= 0; i
< mlen
; i
++)
569 result
[result
[0] - i
] = a
[i
+ mlen
];
570 while (result
[0] > 1 && result
[result
[0]] == 0)
573 /* Free temporary arrays */
574 for (i
= 0; i
< 2 * mlen
; i
++)
577 for (i
= 0; i
< 2 * mlen
; i
++)
580 for (i
= 0; i
< mlen
; i
++)
583 for (i
= 0; i
< mlen
; i
++)
593 * Compute (p * q) % mod.
594 * The most significant word of mod MUST be non-zero.
595 * We assume that the result array is the same size as the mod array.
597 Bignum
modmul(Bignum p
, Bignum q
, Bignum mod
)
599 BignumInt
*a
, *n
, *m
, *o
;
601 int pqlen
, mlen
, rlen
, i
, j
;
604 /* Allocate m of size mlen, copy mod to m */
605 /* We use big endian internally */
607 m
= snewn(mlen
, BignumInt
);
608 for (j
= 0; j
< mlen
; j
++)
609 m
[j
] = mod
[mod
[0] - j
];
611 /* Shift m left to make msb bit set */
612 for (mshift
= 0; mshift
< BIGNUM_INT_BITS
-1; mshift
++)
613 if ((m
[0] << mshift
) & BIGNUM_TOP_BIT
)
616 for (i
= 0; i
< mlen
- 1; i
++)
617 m
[i
] = (m
[i
] << mshift
) | (m
[i
+ 1] >> (BIGNUM_INT_BITS
- mshift
));
618 m
[mlen
- 1] = m
[mlen
- 1] << mshift
;
621 pqlen
= (p
[0] > q
[0] ? p
[0] : q
[0]);
623 /* Allocate n of size pqlen, copy p to n */
624 n
= snewn(pqlen
, BignumInt
);
626 for (j
= 0; j
< i
; j
++)
628 for (j
= 0; j
< (int)p
[0]; j
++)
629 n
[i
+ j
] = p
[p
[0] - j
];
631 /* Allocate o of size pqlen, copy q to o */
632 o
= snewn(pqlen
, BignumInt
);
634 for (j
= 0; j
< i
; j
++)
636 for (j
= 0; j
< (int)q
[0]; j
++)
637 o
[i
+ j
] = q
[q
[0] - j
];
639 /* Allocate a of size 2*pqlen for result */
640 a
= snewn(2 * pqlen
, BignumInt
);
642 /* Main computation */
643 internal_mul(n
, o
, a
, pqlen
);
644 internal_mod(a
, pqlen
* 2, m
, mlen
, NULL
, 0);
646 /* Fixup result in case the modulus was shifted */
648 for (i
= 2 * pqlen
- mlen
- 1; i
< 2 * pqlen
- 1; i
++)
649 a
[i
] = (a
[i
] << mshift
) | (a
[i
+ 1] >> (BIGNUM_INT_BITS
- mshift
));
650 a
[2 * pqlen
- 1] = a
[2 * pqlen
- 1] << mshift
;
651 internal_mod(a
, pqlen
* 2, m
, mlen
, NULL
, 0);
652 for (i
= 2 * pqlen
- 1; i
>= 2 * pqlen
- mlen
; i
--)
653 a
[i
] = (a
[i
] >> mshift
) | (a
[i
- 1] << (BIGNUM_INT_BITS
- mshift
));
656 /* Copy result to buffer */
657 rlen
= (mlen
< pqlen
* 2 ? mlen
: pqlen
* 2);
658 result
= newbn(rlen
);
659 for (i
= 0; i
< rlen
; i
++)
660 result
[result
[0] - i
] = a
[i
+ 2 * pqlen
- rlen
];
661 while (result
[0] > 1 && result
[result
[0]] == 0)
664 /* Free temporary arrays */
665 for (i
= 0; i
< 2 * pqlen
; i
++)
668 for (i
= 0; i
< mlen
; i
++)
671 for (i
= 0; i
< pqlen
; i
++)
674 for (i
= 0; i
< pqlen
; i
++)
683 * The most significant word of mod MUST be non-zero.
684 * We assume that the result array is the same size as the mod array.
685 * We optionally write out a quotient if `quotient' is non-NULL.
686 * We can avoid writing out the result if `result' is NULL.
688 static void bigdivmod(Bignum p
, Bignum mod
, Bignum result
, Bignum quotient
)
692 int plen
, mlen
, i
, j
;
694 /* Allocate m of size mlen, copy mod to m */
695 /* We use big endian internally */
697 m
= snewn(mlen
, BignumInt
);
698 for (j
= 0; j
< mlen
; j
++)
699 m
[j
] = mod
[mod
[0] - j
];
701 /* Shift m left to make msb bit set */
702 for (mshift
= 0; mshift
< BIGNUM_INT_BITS
-1; mshift
++)
703 if ((m
[0] << mshift
) & BIGNUM_TOP_BIT
)
706 for (i
= 0; i
< mlen
- 1; i
++)
707 m
[i
] = (m
[i
] << mshift
) | (m
[i
+ 1] >> (BIGNUM_INT_BITS
- mshift
));
708 m
[mlen
- 1] = m
[mlen
- 1] << mshift
;
712 /* Ensure plen > mlen */
716 /* Allocate n of size plen, copy p to n */
717 n
= snewn(plen
, BignumInt
);
718 for (j
= 0; j
< plen
; j
++)
720 for (j
= 1; j
<= (int)p
[0]; j
++)
723 /* Main computation */
724 internal_mod(n
, plen
, m
, mlen
, quotient
, mshift
);
726 /* Fixup result in case the modulus was shifted */
728 for (i
= plen
- mlen
- 1; i
< plen
- 1; i
++)
729 n
[i
] = (n
[i
] << mshift
) | (n
[i
+ 1] >> (BIGNUM_INT_BITS
- mshift
));
730 n
[plen
- 1] = n
[plen
- 1] << mshift
;
731 internal_mod(n
, plen
, m
, mlen
, quotient
, 0);
732 for (i
= plen
- 1; i
>= plen
- mlen
; i
--)
733 n
[i
] = (n
[i
] >> mshift
) | (n
[i
- 1] << (BIGNUM_INT_BITS
- mshift
));
736 /* Copy result to buffer */
738 for (i
= 1; i
<= (int)result
[0]; i
++) {
740 result
[i
] = j
>= 0 ? n
[j
] : 0;
744 /* Free temporary arrays */
745 for (i
= 0; i
< mlen
; i
++)
748 for (i
= 0; i
< plen
; i
++)
754 * Decrement a number.
756 void decbn(Bignum bn
)
759 while (i
< (int)bn
[0] && bn
[i
] == 0)
760 bn
[i
++] = BIGNUM_INT_MASK
;
764 Bignum
bignum_from_bytes(const unsigned char *data
, int nbytes
)
769 w
= (nbytes
+ BIGNUM_INT_BYTES
- 1) / BIGNUM_INT_BYTES
; /* bytes->words */
772 for (i
= 1; i
<= w
; i
++)
774 for (i
= nbytes
; i
--;) {
775 unsigned char byte
= *data
++;
776 result
[1 + i
/ BIGNUM_INT_BYTES
] |= byte
<< (8*i
% BIGNUM_INT_BITS
);
779 while (result
[0] > 1 && result
[result
[0]] == 0)
785 * Read an SSH-1-format bignum from a data buffer. Return the number
786 * of bytes consumed, or -1 if there wasn't enough data.
788 int ssh1_read_bignum(const unsigned char *data
, int len
, Bignum
* result
)
790 const unsigned char *p
= data
;
798 for (i
= 0; i
< 2; i
++)
800 b
= (w
+ 7) / 8; /* bits -> bytes */
805 if (!result
) /* just return length */
808 *result
= bignum_from_bytes(p
, b
);
814 * Return the bit count of a bignum, for SSH-1 encoding.
816 int bignum_bitcount(Bignum bn
)
818 int bitcount
= bn
[0] * BIGNUM_INT_BITS
- 1;
820 && (bn
[bitcount
/ BIGNUM_INT_BITS
+ 1] >> (bitcount
% BIGNUM_INT_BITS
)) == 0) bitcount
--;
825 * Return the byte length of a bignum when SSH-1 encoded.
827 int ssh1_bignum_length(Bignum bn
)
829 return 2 + (bignum_bitcount(bn
) + 7) / 8;
833 * Return the byte length of a bignum when SSH-2 encoded.
835 int ssh2_bignum_length(Bignum bn
)
837 return 4 + (bignum_bitcount(bn
) + 8) / 8;
841 * Return a byte from a bignum; 0 is least significant, etc.
843 int bignum_byte(Bignum bn
, int i
)
845 if (i
>= (int)(BIGNUM_INT_BYTES
* bn
[0]))
846 return 0; /* beyond the end */
848 return (bn
[i
/ BIGNUM_INT_BYTES
+ 1] >>
849 ((i
% BIGNUM_INT_BYTES
)*8)) & 0xFF;
853 * Return a bit from a bignum; 0 is least significant, etc.
855 int bignum_bit(Bignum bn
, int i
)
857 if (i
>= (int)(BIGNUM_INT_BITS
* bn
[0]))
858 return 0; /* beyond the end */
860 return (bn
[i
/ BIGNUM_INT_BITS
+ 1] >> (i
% BIGNUM_INT_BITS
)) & 1;
864 * Set a bit in a bignum; 0 is least significant, etc.
866 void bignum_set_bit(Bignum bn
, int bitnum
, int value
)
868 if (bitnum
>= (int)(BIGNUM_INT_BITS
* bn
[0]))
869 abort(); /* beyond the end */
871 int v
= bitnum
/ BIGNUM_INT_BITS
+ 1;
872 int mask
= 1 << (bitnum
% BIGNUM_INT_BITS
);
881 * Write a SSH-1-format bignum into a buffer. It is assumed the
882 * buffer is big enough. Returns the number of bytes used.
884 int ssh1_write_bignum(void *data
, Bignum bn
)
886 unsigned char *p
= data
;
887 int len
= ssh1_bignum_length(bn
);
889 int bitc
= bignum_bitcount(bn
);
891 *p
++ = (bitc
>> 8) & 0xFF;
892 *p
++ = (bitc
) & 0xFF;
893 for (i
= len
- 2; i
--;)
894 *p
++ = bignum_byte(bn
, i
);
899 * Compare two bignums. Returns like strcmp.
901 int bignum_cmp(Bignum a
, Bignum b
)
903 int amax
= a
[0], bmax
= b
[0];
904 int i
= (amax
> bmax ? amax
: bmax
);
906 BignumInt aval
= (i
> amax ?
0 : a
[i
]);
907 BignumInt bval
= (i
> bmax ?
0 : b
[i
]);
918 * Right-shift one bignum to form another.
920 Bignum
bignum_rshift(Bignum a
, int shift
)
923 int i
, shiftw
, shiftb
, shiftbb
, bits
;
926 bits
= bignum_bitcount(a
) - shift
;
927 ret
= newbn((bits
+ BIGNUM_INT_BITS
- 1) / BIGNUM_INT_BITS
);
930 shiftw
= shift
/ BIGNUM_INT_BITS
;
931 shiftb
= shift
% BIGNUM_INT_BITS
;
932 shiftbb
= BIGNUM_INT_BITS
- shiftb
;
935 for (i
= 1; i
<= (int)ret
[0]; i
++) {
937 ai1
= (i
+ shiftw
+ 1 <= (int)a
[0] ? a
[i
+ shiftw
+ 1] : 0);
938 ret
[i
] = ((ai
>> shiftb
) | (ai1
<< shiftbb
)) & BIGNUM_INT_MASK
;
946 * Non-modular multiplication and addition.
948 Bignum
bigmuladd(Bignum a
, Bignum b
, Bignum addend
)
950 int alen
= a
[0], blen
= b
[0];
951 int mlen
= (alen
> blen ? alen
: blen
);
952 int rlen
, i
, maxspot
;
953 BignumInt
*workspace
;
956 /* mlen space for a, mlen space for b, 2*mlen for result */
957 workspace
= snewn(mlen
* 4, BignumInt
);
958 for (i
= 0; i
< mlen
; i
++) {
959 workspace
[0 * mlen
+ i
] = (mlen
- i
<= (int)a
[0] ? a
[mlen
- i
] : 0);
960 workspace
[1 * mlen
+ i
] = (mlen
- i
<= (int)b
[0] ? b
[mlen
- i
] : 0);
963 internal_mul(workspace
+ 0 * mlen
, workspace
+ 1 * mlen
,
964 workspace
+ 2 * mlen
, mlen
);
966 /* now just copy the result back */
967 rlen
= alen
+ blen
+ 1;
968 if (addend
&& rlen
<= (int)addend
[0])
969 rlen
= addend
[0] + 1;
972 for (i
= 1; i
<= (int)ret
[0]; i
++) {
973 ret
[i
] = (i
<= 2 * mlen ? workspace
[4 * mlen
- i
] : 0);
979 /* now add in the addend, if any */
981 BignumDblInt carry
= 0;
982 for (i
= 1; i
<= rlen
; i
++) {
983 carry
+= (i
<= (int)ret
[0] ? ret
[i
] : 0);
984 carry
+= (i
<= (int)addend
[0] ? addend
[i
] : 0);
985 ret
[i
] = (BignumInt
) carry
& BIGNUM_INT_MASK
;
986 carry
>>= BIGNUM_INT_BITS
;
987 if (ret
[i
] != 0 && i
> maxspot
)
998 * Non-modular multiplication.
1000 Bignum
bigmul(Bignum a
, Bignum b
)
1002 return bigmuladd(a
, b
, NULL
);
1006 * Create a bignum which is the bitmask covering another one. That
1007 * is, the smallest integer which is >= N and is also one less than
1010 Bignum
bignum_bitmask(Bignum n
)
1012 Bignum ret
= copybn(n
);
1017 while (n
[i
] == 0 && i
> 0)
1020 return ret
; /* input was zero */
1026 ret
[i
] = BIGNUM_INT_MASK
;
1031 * Convert a (max 32-bit) long into a bignum.
1033 Bignum
bignum_from_long(unsigned long nn
)
1036 BignumDblInt n
= nn
;
1039 ret
[1] = (BignumInt
)(n
& BIGNUM_INT_MASK
);
1040 ret
[2] = (BignumInt
)((n
>> BIGNUM_INT_BITS
) & BIGNUM_INT_MASK
);
1042 ret
[0] = (ret
[2] ?
2 : 1);
1047 * Add a long to a bignum.
1049 Bignum
bignum_add_long(Bignum number
, unsigned long addendx
)
1051 Bignum ret
= newbn(number
[0] + 1);
1053 BignumDblInt carry
= 0, addend
= addendx
;
1055 for (i
= 1; i
<= (int)ret
[0]; i
++) {
1056 carry
+= addend
& BIGNUM_INT_MASK
;
1057 carry
+= (i
<= (int)number
[0] ? number
[i
] : 0);
1058 addend
>>= BIGNUM_INT_BITS
;
1059 ret
[i
] = (BignumInt
) carry
& BIGNUM_INT_MASK
;
1060 carry
>>= BIGNUM_INT_BITS
;
1069 * Compute the residue of a bignum, modulo a (max 16-bit) short.
1071 unsigned short bignum_mod_short(Bignum number
, unsigned short modulus
)
1073 BignumDblInt mod
, r
;
1078 for (i
= number
[0]; i
> 0; i
--)
1079 r
= (r
* (BIGNUM_TOP_BIT
% mod
) * 2 + number
[i
] % mod
) % mod
;
1080 return (unsigned short) r
;
1084 void diagbn(char *prefix
, Bignum md
)
1086 int i
, nibbles
, morenibbles
;
1087 static const char hex
[] = "0123456789ABCDEF";
1089 debug(("%s0x", prefix ? prefix
: ""));
1091 nibbles
= (3 + bignum_bitcount(md
)) / 4;
1094 morenibbles
= 4 * md
[0] - nibbles
;
1095 for (i
= 0; i
< morenibbles
; i
++)
1097 for (i
= nibbles
; i
--;)
1099 hex
[(bignum_byte(md
, i
/ 2) >> (4 * (i
% 2))) & 0xF]));
1109 Bignum
bigdiv(Bignum a
, Bignum b
)
1111 Bignum q
= newbn(a
[0]);
1112 bigdivmod(a
, b
, NULL
, q
);
1119 Bignum
bigmod(Bignum a
, Bignum b
)
1121 Bignum r
= newbn(b
[0]);
1122 bigdivmod(a
, b
, r
, NULL
);
1127 * Greatest common divisor.
1129 Bignum
biggcd(Bignum av
, Bignum bv
)
1131 Bignum a
= copybn(av
);
1132 Bignum b
= copybn(bv
);
1134 while (bignum_cmp(b
, Zero
) != 0) {
1135 Bignum t
= newbn(b
[0]);
1136 bigdivmod(a
, b
, t
, NULL
);
1137 while (t
[0] > 1 && t
[t
[0]] == 0)
1149 * Modular inverse, using Euclid's extended algorithm.
1151 Bignum
modinv(Bignum number
, Bignum modulus
)
1153 Bignum a
= copybn(modulus
);
1154 Bignum b
= copybn(number
);
1155 Bignum xp
= copybn(Zero
);
1156 Bignum x
= copybn(One
);
1159 while (bignum_cmp(b
, One
) != 0) {
1160 Bignum t
= newbn(b
[0]);
1161 Bignum q
= newbn(a
[0]);
1162 bigdivmod(a
, b
, t
, q
);
1163 while (t
[0] > 1 && t
[t
[0]] == 0)
1170 x
= bigmuladd(q
, xp
, t
);
1180 /* now we know that sign * x == 1, and that x < modulus */
1182 /* set a new x to be modulus - x */
1183 Bignum newx
= newbn(modulus
[0]);
1184 BignumInt carry
= 0;
1188 for (i
= 1; i
<= (int)newx
[0]; i
++) {
1189 BignumInt aword
= (i
<= (int)modulus
[0] ? modulus
[i
] : 0);
1190 BignumInt bword
= (i
<= (int)x
[0] ? x
[i
] : 0);
1191 newx
[i
] = aword
- bword
- carry
;
1193 carry
= carry ?
(newx
[i
] >= bword
) : (newx
[i
] > bword
);
1207 * Render a bignum into decimal. Return a malloced string holding
1208 * the decimal representation.
1210 char *bignum_decimal(Bignum x
)
1212 int ndigits
, ndigit
;
1216 BignumInt
*workspace
;
1219 * First, estimate the number of digits. Since log(10)/log(2)
1220 * is just greater than 93/28 (the joys of continued fraction
1221 * approximations...) we know that for every 93 bits, we need
1222 * at most 28 digits. This will tell us how much to malloc.
1224 * Formally: if x has i bits, that means x is strictly less
1225 * than 2^i. Since 2 is less than 10^(28/93), this is less than
1226 * 10^(28i/93). We need an integer power of ten, so we must
1227 * round up (rounding down might make it less than x again).
1228 * Therefore if we multiply the bit count by 28/93, rounding
1229 * up, we will have enough digits.
1231 * i=0 (i.e., x=0) is an irritating special case.
1233 i
= bignum_bitcount(x
);
1235 ndigits
= 1; /* x = 0 */
1237 ndigits
= (28 * i
+ 92) / 93; /* multiply by 28/93 and round up */
1238 ndigits
++; /* allow for trailing \0 */
1239 ret
= snewn(ndigits
, char);
1242 * Now allocate some workspace to hold the binary form as we
1243 * repeatedly divide it by ten. Initialise this to the
1244 * big-endian form of the number.
1246 workspace
= snewn(x
[0], BignumInt
);
1247 for (i
= 0; i
< (int)x
[0]; i
++)
1248 workspace
[i
] = x
[x
[0] - i
];
1251 * Next, write the decimal number starting with the last digit.
1252 * We use ordinary short division, dividing 10 into the
1255 ndigit
= ndigits
- 1;
1260 for (i
= 0; i
< (int)x
[0]; i
++) {
1261 carry
= (carry
<< BIGNUM_INT_BITS
) + workspace
[i
];
1262 workspace
[i
] = (BignumInt
) (carry
/ 10);
1267 ret
[--ndigit
] = (char) (carry
+ '0');
1271 * There's a chance we've fallen short of the start of the
1272 * string. Correct if so.
1275 memmove(ret
, ret
+ ndigit
, ndigits
- ndigit
);