sqrt.c
Go to the documentation of this file.
1 /* Written by Lenka Fibikova <fibikova@exp-math.uni-essen.de>
2  * and Bodo Moeller for the OpenSSL project. */
3 /* ====================================================================
4  * Copyright (c) 1998-2000 The OpenSSL Project. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. All advertising materials mentioning features or use of this
19  * software must display the following acknowledgment:
20  * "This product includes software developed by the OpenSSL Project
21  * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
22  *
23  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
24  * endorse or promote products derived from this software without
25  * prior written permission. For written permission, please contact
26  * openssl-core@openssl.org.
27  *
28  * 5. Products derived from this software may not be called "OpenSSL"
29  * nor may "OpenSSL" appear in their names without prior written
30  * permission of the OpenSSL Project.
31  *
32  * 6. Redistributions of any form whatsoever must retain the following
33  * acknowledgment:
34  * "This product includes software developed by the OpenSSL Project
35  * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
36  *
37  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
38  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
40  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
43  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
45  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
46  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
47  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
48  * OF THE POSSIBILITY OF SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This product includes cryptographic software written by Eric Young
52  * (eay@cryptsoft.com). This product includes software written by Tim
53  * Hudson (tjh@cryptsoft.com). */
54 
55 #include <openssl/bn.h>
56 
57 #include <openssl/err.h>
58 
59 #include "internal.h"
60 
61 
62 BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) {
63  // Compute a square root of |a| mod |p| using the Tonelli/Shanks algorithm
64  // (cf. Henri Cohen, "A Course in Algebraic Computational Number Theory",
65  // algorithm 1.5.1). |p| is assumed to be a prime.
66 
67  BIGNUM *ret = in;
68  int err = 1;
69  int r;
70  BIGNUM *A, *b, *q, *t, *x, *y;
71  int e, i, j;
72 
73  if (!BN_is_odd(p) || BN_abs_is_word(p, 1)) {
74  if (BN_abs_is_word(p, 2)) {
75  if (ret == NULL) {
76  ret = BN_new();
77  }
78  if (ret == NULL ||
79  !BN_set_word(ret, BN_is_bit_set(a, 0))) {
80  if (ret != in) {
81  BN_free(ret);
82  }
83  return NULL;
84  }
85  return ret;
86  }
87 
89  return NULL;
90  }
91 
92  if (BN_is_zero(a) || BN_is_one(a)) {
93  if (ret == NULL) {
94  ret = BN_new();
95  }
96  if (ret == NULL ||
97  !BN_set_word(ret, BN_is_one(a))) {
98  if (ret != in) {
99  BN_free(ret);
100  }
101  return NULL;
102  }
103  return ret;
104  }
105 
106  BN_CTX_start(ctx);
107  A = BN_CTX_get(ctx);
108  b = BN_CTX_get(ctx);
109  q = BN_CTX_get(ctx);
110  t = BN_CTX_get(ctx);
111  x = BN_CTX_get(ctx);
112  y = BN_CTX_get(ctx);
113  if (y == NULL) {
114  goto end;
115  }
116 
117  if (ret == NULL) {
118  ret = BN_new();
119  }
120  if (ret == NULL) {
121  goto end;
122  }
123 
124  // A = a mod p
125  if (!BN_nnmod(A, a, p, ctx)) {
126  goto end;
127  }
128 
129  // now write |p| - 1 as 2^e*q where q is odd
130  e = 1;
131  while (!BN_is_bit_set(p, e)) {
132  e++;
133  }
134  // we'll set q later (if needed)
135 
136  if (e == 1) {
137  // The easy case: (|p|-1)/2 is odd, so 2 has an inverse
138  // modulo (|p|-1)/2, and square roots can be computed
139  // directly by modular exponentiation.
140  // We have
141  // 2 * (|p|+1)/4 == 1 (mod (|p|-1)/2),
142  // so we can use exponent (|p|+1)/4, i.e. (|p|-3)/4 + 1.
143  if (!BN_rshift(q, p, 2)) {
144  goto end;
145  }
146  q->neg = 0;
147  if (!BN_add_word(q, 1) ||
148  !BN_mod_exp_mont(ret, A, q, p, ctx, NULL)) {
149  goto end;
150  }
151  err = 0;
152  goto vrfy;
153  }
154 
155  if (e == 2) {
156  // |p| == 5 (mod 8)
157  //
158  // In this case 2 is always a non-square since
159  // Legendre(2,p) = (-1)^((p^2-1)/8) for any odd prime.
160  // So if a really is a square, then 2*a is a non-square.
161  // Thus for
162  // b := (2*a)^((|p|-5)/8),
163  // i := (2*a)*b^2
164  // we have
165  // i^2 = (2*a)^((1 + (|p|-5)/4)*2)
166  // = (2*a)^((p-1)/2)
167  // = -1;
168  // so if we set
169  // x := a*b*(i-1),
170  // then
171  // x^2 = a^2 * b^2 * (i^2 - 2*i + 1)
172  // = a^2 * b^2 * (-2*i)
173  // = a*(-i)*(2*a*b^2)
174  // = a*(-i)*i
175  // = a.
176  //
177  // (This is due to A.O.L. Atkin,
178  // <URL:
179  //http://listserv.nodak.edu/scripts/wa.exe?A2=ind9211&L=nmbrthry&O=T&P=562>,
180  // November 1992.)
181 
182  // t := 2*a
183  if (!bn_mod_lshift1_consttime(t, A, p, ctx)) {
184  goto end;
185  }
186 
187  // b := (2*a)^((|p|-5)/8)
188  if (!BN_rshift(q, p, 3)) {
189  goto end;
190  }
191  q->neg = 0;
192  if (!BN_mod_exp_mont(b, t, q, p, ctx, NULL)) {
193  goto end;
194  }
195 
196  // y := b^2
197  if (!BN_mod_sqr(y, b, p, ctx)) {
198  goto end;
199  }
200 
201  // t := (2*a)*b^2 - 1
202  if (!BN_mod_mul(t, t, y, p, ctx) ||
203  !BN_sub_word(t, 1)) {
204  goto end;
205  }
206 
207  // x = a*b*t
208  if (!BN_mod_mul(x, A, b, p, ctx) ||
209  !BN_mod_mul(x, x, t, p, ctx)) {
210  goto end;
211  }
212 
213  if (!BN_copy(ret, x)) {
214  goto end;
215  }
216  err = 0;
217  goto vrfy;
218  }
219 
220  // e > 2, so we really have to use the Tonelli/Shanks algorithm.
221  // First, find some y that is not a square.
222  if (!BN_copy(q, p)) {
223  goto end; // use 'q' as temp
224  }
225  q->neg = 0;
226  i = 2;
227  do {
228  // For efficiency, try small numbers first;
229  // if this fails, try random numbers.
230  if (i < 22) {
231  if (!BN_set_word(y, i)) {
232  goto end;
233  }
234  } else {
235  if (!BN_pseudo_rand(y, BN_num_bits(p), 0, 0)) {
236  goto end;
237  }
238  if (BN_ucmp(y, p) >= 0) {
239  if (!(p->neg ? BN_add : BN_sub)(y, y, p)) {
240  goto end;
241  }
242  }
243  // now 0 <= y < |p|
244  if (BN_is_zero(y)) {
245  if (!BN_set_word(y, i)) {
246  goto end;
247  }
248  }
249  }
250 
251  r = bn_jacobi(y, q, ctx); // here 'q' is |p|
252  if (r < -1) {
253  goto end;
254  }
255  if (r == 0) {
256  // m divides p
258  goto end;
259  }
260  } while (r == 1 && ++i < 82);
261 
262  if (r != -1) {
263  // Many rounds and still no non-square -- this is more likely
264  // a bug than just bad luck.
265  // Even if p is not prime, we should have found some y
266  // such that r == -1.
268  goto end;
269  }
270 
271  // Here's our actual 'q':
272  if (!BN_rshift(q, q, e)) {
273  goto end;
274  }
275 
276  // Now that we have some non-square, we can find an element
277  // of order 2^e by computing its q'th power.
278  if (!BN_mod_exp_mont(y, y, q, p, ctx, NULL)) {
279  goto end;
280  }
281  if (BN_is_one(y)) {
283  goto end;
284  }
285 
286  // Now we know that (if p is indeed prime) there is an integer
287  // k, 0 <= k < 2^e, such that
288  //
289  // a^q * y^k == 1 (mod p).
290  //
291  // As a^q is a square and y is not, k must be even.
292  // q+1 is even, too, so there is an element
293  //
294  // X := a^((q+1)/2) * y^(k/2),
295  //
296  // and it satisfies
297  //
298  // X^2 = a^q * a * y^k
299  // = a,
300  //
301  // so it is the square root that we are looking for.
302 
303  // t := (q-1)/2 (note that q is odd)
304  if (!BN_rshift1(t, q)) {
305  goto end;
306  }
307 
308  // x := a^((q-1)/2)
309  if (BN_is_zero(t)) // special case: p = 2^e + 1
310  {
311  if (!BN_nnmod(t, A, p, ctx)) {
312  goto end;
313  }
314  if (BN_is_zero(t)) {
315  // special case: a == 0 (mod p)
316  BN_zero(ret);
317  err = 0;
318  goto end;
319  } else if (!BN_one(x)) {
320  goto end;
321  }
322  } else {
323  if (!BN_mod_exp_mont(x, A, t, p, ctx, NULL)) {
324  goto end;
325  }
326  if (BN_is_zero(x)) {
327  // special case: a == 0 (mod p)
328  BN_zero(ret);
329  err = 0;
330  goto end;
331  }
332  }
333 
334  // b := a*x^2 (= a^q)
335  if (!BN_mod_sqr(b, x, p, ctx) ||
336  !BN_mod_mul(b, b, A, p, ctx)) {
337  goto end;
338  }
339 
340  // x := a*x (= a^((q+1)/2))
341  if (!BN_mod_mul(x, x, A, p, ctx)) {
342  goto end;
343  }
344 
345  while (1) {
346  // Now b is a^q * y^k for some even k (0 <= k < 2^E
347  // where E refers to the original value of e, which we
348  // don't keep in a variable), and x is a^((q+1)/2) * y^(k/2).
349  //
350  // We have a*b = x^2,
351  // y^2^(e-1) = -1,
352  // b^2^(e-1) = 1.
353 
354  if (BN_is_one(b)) {
355  if (!BN_copy(ret, x)) {
356  goto end;
357  }
358  err = 0;
359  goto vrfy;
360  }
361 
362 
363  // find smallest i such that b^(2^i) = 1
364  i = 1;
365  if (!BN_mod_sqr(t, b, p, ctx)) {
366  goto end;
367  }
368  while (!BN_is_one(t)) {
369  i++;
370  if (i == e) {
372  goto end;
373  }
374  if (!BN_mod_mul(t, t, t, p, ctx)) {
375  goto end;
376  }
377  }
378 
379 
380  // t := y^2^(e - i - 1)
381  if (!BN_copy(t, y)) {
382  goto end;
383  }
384  for (j = e - i - 1; j > 0; j--) {
385  if (!BN_mod_sqr(t, t, p, ctx)) {
386  goto end;
387  }
388  }
389  if (!BN_mod_mul(y, t, t, p, ctx) ||
390  !BN_mod_mul(x, x, t, p, ctx) ||
391  !BN_mod_mul(b, b, y, p, ctx)) {
392  goto end;
393  }
394  e = i;
395  }
396 
397 vrfy:
398  if (!err) {
399  // verify the result -- the input might have been not a square
400  // (test added in 0.9.8)
401 
402  if (!BN_mod_sqr(x, ret, p, ctx)) {
403  err = 1;
404  }
405 
406  if (!err && 0 != BN_cmp(x, A)) {
408  err = 1;
409  }
410  }
411 
412 end:
413  if (err) {
414  if (ret != in) {
416  }
417  ret = NULL;
418  }
419  BN_CTX_end(ctx);
420  return ret;
421 }
422 
423 int BN_sqrt(BIGNUM *out_sqrt, const BIGNUM *in, BN_CTX *ctx) {
424  BIGNUM *estimate, *tmp, *delta, *last_delta, *tmp2;
425  int ok = 0, last_delta_valid = 0;
426 
427  if (in->neg) {
429  return 0;
430  }
431  if (BN_is_zero(in)) {
432  BN_zero(out_sqrt);
433  return 1;
434  }
435 
436  BN_CTX_start(ctx);
437  if (out_sqrt == in) {
438  estimate = BN_CTX_get(ctx);
439  } else {
440  estimate = out_sqrt;
441  }
442  tmp = BN_CTX_get(ctx);
443  last_delta = BN_CTX_get(ctx);
444  delta = BN_CTX_get(ctx);
445  if (estimate == NULL || tmp == NULL || last_delta == NULL || delta == NULL) {
447  goto err;
448  }
449 
450  // We estimate that the square root of an n-bit number is 2^{n/2}.
451  if (!BN_lshift(estimate, BN_value_one(), BN_num_bits(in)/2)) {
452  goto err;
453  }
454 
455  // This is Newton's method for finding a root of the equation |estimate|^2 -
456  // |in| = 0.
457  for (;;) {
458  // |estimate| = 1/2 * (|estimate| + |in|/|estimate|)
459  if (!BN_div(tmp, NULL, in, estimate, ctx) ||
460  !BN_add(tmp, tmp, estimate) ||
461  !BN_rshift1(estimate, tmp) ||
462  // |tmp| = |estimate|^2
463  !BN_sqr(tmp, estimate, ctx) ||
464  // |delta| = |in| - |tmp|
465  !BN_sub(delta, in, tmp)) {
467  goto err;
468  }
469 
470  delta->neg = 0;
471  // The difference between |in| and |estimate| squared is required to always
472  // decrease. This ensures that the loop always terminates, but I don't have
473  // a proof that it always finds the square root for a given square.
474  if (last_delta_valid && BN_cmp(delta, last_delta) >= 0) {
475  break;
476  }
477 
478  last_delta_valid = 1;
479 
480  tmp2 = last_delta;
481  last_delta = delta;
482  delta = tmp2;
483  }
484 
485  if (BN_cmp(tmp, in) != 0) {
487  goto err;
488  }
489 
490  ok = 1;
491 
492 err:
493  if (ok && out_sqrt == in && !BN_copy(out_sqrt, estimate)) {
494  ok = 0;
495  }
496  BN_CTX_end(ctx);
497  return ok;
498 }
bn.h
bn_jacobi
#define bn_jacobi
Definition: boringssl_prefix_symbols.h:2862
BN_rshift1
#define BN_rshift1
Definition: boringssl_prefix_symbols.h:988
ctx
Definition: benchmark-async.c:30
BN_is_bit_set
#define BN_is_bit_set
Definition: boringssl_prefix_symbols.h:932
BN_clear_free
#define BN_clear_free
Definition: boringssl_prefix_symbols.h:911
BN_add_word
#define BN_add_word
Definition: boringssl_prefix_symbols.h:898
y
const double y
Definition: bloaty/third_party/googletest/googlemock/test/gmock-matchers_test.cc:3611
OPENSSL_PUT_ERROR
#define OPENSSL_PUT_ERROR(library, reason)
Definition: err.h:423
error_ref_leak.err
err
Definition: error_ref_leak.py:35
BN_free
#define BN_free
Definition: boringssl_prefix_symbols.h:923
a
int a
Definition: abseil-cpp/absl/container/internal/hash_policy_traits_test.cc:88
BN_R_NEGATIVE_NUMBER
#define BN_R_NEGATIVE_NUMBER
Definition: bn.h:1045
bignum_ctx
Definition: ctx.c:91
BN_CTX_get
#define BN_CTX_get
Definition: boringssl_prefix_symbols.h:884
xds_manager.p
p
Definition: xds_manager.py:60
BN_set_word
#define BN_set_word
Definition: boringssl_prefix_symbols.h:992
BN_sub
#define BN_sub
Definition: boringssl_prefix_symbols.h:995
BN_one
#define BN_one
Definition: boringssl_prefix_symbols.h:977
BN_value_one
const OPENSSL_EXPORT BIGNUM * BN_value_one(void)
BN_mod_sqrt
BIGNUM * BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
Definition: sqrt.c:62
BN_lshift
#define BN_lshift
Definition: boringssl_prefix_symbols.h:942
BN_R_NOT_A_SQUARE
#define BN_R_NOT_A_SQUARE
Definition: bn.h:1046
in
const char * in
Definition: third_party/abseil-cpp/absl/strings/internal/str_format/parser_test.cc:391
end
char * end
Definition: abseil-cpp/absl/strings/internal/str_format/float_conversion.cc:1008
BN_mod_exp_mont
#define BN_mod_exp_mont
Definition: boringssl_prefix_symbols.h:950
BN_sqrt
int BN_sqrt(BIGNUM *out_sqrt, const BIGNUM *in, BN_CTX *ctx)
Definition: sqrt.c:423
BN_R_TOO_MANY_ITERATIONS
#define BN_R_TOO_MANY_ITERATIONS
Definition: bn.h:1051
BN_sub_word
#define BN_sub_word
Definition: boringssl_prefix_symbols.h:996
err.h
A
#define A(T)
BN_is_odd
#define BN_is_odd
Definition: boringssl_prefix_symbols.h:934
BN_mod_mul
#define BN_mod_mul
Definition: boringssl_prefix_symbols.h:960
ERR_R_BN_LIB
#define ERR_R_BN_LIB
Definition: err.h:331
x
int x
Definition: bloaty/third_party/googletest/googlemock/test/gmock-matchers_test.cc:3610
BN_ucmp
#define BN_ucmp
Definition: boringssl_prefix_symbols.h:1001
BN_is_zero
#define BN_is_zero
Definition: boringssl_prefix_symbols.h:940
BN_R_P_IS_NOT_PRIME
#define BN_R_P_IS_NOT_PRIME
Definition: bn.h:1050
b
uint64_t b
Definition: abseil-cpp/absl/container/internal/layout_test.cc:53
BN_copy
#define BN_copy
Definition: boringssl_prefix_symbols.h:914
BN_num_bits
#define BN_num_bits
Definition: boringssl_prefix_symbols.h:974
bignum_st::neg
int neg
Definition: bn.h:979
BN_zero
#define BN_zero
Definition: boringssl_prefix_symbols.h:1004
BN_CTX_start
#define BN_CTX_start
Definition: boringssl_prefix_symbols.h:886
bignum_st
Definition: bn.h:957
BN_is_one
#define BN_is_one
Definition: boringssl_prefix_symbols.h:935
internal.h
ret
UniquePtr< SSL_SESSION > ret
Definition: ssl_x509.cc:1029
BN_pseudo_rand
#define BN_pseudo_rand
Definition: boringssl_prefix_symbols.h:982
fix_build_deps.r
r
Definition: fix_build_deps.py:491
BN_mod_sqr
#define BN_mod_sqr
Definition: boringssl_prefix_symbols.h:963
BN_cmp
#define BN_cmp
Definition: boringssl_prefix_symbols.h:912
A
Definition: miscompile_with_no_unique_address_test.cc:23
ok
bool ok
Definition: async_end2end_test.cc:197
BN_sqr
#define BN_sqr
Definition: boringssl_prefix_symbols.h:993
BN_nnmod
#define BN_nnmod
Definition: boringssl_prefix_symbols.h:972
BN_CTX_end
#define BN_CTX_end
Definition: boringssl_prefix_symbols.h:882
BN_add
#define BN_add
Definition: boringssl_prefix_symbols.h:897
bn_mod_lshift1_consttime
#define bn_mod_lshift1_consttime
Definition: boringssl_prefix_symbols.h:2877
BN_abs_is_word
#define BN_abs_is_word
Definition: boringssl_prefix_symbols.h:896
autogen_x86imm.tmp
tmp
Definition: autogen_x86imm.py:12
BN_rshift
#define BN_rshift
Definition: boringssl_prefix_symbols.h:987
BN_div
#define BN_div
Definition: boringssl_prefix_symbols.h:917
BN_new
#define BN_new
Definition: boringssl_prefix_symbols.h:971
i
uint64_t i
Definition: abseil-cpp/absl/container/btree_benchmark.cc:230
ERR_R_MALLOC_FAILURE
#define ERR_R_MALLOC_FAILURE
Definition: err.h:371


grpc
Author(s):
autogenerated on Thu Mar 13 2025 03:01:20