# BRCM_VERSION=3
[bcm963xx.git] / userapps / opensource / sshd / libtommath / bn_s_mp_sqr.c
1 /* LibTomMath, multiple-precision integer library -- Tom St Denis
2  *
3  * LibTomMath is library that provides for multiple-precision
4  * integer arithmetic as well as number theoretic functionality.
5  *
6  * The library is designed directly after the MPI library by
7  * Michael Fromberger but has been written from scratch with
8  * additional optimizations in place.
9  *
10  * The library is free for all purposes without any express
11  * guarantee it works.
12  *
13  * Tom St Denis, tomstdenis@iahu.ca, http://math.libtomcrypt.org
14  */
15 #include <tommath.h>
16
17 /* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */
18 int
19 s_mp_sqr (mp_int * a, mp_int * b)
20 {
21   mp_int  t;
22   int     res, ix, iy, pa;
23   mp_word r;
24   mp_digit u, tmpx, *tmpt;
25
26   pa = a->used;
27   if ((res = mp_init_size (&t, 2*pa + 1)) != MP_OKAY) {
28     return res;
29   }
30   t.used = 2*pa + 1;
31
32   for (ix = 0; ix < pa; ix++) {
33     /* first calculate the digit at 2*ix */
34     /* calculate double precision result */
35     r = ((mp_word) t.dp[2*ix]) + 
36         ((mp_word) a->dp[ix]) * ((mp_word) a->dp[ix]);
37
38     /* store lower part in result */
39     t.dp[2*ix] = (mp_digit) (r & ((mp_word) MP_MASK));
40
41     /* get the carry */
42     u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
43
44     /* left hand side of A[ix] * A[iy] */
45     tmpx = a->dp[ix];
46
47     /* alias for where to store the results */
48     tmpt = t.dp + (2*ix + 1);
49     
50     for (iy = ix + 1; iy < pa; iy++) {
51       /* first calculate the product */
52       r = ((mp_word) tmpx) * ((mp_word) a->dp[iy]);
53
54       /* now calculate the double precision result, note we use
55        * addition instead of *2 since it's easier to optimize
56        */
57       r = ((mp_word) * tmpt) + r + r + ((mp_word) u);
58
59       /* store lower part */
60       *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
61
62       /* get carry */
63       u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
64     }
65     /* propagate upwards */
66     while (u != ((mp_digit) 0)) {
67       r = ((mp_word) * tmpt) + ((mp_word) u);
68       *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
69       u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
70     }
71   }
72
73   mp_clamp (&t);
74   mp_exch (&t, b);
75   mp_clear (&t);
76   return MP_OKAY;
77 }