sqrt.c 12 KB

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