• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1diff --git a/crypto/bn/bn_sqrt.c b/crypto/bn/bn_sqrt.c
2index 1723d5ded5..53b0f55985 100644
3--- a/crypto/bn/bn_sqrt.c
4+++ b/crypto/bn/bn_sqrt.c
5@@ -14,7 +14,8 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
6 /*
7  * Returns 'ret' such that ret^2 == a (mod p), using the Tonelli/Shanks
8  * algorithm (cf. Henri Cohen, "A Course in Algebraic Computational Number
9- * Theory", algorithm 1.5.1). 'p' must be prime!
10+ * Theory", algorithm 1.5.1). 'p' must be prime, otherwise an error or
11+ * an incorrect "result" will be returned.
12  */
13 {
14     BIGNUM *ret = in;
15@@ -301,18 +302,23 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
16             goto vrfy;
17         }
18
19-        /* find smallest  i  such that  b^(2^i) = 1 */
20-        i = 1;
21-        if (!BN_mod_sqr(t, b, p, ctx))
22-            goto end;
23-        while (!BN_is_one(t)) {
24-            i++;
25-            if (i == e) {
26-                BNerr(BN_F_BN_MOD_SQRT, BN_R_NOT_A_SQUARE);
27-                goto end;
28+        /* Find the smallest i, 0 < i < e, such that b^(2^i) = 1. */
29+        for (i = 1; i < e; i++) {
30+            if (i == 1) {
31+                if (!BN_mod_sqr(t, b, p, ctx))
32+                    goto end;
33+
34+            } else {
35+                if (!BN_mod_mul(t, t, t, p, ctx))
36+                    goto end;
37             }
38-            if (!BN_mod_mul(t, t, t, p, ctx))
39-                goto end;
40+            if (BN_is_one(t))
41+                break;
42+        }
43+        /* If not found, a is not a square or p is not prime. */
44+        if (i >= e) {
45+            BNerr(BN_F_BN_MOD_SQRT, BN_R_NOT_A_SQUARE);
46+            goto end;
47         }
48
49         /* t := y^2^(e - i - 1) */