142
|
1 #include <tommath.h> |
|
2 #ifdef BN_S_MP_MUL_DIGS_C |
2
|
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis |
|
4 * |
|
5 * LibTomMath is a library that provides multiple-precision |
|
6 * integer arithmetic as well as number theoretic functionality. |
|
7 * |
|
8 * The library was designed directly after the MPI library by |
|
9 * Michael Fromberger but has been written from scratch with |
|
10 * additional optimizations in place. |
|
11 * |
|
12 * The library is free for all purposes without any express |
|
13 * guarantee it works. |
|
14 * |
|
15 * Tom St Denis, [email protected], http://math.libtomcrypt.org |
|
16 */ |
|
17 |
|
18 /* multiplies |a| * |b| and only computes upto digs digits of result |
|
19 * HAC pp. 595, Algorithm 14.12 Modified so you can control how |
|
20 * many digits of output are created. |
|
21 */ |
|
22 int |
|
23 s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs) |
|
24 { |
|
25 mp_int t; |
|
26 int res, pa, pb, ix, iy; |
|
27 mp_digit u; |
|
28 mp_word r; |
|
29 mp_digit tmpx, *tmpt, *tmpy; |
|
30 |
|
31 /* can we use the fast multiplier? */ |
|
32 if (((digs) < MP_WARRAY) && |
|
33 MIN (a->used, b->used) < |
|
34 (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) { |
|
35 return fast_s_mp_mul_digs (a, b, c, digs); |
|
36 } |
|
37 |
|
38 if ((res = mp_init_size (&t, digs)) != MP_OKAY) { |
|
39 return res; |
|
40 } |
|
41 t.used = digs; |
|
42 |
|
43 /* compute the digits of the product directly */ |
|
44 pa = a->used; |
|
45 for (ix = 0; ix < pa; ix++) { |
|
46 /* set the carry to zero */ |
|
47 u = 0; |
|
48 |
|
49 /* limit ourselves to making digs digits of output */ |
|
50 pb = MIN (b->used, digs - ix); |
|
51 |
|
52 /* setup some aliases */ |
|
53 /* copy of the digit from a used within the nested loop */ |
|
54 tmpx = a->dp[ix]; |
|
55 |
|
56 /* an alias for the destination shifted ix places */ |
|
57 tmpt = t.dp + ix; |
|
58 |
|
59 /* an alias for the digits of b */ |
|
60 tmpy = b->dp; |
|
61 |
|
62 /* compute the columns of the output and propagate the carry */ |
|
63 for (iy = 0; iy < pb; iy++) { |
|
64 /* compute the column as a mp_word */ |
|
65 r = ((mp_word)*tmpt) + |
|
66 ((mp_word)tmpx) * ((mp_word)*tmpy++) + |
|
67 ((mp_word) u); |
|
68 |
|
69 /* the new column is the lower part of the result */ |
|
70 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK)); |
|
71 |
|
72 /* get the carry word from the result */ |
|
73 u = (mp_digit) (r >> ((mp_word) DIGIT_BIT)); |
|
74 } |
|
75 /* set carry if it is placed below digs */ |
|
76 if (ix + iy < digs) { |
|
77 *tmpt = u; |
|
78 } |
|
79 } |
|
80 |
|
81 mp_clamp (&t); |
|
82 mp_exch (&t, c); |
|
83 |
|
84 mp_clear (&t); |
|
85 return MP_OKAY; |
|
86 } |
142
|
87 #endif |