sqrt.c 12 KB

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