Change BN_mod_sqrt() so that it verifies that the input value is
[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  * If 'a' is not a square, this is not necessarily detected by
69  * the algorithms; a bogus result must be expected in this case.
70  */
71         {
72         BIGNUM *ret = in;
73         int err = 1;
74         int r;
75         BIGNUM *A, *b, *q, *t, *x, *y;
76         int e, i, j;
77         
78         if (!BN_is_odd(p) || BN_abs_is_word(p, 1))
79                 {
80                 if (BN_abs_is_word(p, 2))
81                         {
82                         if (ret == NULL)
83                                 ret = BN_new();
84                         if (ret == NULL)
85                                 goto end;
86                         if (!BN_set_word(ret, BN_is_bit_set(a, 0)))
87                                 {
88                                 BN_free(ret);
89                                 return NULL;
90                                 }
91                         return ret;
92                         }
93
94                 BNerr(BN_F_BN_MOD_SQRT, BN_R_P_IS_NOT_PRIME);
95                 return(NULL);
96                 }
97
98         if (BN_is_zero(a) || BN_is_one(a))
99                 {
100                 if (ret == NULL)
101                         ret = BN_new();
102                 if (ret == NULL)
103                         goto end;
104                 if (!BN_set_word(ret, BN_is_one(a)))
105                         {
106                         BN_free(ret);
107                         return NULL;
108                         }
109                 return ret;
110                 }
111
112 #if 0 /* if BN_mod_sqrt is used with correct input, this just wastes time */
113         r = BN_kronecker(a, p, ctx);
114         if (r < -1) return NULL;
115         if (r == -1)
116                 {
117                 BNerr(BN_F_BN_MOD_SQRT, BN_R_NOT_A_SQUARE);
118                 return(NULL);
119                 }
120 #endif
121
122         BN_CTX_start(ctx);
123         A = BN_CTX_get(ctx);
124         b = BN_CTX_get(ctx);
125         q = BN_CTX_get(ctx);
126         t = BN_CTX_get(ctx);
127         x = BN_CTX_get(ctx);
128         y = BN_CTX_get(ctx);
129         if (y == NULL) goto end;
130         
131         if (ret == NULL)
132                 ret = BN_new();
133         if (ret == NULL) goto end;
134
135         /* A = a mod p */
136         if (!BN_nnmod(A, a, p, ctx)) goto end;
137
138         /* now write  |p| - 1  as  2^e*q  where  q  is odd */
139         e = 1;
140         while (!BN_is_bit_set(p, e))
141                 e++;
142         /* we'll set  q  later (if needed) */
143
144         if (e == 1)
145                 {
146                 /* The easy case:  (|p|-1)/2  is odd, so 2 has an inverse
147                  * modulo  (|p|-1)/2,  and square roots can be computed
148                  * directly by modular exponentiation.
149                  * We have
150                  *     2 * (|p|+1)/4 == 1   (mod (|p|-1)/2),
151                  * so we can use exponent  (|p|+1)/4,  i.e.  (|p|-3)/4 + 1.
152                  */
153                 if (!BN_rshift(q, p, 2)) goto end;
154                 q->neg = 0;
155                 if (!BN_add_word(q, 1)) goto end;
156                 if (!BN_mod_exp(ret, A, q, p, ctx)) goto end;
157                 err = 0;
158                 goto vrfy;
159                 }
160         
161         if (e == 2)
162                 {
163                 /* |p| == 5  (mod 8)
164                  *
165                  * In this case  2  is always a non-square since
166                  * Legendre(2,p) = (-1)^((p^2-1)/8)  for any odd prime.
167                  * So if  a  really is a square, then  2*a  is a non-square.
168                  * Thus for
169                  *      b := (2*a)^((|p|-5)/8),
170                  *      i := (2*a)*b^2
171                  * we have
172                  *     i^2 = (2*a)^((1 + (|p|-5)/4)*2)
173                  *         = (2*a)^((p-1)/2)
174                  *         = -1;
175                  * so if we set
176                  *      x := a*b*(i-1),
177                  * then
178                  *     x^2 = a^2 * b^2 * (i^2 - 2*i + 1)
179                  *         = a^2 * b^2 * (-2*i)
180                  *         = a*(-i)*(2*a*b^2)
181                  *         = a*(-i)*i
182                  *         = a.
183                  *
184                  * (This is due to A.O.L. Atkin, 
185                  * <URL: http://listserv.nodak.edu/scripts/wa.exe?A2=ind9211&L=nmbrthry&O=T&P=562>,
186                  * November 1992.)
187                  */
188
189                 /* t := 2*a */
190                 if (!BN_mod_lshift1_quick(t, A, p)) goto end;
191
192                 /* b := (2*a)^((|p|-5)/8) */
193                 if (!BN_rshift(q, p, 3)) goto end;
194                 q->neg = 0;
195                 if (!BN_mod_exp(b, t, q, p, ctx)) goto end;
196
197                 /* y := b^2 */
198                 if (!BN_mod_sqr(y, b, p, ctx)) goto end;
199
200                 /* t := (2*a)*b^2 - 1*/
201                 if (!BN_mod_mul(t, t, y, p, ctx)) goto end;
202                 if (!BN_sub_word(t, 1)) goto end;
203
204                 /* x = a*b*t */
205                 if (!BN_mod_mul(x, A, b, p, ctx)) goto end;
206                 if (!BN_mod_mul(x, x, t, p, ctx)) goto end;
207
208                 if (!BN_copy(ret, x)) goto end;
209                 err = 0;
210                 goto vrfy;
211                 }
212         
213         /* e > 2, so we really have to use the Tonelli/Shanks algorithm.
214          * First, find some  y  that is not a square. */
215         if (!BN_copy(q, p)) goto end; /* use 'q' as temp */
216         q->neg = 0;
217         i = 2;
218         do
219                 {
220                 /* For efficiency, try small numbers first;
221                  * if this fails, try random numbers.
222                  */
223                 if (i < 22)
224                         {
225                         if (!BN_set_word(y, i)) goto end;
226                         }
227                 else
228                         {
229                         if (!BN_pseudo_rand(y, BN_num_bits(p), 0, 0)) goto end;
230                         if (BN_ucmp(y, p) >= 0)
231                                 {
232                                 if (!(p->neg ? BN_add : BN_sub)(y, y, p)) goto end;
233                                 }
234                         /* now 0 <= y < |p| */
235                         if (BN_is_zero(y))
236                                 if (!BN_set_word(y, i)) goto end;
237                         }
238                 
239                 r = BN_kronecker(y, q, ctx); /* here 'q' is |p| */
240                 if (r < -1) goto end;
241                 if (r == 0)
242                         {
243                         /* m divides p */
244                         BNerr(BN_F_BN_MOD_SQRT, BN_R_P_IS_NOT_PRIME);
245                         goto end;
246                         }
247                 }
248         while (r == 1 && ++i < 82);
249         
250         if (r != -1)
251                 {
252                 /* Many rounds and still no non-square -- this is more likely
253                  * a bug than just bad luck.
254                  * Even if  p  is not prime, we should have found some  y
255                  * such that r == -1.
256                  */
257                 BNerr(BN_F_BN_MOD_SQRT, BN_R_TOO_MANY_ITERATIONS);
258                 goto end;
259                 }
260
261         /* Here's our actual 'q': */
262         if (!BN_rshift(q, q, e)) goto end;
263
264         /* Now that we have some non-square, we can find an element
265          * of order  2^e  by computing its q'th power. */
266         if (!BN_mod_exp(y, y, q, p, ctx)) goto end;
267         if (BN_is_one(y))
268                 {
269                 BNerr(BN_F_BN_MOD_SQRT, BN_R_P_IS_NOT_PRIME);
270                 goto end;
271                 }
272
273         /* Now we know that (if  p  is indeed prime) there is an integer
274          * k,  0 <= k < 2^e,  such that
275          *
276          *      a^q * y^k == 1   (mod p).
277          *
278          * As  a^q  is a square and  y  is not,  k  must be even.
279          * q+1  is even, too, so there is an element
280          *
281          *     X := a^((q+1)/2) * y^(k/2),
282          *
283          * and it satisfies
284          *
285          *     X^2 = a^q * a     * y^k
286          *         = a,
287          *
288          * so it is the square root that we are looking for.
289          */
290         
291         /* t := (q-1)/2  (note that  q  is odd) */
292         if (!BN_rshift1(t, q)) goto end;
293         
294         /* x := a^((q-1)/2) */
295         if (BN_is_zero(t)) /* special case: p = 2^e + 1 */
296                 {
297                 if (!BN_nnmod(t, A, p, ctx)) goto end;
298                 if (BN_is_zero(t))
299                         {
300                         /* special case: a == 0  (mod p) */
301                         if (!BN_zero(ret)) goto end;
302                         err = 0;
303                         goto end;
304                         }
305                 else
306                         if (!BN_one(x)) goto end;
307                 }
308         else
309                 {
310                 if (!BN_mod_exp(x, A, t, p, ctx)) goto end;
311                 if (BN_is_zero(x))
312                         {
313                         /* special case: a == 0  (mod p) */
314                         if (!BN_zero(ret)) goto end;
315                         err = 0;
316                         goto end;
317                         }
318                 }
319
320         /* b := a*x^2  (= a^q) */
321         if (!BN_mod_sqr(b, x, p, ctx)) goto end;
322         if (!BN_mod_mul(b, b, A, p, ctx)) goto end;
323         
324         /* x := a*x    (= a^((q+1)/2)) */
325         if (!BN_mod_mul(x, x, A, p, ctx)) goto end;
326
327         while (1)
328                 {
329                 /* Now  b  is  a^q * y^k  for some even  k  (0 <= k < 2^E
330                  * where  E  refers to the original value of  e,  which we
331                  * don't keep in a variable),  and  x  is  a^((q+1)/2) * y^(k/2).
332                  *
333                  * We have  a*b = x^2,
334                  *    y^2^(e-1) = -1,
335                  *    b^2^(e-1) = 1.
336                  */
337
338                 if (BN_is_one(b))
339                         {
340                         if (!BN_copy(ret, x)) goto end;
341                         err = 0;
342                         goto vrfy;
343                         }
344
345
346                 /* find smallest  i  such that  b^(2^i) = 1 */
347                 i = 1;
348                 if (!BN_mod_sqr(t, b, p, ctx)) goto end;
349                 while (!BN_is_one(t))
350                         {
351                         i++;
352                         if (i == e)
353                                 {
354                                 BNerr(BN_F_BN_MOD_SQRT, BN_R_NOT_A_SQUARE);
355                                 goto end;
356                                 }
357                         if (!BN_mod_mul(t, t, t, p, ctx)) goto end;
358                         }
359                 
360
361                 /* t := y^2^(e - i - 1) */
362                 if (!BN_copy(t, y)) goto end;
363                 for (j = e - i - 1; j > 0; j--)
364                         {
365                         if (!BN_mod_sqr(t, t, p, ctx)) goto end;
366                         }
367                 if (!BN_mod_mul(y, t, t, p, ctx)) goto end;
368                 if (!BN_mod_mul(x, x, t, p, ctx)) goto end;
369                 if (!BN_mod_mul(b, b, y, p, ctx)) goto end;
370                 e = i;
371                 }
372
373  vrfy:
374         if (!err)
375                 {
376                 /* verify the result -- the input might have been not a square
377                  * (test added in 0.9.8) */
378                 
379                 if (!BN_mod_sqr(x, ret, p, ctx))
380                         err = 1;
381                 
382                 if (!err && 0 != BN_cmp(x, A))
383                         {
384                         BNerr(BN_F_BN_MOD_SQRT, BN_R_NOT_A_SQUARE);
385                         err = 1;
386                         }
387                 }
388
389  end:
390         if (err)
391                 {
392                 if (ret != NULL && ret != in)
393                         {
394                         BN_clear_free(ret);
395                         }
396                 ret = NULL;
397                 }
398         BN_CTX_end(ctx);
399         return ret;
400         }