• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the OpenSSL license (the "License").  You may not use
5 * this file except in compliance with the License.  You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10#include <openssl/bn.h>
11
12#include <openssl/err.h>
13
14#include "internal.h"
15
16
17BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) {
18  // Compute a square root of |a| mod |p| using the Tonelli/Shanks algorithm
19  // (cf. Henri Cohen, "A Course in Algebraic Computational Number Theory",
20  // algorithm 1.5.1). |p| is assumed to be a prime.
21
22  BIGNUM *ret = in;
23  int err = 1;
24  int r;
25  BIGNUM *A, *b, *q, *t, *x, *y;
26  int e, i, j;
27
28  if (!BN_is_odd(p) || BN_abs_is_word(p, 1)) {
29    if (BN_abs_is_word(p, 2)) {
30      if (ret == NULL) {
31        ret = BN_new();
32      }
33      if (ret == NULL ||
34          !BN_set_word(ret, BN_is_bit_set(a, 0))) {
35        if (ret != in) {
36          BN_free(ret);
37        }
38        return NULL;
39      }
40      return ret;
41    }
42
43    OPENSSL_PUT_ERROR(BN, BN_R_P_IS_NOT_PRIME);
44    return NULL;
45  }
46
47  if (BN_is_zero(a) || BN_is_one(a)) {
48    if (ret == NULL) {
49      ret = BN_new();
50    }
51    if (ret == NULL ||
52        !BN_set_word(ret, BN_is_one(a))) {
53      if (ret != in) {
54        BN_free(ret);
55      }
56      return NULL;
57    }
58    return ret;
59  }
60
61  BN_CTX_start(ctx);
62  A = BN_CTX_get(ctx);
63  b = BN_CTX_get(ctx);
64  q = BN_CTX_get(ctx);
65  t = BN_CTX_get(ctx);
66  x = BN_CTX_get(ctx);
67  y = BN_CTX_get(ctx);
68  if (y == NULL) {
69    goto end;
70  }
71
72  if (ret == NULL) {
73    ret = BN_new();
74  }
75  if (ret == NULL) {
76    goto end;
77  }
78
79  // A = a mod p
80  if (!BN_nnmod(A, a, p, ctx)) {
81    goto end;
82  }
83
84  // now write  |p| - 1  as  2^e*q  where  q  is odd
85  e = 1;
86  while (!BN_is_bit_set(p, e)) {
87    e++;
88  }
89  // we'll set  q  later (if needed)
90
91  if (e == 1) {
92    // The easy case:  (|p|-1)/2  is odd, so 2 has an inverse
93    // modulo  (|p|-1)/2,  and square roots can be computed
94    // directly by modular exponentiation.
95    // We have
96    //     2 * (|p|+1)/4 == 1   (mod (|p|-1)/2),
97    // so we can use exponent  (|p|+1)/4,  i.e.  (|p|-3)/4 + 1.
98    if (!BN_rshift(q, p, 2)) {
99      goto end;
100    }
101    q->neg = 0;
102    if (!BN_add_word(q, 1) ||
103        !BN_mod_exp_mont(ret, A, q, p, ctx, NULL)) {
104      goto end;
105    }
106    err = 0;
107    goto vrfy;
108  }
109
110  if (e == 2) {
111    // |p| == 5  (mod 8)
112    //
113    // In this case  2  is always a non-square since
114    // Legendre(2,p) = (-1)^((p^2-1)/8)  for any odd prime.
115    // So if  a  really is a square, then  2*a  is a non-square.
116    // Thus for
117    //      b := (2*a)^((|p|-5)/8),
118    //      i := (2*a)*b^2
119    // we have
120    //     i^2 = (2*a)^((1 + (|p|-5)/4)*2)
121    //         = (2*a)^((p-1)/2)
122    //         = -1;
123    // so if we set
124    //      x := a*b*(i-1),
125    // then
126    //     x^2 = a^2 * b^2 * (i^2 - 2*i + 1)
127    //         = a^2 * b^2 * (-2*i)
128    //         = a*(-i)*(2*a*b^2)
129    //         = a*(-i)*i
130    //         = a.
131    //
132    // (This is due to A.O.L. Atkin,
133    // <URL:
134    //http://listserv.nodak.edu/scripts/wa.exe?A2=ind9211&L=nmbrthry&O=T&P=562>,
135    // November 1992.)
136
137    // t := 2*a
138    if (!bn_mod_lshift1_consttime(t, A, p, ctx)) {
139      goto end;
140    }
141
142    // b := (2*a)^((|p|-5)/8)
143    if (!BN_rshift(q, p, 3)) {
144      goto end;
145    }
146    q->neg = 0;
147    if (!BN_mod_exp_mont(b, t, q, p, ctx, NULL)) {
148      goto end;
149    }
150
151    // y := b^2
152    if (!BN_mod_sqr(y, b, p, ctx)) {
153      goto end;
154    }
155
156    // t := (2*a)*b^2 - 1
157    if (!BN_mod_mul(t, t, y, p, ctx) ||
158        !BN_sub_word(t, 1)) {
159      goto end;
160    }
161
162    // x = a*b*t
163    if (!BN_mod_mul(x, A, b, p, ctx) ||
164        !BN_mod_mul(x, x, t, p, ctx)) {
165      goto end;
166    }
167
168    if (!BN_copy(ret, x)) {
169      goto end;
170    }
171    err = 0;
172    goto vrfy;
173  }
174
175  // e > 2, so we really have to use the Tonelli/Shanks algorithm.
176  // First, find some  y  that is not a square.
177  if (!BN_copy(q, p)) {
178    goto end;  // use 'q' as temp
179  }
180  q->neg = 0;
181  i = 2;
182  do {
183    // For efficiency, try small numbers first;
184    // if this fails, try random numbers.
185    if (i < 22) {
186      if (!BN_set_word(y, i)) {
187        goto end;
188      }
189    } else {
190      if (!BN_pseudo_rand(y, BN_num_bits(p), 0, 0)) {
191        goto end;
192      }
193      if (BN_ucmp(y, p) >= 0) {
194        if (BN_usub(y, y, p)) {
195          goto end;
196        }
197      }
198      // now 0 <= y < |p|
199      if (BN_is_zero(y)) {
200        if (!BN_set_word(y, i)) {
201          goto end;
202        }
203      }
204    }
205
206    r = bn_jacobi(y, q, ctx);  // here 'q' is |p|
207    if (r < -1) {
208      goto end;
209    }
210    if (r == 0) {
211      // m divides p
212      OPENSSL_PUT_ERROR(BN, BN_R_P_IS_NOT_PRIME);
213      goto end;
214    }
215  } while (r == 1 && ++i < 82);
216
217  if (r != -1) {
218    // Many rounds and still no non-square -- this is more likely
219    // a bug than just bad luck.
220    // Even if  p  is not prime, we should have found some  y
221    // such that r == -1.
222    OPENSSL_PUT_ERROR(BN, BN_R_TOO_MANY_ITERATIONS);
223    goto end;
224  }
225
226  // Here's our actual 'q':
227  if (!BN_rshift(q, q, e)) {
228    goto end;
229  }
230
231  // Now that we have some non-square, we can find an element
232  // of order  2^e  by computing its q'th power.
233  if (!BN_mod_exp_mont(y, y, q, p, ctx, NULL)) {
234    goto end;
235  }
236  if (BN_is_one(y)) {
237    OPENSSL_PUT_ERROR(BN, BN_R_P_IS_NOT_PRIME);
238    goto end;
239  }
240
241  // Now we know that (if  p  is indeed prime) there is an integer
242  // k,  0 <= k < 2^e,  such that
243  //
244  //      a^q * y^k == 1   (mod p).
245  //
246  // As  a^q  is a square and  y  is not,  k  must be even.
247  // q+1  is even, too, so there is an element
248  //
249  //     X := a^((q+1)/2) * y^(k/2),
250  //
251  // and it satisfies
252  //
253  //     X^2 = a^q * a     * y^k
254  //         = a,
255  //
256  // so it is the square root that we are looking for.
257
258  // t := (q-1)/2  (note that  q  is odd)
259  if (!BN_rshift1(t, q)) {
260    goto end;
261  }
262
263  // x := a^((q-1)/2)
264  if (BN_is_zero(t)) {  // special case: p = 2^e + 1
265    if (!BN_nnmod(t, A, p, ctx)) {
266      goto end;
267    }
268    if (BN_is_zero(t)) {
269      // special case: a == 0  (mod p)
270      BN_zero(ret);
271      err = 0;
272      goto end;
273    } else if (!BN_one(x)) {
274      goto end;
275    }
276  } else {
277    if (!BN_mod_exp_mont(x, A, t, p, ctx, NULL)) {
278      goto end;
279    }
280    if (BN_is_zero(x)) {
281      // special case: a == 0  (mod p)
282      BN_zero(ret);
283      err = 0;
284      goto end;
285    }
286  }
287
288  // b := a*x^2  (= a^q)
289  if (!BN_mod_sqr(b, x, p, ctx) ||
290      !BN_mod_mul(b, b, A, p, ctx)) {
291    goto end;
292  }
293
294  // x := a*x    (= a^((q+1)/2))
295  if (!BN_mod_mul(x, x, A, p, ctx)) {
296    goto end;
297  }
298
299  while (1) {
300    // Now  b  is  a^q * y^k  for some even  k  (0 <= k < 2^E
301    // where  E  refers to the original value of  e,  which we
302    // don't keep in a variable),  and  x  is  a^((q+1)/2) * y^(k/2).
303    //
304    // We have  a*b = x^2,
305    //    y^2^(e-1) = -1,
306    //    b^2^(e-1) = 1.
307    if (BN_is_one(b)) {
308      if (!BN_copy(ret, x)) {
309        goto end;
310      }
311      err = 0;
312      goto vrfy;
313    }
314
315    // Find the smallest i, 0 < i < e, such that b^(2^i) = 1
316    for (i = 1; i < e; i++) {
317      if (i == 1) {
318        if (!BN_mod_sqr(t, b, p, ctx)) {
319          goto end;
320        }
321      } else {
322        if (!BN_mod_mul(t, t, t, p, ctx)) {
323          goto end;
324        }
325      }
326      if (BN_is_one(t)) {
327        break;
328      }
329    }
330    // If not found, a is not a square or p is not a prime.
331    if (i >= e) {
332      OPENSSL_PUT_ERROR(BN, BN_R_NOT_A_SQUARE);
333      goto end;
334    }
335
336    // t := y^2^(e - i - 1)
337    if (!BN_copy(t, y)) {
338      goto end;
339    }
340    for (j = e - i - 1; j > 0; j--) {
341      if (!BN_mod_sqr(t, t, p, ctx)) {
342        goto end;
343      }
344    }
345    if (!BN_mod_mul(y, t, t, p, ctx) ||
346        !BN_mod_mul(x, x, t, p, ctx) ||
347        !BN_mod_mul(b, b, y, p, ctx)) {
348      goto end;
349    }
350
351    // e decreases each iteration, so this loop will terminate.
352    assert(i < e);
353    e = i;
354  }
355
356vrfy:
357  if (!err) {
358    // Verify the result. The input might have been not a square.
359    if (!BN_mod_sqr(x, ret, p, ctx)) {
360      err = 1;
361    }
362
363    if (!err && 0 != BN_cmp(x, A)) {
364      OPENSSL_PUT_ERROR(BN, BN_R_NOT_A_SQUARE);
365      err = 1;
366    }
367  }
368
369end:
370  if (err) {
371    if (ret != in) {
372      BN_clear_free(ret);
373    }
374    ret = NULL;
375  }
376  BN_CTX_end(ctx);
377  return ret;
378}
379
380int BN_sqrt(BIGNUM *out_sqrt, const BIGNUM *in, BN_CTX *ctx) {
381  BIGNUM *estimate, *tmp, *delta, *last_delta, *tmp2;
382  int ok = 0, last_delta_valid = 0;
383
384  if (in->neg) {
385    OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
386    return 0;
387  }
388  if (BN_is_zero(in)) {
389    BN_zero(out_sqrt);
390    return 1;
391  }
392
393  BN_CTX_start(ctx);
394  if (out_sqrt == in) {
395    estimate = BN_CTX_get(ctx);
396  } else {
397    estimate = out_sqrt;
398  }
399  tmp = BN_CTX_get(ctx);
400  last_delta = BN_CTX_get(ctx);
401  delta = BN_CTX_get(ctx);
402  if (estimate == NULL || tmp == NULL || last_delta == NULL || delta == NULL) {
403    goto err;
404  }
405
406  // We estimate that the square root of an n-bit number is 2^{n/2}.
407  if (!BN_lshift(estimate, BN_value_one(), BN_num_bits(in)/2)) {
408    goto err;
409  }
410
411  // This is Newton's method for finding a root of the equation |estimate|^2 -
412  // |in| = 0.
413  for (;;) {
414    // |estimate| = 1/2 * (|estimate| + |in|/|estimate|)
415    if (!BN_div(tmp, NULL, in, estimate, ctx) ||
416        !BN_add(tmp, tmp, estimate) ||
417        !BN_rshift1(estimate, tmp) ||
418        // |tmp| = |estimate|^2
419        !BN_sqr(tmp, estimate, ctx) ||
420        // |delta| = |in| - |tmp|
421        !BN_sub(delta, in, tmp)) {
422      OPENSSL_PUT_ERROR(BN, ERR_R_BN_LIB);
423      goto err;
424    }
425
426    delta->neg = 0;
427    // The difference between |in| and |estimate| squared is required to always
428    // decrease. This ensures that the loop always terminates, but I don't have
429    // a proof that it always finds the square root for a given square.
430    if (last_delta_valid && BN_cmp(delta, last_delta) >= 0) {
431      break;
432    }
433
434    last_delta_valid = 1;
435
436    tmp2 = last_delta;
437    last_delta = delta;
438    delta = tmp2;
439  }
440
441  if (BN_cmp(tmp, in) != 0) {
442    OPENSSL_PUT_ERROR(BN, BN_R_NOT_A_SQUARE);
443    goto err;
444  }
445
446  ok = 1;
447
448err:
449  if (ok && out_sqrt == in && !BN_copy(out_sqrt, estimate)) {
450    ok = 0;
451  }
452  BN_CTX_end(ctx);
453  return ok;
454}
455