2a72c189cbad97b99694f99635dd1b175212b4de
[openssl.git] / crypto / bn / bn_sqrt.c
1 /* crypto/bn/bn_mod.c */
2 /* Written by Lenka Fibikova <fibikova@exp-math.uni-essen.de>
3  * and Bodo Moeller for the OpenSSL project. */
4 /* ====================================================================
5  * Copyright (c) 1998-2000 The OpenSSL Project.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer. 
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. All advertising materials mentioning features or use of this
20  *    software must display the following acknowledgment:
21  *    "This product includes software developed by the OpenSSL Project
22  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
23  *
24  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
25  *    endorse or promote products derived from this software without
26  *    prior written permission. For written permission, please contact
27  *    openssl-core@openssl.org.
28  *
29  * 5. Products derived from this software may not be called "OpenSSL"
30  *    nor may "OpenSSL" appear in their names without prior written
31  *    permission of the OpenSSL Project.
32  *
33  * 6. Redistributions of any form whatsoever must retain the following
34  *    acknowledgment:
35  *    "This product includes software developed by the OpenSSL Project
36  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
37  *
38  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
39  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
40  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
41  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
42  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
43  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
44  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
45  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
47  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
49  * OF THE POSSIBILITY OF SUCH DAMAGE.
50  * ====================================================================
51  *
52  * This product includes cryptographic software written by Eric Young
53  * (eay@cryptsoft.com).  This product includes software written by Tim
54  * Hudson (tjh@cryptsoft.com).
55  *
56  */
57
58 #include "cryptlib.h"
59 #include "bn_lcl.h"
60
61
62 BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) 
63 /* Returns 'ret' such that
64  *      ret^2 == a (mod p),
65  * using the Tonelli/Shanks algorithm (cf. Henri Cohen, "A Course
66  * in Algebraic Computational Number Theory", algorithm 1.5.1).
67  * 'p' must be prime!
68  */
69         {
70         BIGNUM *ret = in;
71         int err = 1;
72         int r;
73         BIGNUM *b, *q, *t, *x, *y;
74         int e, i, j;
75         
76         if (!BN_is_odd(p) || BN_abs_is_word(p, 1))
77                 {
78                 if (BN_abs_is_word(p, 2))
79                         {
80                         if (ret == NULL)
81                                 ret = BN_new();
82                         if (ret == NULL)
83                                 goto end;
84                         if (!BN_set_word(ret, BN_is_bit_set(a, 0)))
85                                 {
86                                 BN_free(ret);
87                                 return NULL;
88                                 }
89                         return ret;
90                         }
91
92                 BNerr(BN_F_BN_MOD_SQRT, BN_R_P_IS_NOT_PRIME);
93                 return(NULL);
94                 }
95
96 #if 0 /* if BN_mod_sqrt is used with correct input, this just wastes time */
97         r = BN_kronecker(a, p, ctx);
98         if (r < -1) return NULL;
99         if (r == -1)
100                 {
101                 BNerr(BN_F_BN_MOD_SQRT, BN_R_NOT_A_SQUARE);
102                 return(NULL);
103                 }
104 #endif
105
106         BN_CTX_start(ctx);
107         b = BN_CTX_get(ctx);
108         q = BN_CTX_get(ctx);
109         t = BN_CTX_get(ctx);
110         x = BN_CTX_get(ctx);
111         y = BN_CTX_get(ctx);
112         if (y == NULL) goto end;
113         
114         if (ret == NULL)
115                 ret = BN_new();
116         if (ret == NULL) goto end;
117
118         /* now write  |p| - 1  as  2^e*q  where  q  is odd */
119         e = 1;
120         while (!BN_is_bit_set(p, e))
121                 e++;
122         if (!BN_rshift(q, p, e)) goto end;
123         q->neg = 0;
124
125         if (e == 1)
126                 {
127                 /* The easy case:  (p-1)/2  is odd, so 2 has an inverse
128                  * modulo  (p-1)/2,  and square roots can be computed
129                  * directly by modular exponentiation.
130                  * We have
131                  *     2 * (p+1)/4 == 1   (mod (p-1)/2),
132                  * so we can use exponent  (p+1)/4,  i.e.  (q+1)/2.
133                  */
134                 if (!BN_add_word(q,1)) goto end;
135                 if (!BN_rshift1(q,q)) goto end;
136                 if (!BN_mod_exp(ret, a, q, p, ctx)) goto end;
137                 err = 0;
138                 goto end;
139                 }
140         
141         /* e > 1, so we really have to use the Tonelli/Shanks algorithm.
142          * First, find some  y  that is not a square. */
143         i = 2;
144         do
145                 {
146                 /* For efficiency, try small numbers first;
147                  * if this fails, try random numbers.
148                  */
149                 if (i < 22)
150                         {
151                         if (!BN_set_word(y, i)) goto end;
152                         }
153                 else
154                         {
155                         if (!BN_pseudo_rand(y, BN_num_bits(p), 0, 0)) goto end;
156                         if (BN_ucmp(y, p) >= 0)
157                                 {
158                                 if (!(p->neg ? BN_add : BN_sub)(y, y, p)) goto end;
159                                 }
160                         /* now 0 <= y < |p| */
161                         if (BN_is_zero(y))
162                                 if (!BN_set_word(y, i)) goto end;
163                         }
164                 
165                 r = BN_kronecker(y, p, ctx);
166                 if (r < -1) goto end;
167                 if (r == 0)
168                         {
169                         /* m divides p */
170                         BNerr(BN_F_BN_MOD_SQRT, BN_R_P_IS_NOT_PRIME);
171                         goto end;
172                         }
173                 }
174         while (r == 1 && ++i < 82);
175         
176         if (r != -1)
177                 {
178                 /* Many rounds and still no non-square -- this is more likely
179                  * a bug than just bad luck.
180                  * Even if  p  is not prime, we should have found some  y
181                  * such that r == -1.
182                  */
183                 BNerr(BN_F_BN_MOD_SQRT, BN_R_TOO_MANY_ITERATIONS);
184                 goto end;
185                 }
186
187
188         /* Now that we have some non-square, we can find an element
189          * of order  2^e  by computing its q'th power. */
190         if (!BN_mod_exp(y, y, q, p, ctx)) goto end;
191         if (BN_is_one(y))
192                 {
193                 BNerr(BN_F_BN_MOD_SQRT, BN_R_P_IS_NOT_PRIME);
194                 goto end;
195                 }
196
197         /* Now we know that (if  p  is indeed prime) there is an integer
198          * k,  0 <= k < 2^e,  such that
199          *
200          *      a^q * y^k == 1   (mod p).
201          *
202          * As  a^q  is a square and  y  is not,  k  must be even.
203          * q+1  is even, too, so there is an element
204          *
205          *     X := a^((q+1)/2) * y^(k/2),
206          *
207          * and it satisfies
208          *
209          *     X^2 = a^q * a     * y^k
210          *         = a,
211          *
212          * so it is the square root that we are looking for.
213          */
214         
215         /* t := (q-1)/2  (note that  q  is odd) */
216         if (!BN_rshift1(t, q)) goto end;
217         
218         /* x := a^((q-1)/2) */
219         if (BN_is_zero(t)) /* special case: p = 2^e + 1 */
220                 {
221                 if (!BN_nnmod(t, a, p, ctx)) goto end;
222                 if (BN_is_zero(t))
223                         {
224                         /* special case: a == 0  (mod p) */
225                         if (!BN_zero(ret)) goto end;
226                         err = 0;
227                         goto end;
228                         }
229                 else
230                         if (!BN_one(x)) goto end;
231                 }
232         else
233                 {
234                 if (!BN_mod_exp(x, a, t, p, ctx)) goto end;
235                 if (BN_is_zero(x))
236                         {
237                         /* special case: a == 0  (mod p) */
238                         if (!BN_zero(ret)) goto end;
239                         err = 0;
240                         goto end;
241                         }
242                 }
243
244         /* b := a*x^2  (= a^q) */
245         if (!BN_mod_sqr(b, x, p, ctx)) goto end;
246         if (!BN_mod_mul(b, b, a, p, ctx)) goto end;
247         
248         /* x := a*x    (= a^((q+1)/2)) */
249         if (!BN_mod_mul(x, x, a, p, ctx)) goto end;
250
251         while (1)
252                 {
253                 /* Now  b  is  a^q * y^k  for some even  k  (0 <= k < 2^E
254                  * where  E  refers to the original value of  e,  which we
255                  * don't keep in a variable),  and  x  is  a^((q+1)/2) * y^(k/2).
256                  *
257                  * We have  a*b = x^2,
258                  *    y^2^(e-1) = -1,
259                  *    b^2^(e-1) = 1.
260                  */
261
262                 if (BN_is_one(b))
263                         {
264                         if (!BN_copy(ret, x)) goto end;
265                         err = 0;
266                         goto end;
267                         }
268
269
270                 /* find smallest  i  such that  b^(2^i) = 1 */
271                 i = 1;
272                 if (!BN_mod_sqr(t, b, p, ctx)) goto end;
273                 while (!BN_is_one(t))
274                         {
275                         i++;
276                         if (i == e)
277                                 {
278                                 BNerr(BN_F_BN_MOD_SQRT, BN_R_NOT_A_SQUARE);
279                                 goto end;
280                                 }
281                         if (!BN_mod_mul(t, t, t, p, ctx)) goto end;
282                         }
283                 
284
285                 /* t := y^2^(e - i - 1) */
286                 if (!BN_copy(t, y)) goto end;
287                 for (j = e - i - 1; j > 0; j--)
288                         {
289                         if (!BN_mod_sqr(t, t, p, ctx)) goto end;
290                         }
291                 if (!BN_mod_mul(y, t, t, p, ctx)) goto end;
292                 if (!BN_mod_mul(x, x, t, p, ctx)) goto end;
293                 if (!BN_mod_mul(b, b, y, p, ctx)) goto end;
294                 e = i;
295                 }
296
297  end:
298         if (err)
299                 {
300                 if (ret != NULL && ret != in)
301                         {
302                         BN_clear_free(ret);
303                         }
304                 ret = NULL;
305                 }
306         BN_CTX_end(ctx);
307         return ret;
308         }