Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

658 linhas
16 KiB

  1. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  2. * All rights reserved.
  3. *
  4. * This package is an SSL implementation written
  5. * by Eric Young (eay@cryptsoft.com).
  6. * The implementation was written so as to conform with Netscapes SSL.
  7. *
  8. * This library is free for commercial and non-commercial use as long as
  9. * the following conditions are aheared to. The following conditions
  10. * apply to all code found in this distribution, be it the RC4, RSA,
  11. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  12. * included with this distribution is covered by the same copyright terms
  13. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  14. *
  15. * Copyright remains Eric Young's, and as such any Copyright notices in
  16. * the code are not to be removed.
  17. * If this package is used in a product, Eric Young should be given attribution
  18. * as the author of the parts of the library used.
  19. * This can be in the form of a textual message at program startup or
  20. * in documentation (online or textual) provided with the package.
  21. *
  22. * Redistribution and use in source and binary forms, with or without
  23. * modification, are permitted provided that the following conditions
  24. * are met:
  25. * 1. Redistributions of source code must retain the copyright
  26. * notice, this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright
  28. * notice, this list of conditions and the following disclaimer in the
  29. * documentation and/or other materials provided with the distribution.
  30. * 3. All advertising materials mentioning features or use of this software
  31. * must display the following acknowledgement:
  32. * "This product includes cryptographic software written by
  33. * Eric Young (eay@cryptsoft.com)"
  34. * The word 'cryptographic' can be left out if the rouines from the library
  35. * being used are not cryptographic related :-).
  36. * 4. If you include any Windows specific code (or a derivative thereof) from
  37. * the apps directory (application code) you must include an acknowledgement:
  38. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  41. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  43. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  44. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  45. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  46. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  48. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  49. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  50. * SUCH DAMAGE.
  51. *
  52. * The licence and distribution terms for any publically available version or
  53. * derivative of this code cannot be changed. i.e. this code cannot simply be
  54. * copied and put under another distribution licence
  55. * [including the GNU Public Licence.] */
  56. #include <openssl/bn.h>
  57. #include <assert.h>
  58. #include <limits.h>
  59. #include <openssl/err.h>
  60. #include "internal.h"
  61. #if !defined(BN_ULLONG)
  62. /* bn_div_words divides a double-width |h|,|l| by |d| and returns the result,
  63. * which must fit in a |BN_ULONG|. */
  64. static BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d) {
  65. BN_ULONG dh, dl, q, ret = 0, th, tl, t;
  66. int i, count = 2;
  67. if (d == 0) {
  68. return BN_MASK2;
  69. }
  70. i = BN_num_bits_word(d);
  71. assert((i == BN_BITS2) || (h <= (BN_ULONG)1 << i));
  72. i = BN_BITS2 - i;
  73. if (h >= d) {
  74. h -= d;
  75. }
  76. if (i) {
  77. d <<= i;
  78. h = (h << i) | (l >> (BN_BITS2 - i));
  79. l <<= i;
  80. }
  81. dh = (d & BN_MASK2h) >> BN_BITS4;
  82. dl = (d & BN_MASK2l);
  83. for (;;) {
  84. if ((h >> BN_BITS4) == dh) {
  85. q = BN_MASK2l;
  86. } else {
  87. q = h / dh;
  88. }
  89. th = q * dh;
  90. tl = dl * q;
  91. for (;;) {
  92. t = h - th;
  93. if ((t & BN_MASK2h) ||
  94. ((tl) <= ((t << BN_BITS4) | ((l & BN_MASK2h) >> BN_BITS4)))) {
  95. break;
  96. }
  97. q--;
  98. th -= dh;
  99. tl -= dl;
  100. }
  101. t = (tl >> BN_BITS4);
  102. tl = (tl << BN_BITS4) & BN_MASK2h;
  103. th += t;
  104. if (l < tl) {
  105. th++;
  106. }
  107. l -= tl;
  108. if (h < th) {
  109. h += d;
  110. q--;
  111. }
  112. h -= th;
  113. if (--count == 0) {
  114. break;
  115. }
  116. ret = q << BN_BITS4;
  117. h = ((h << BN_BITS4) | (l >> BN_BITS4)) & BN_MASK2;
  118. l = (l & BN_MASK2l) << BN_BITS4;
  119. }
  120. ret |= q;
  121. return ret;
  122. }
  123. #endif /* !defined(BN_ULLONG) */
  124. static inline void bn_div_rem_words(BN_ULONG *quotient_out, BN_ULONG *rem_out,
  125. BN_ULONG n0, BN_ULONG n1, BN_ULONG d0) {
  126. /* GCC and Clang generate function calls to |__udivdi3| and |__umoddi3| when
  127. * the |BN_ULLONG|-based C code is used.
  128. *
  129. * GCC bugs:
  130. * * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=14224
  131. * * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=43721
  132. * * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54183
  133. * * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58897
  134. * * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65668
  135. *
  136. * Clang bugs:
  137. * * https://llvm.org/bugs/show_bug.cgi?id=6397
  138. * * https://llvm.org/bugs/show_bug.cgi?id=12418
  139. *
  140. * These issues aren't specific to x86 and x86_64, so it might be worthwhile
  141. * to add more assembly language implementations. */
  142. #if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86) && defined(__GNUC__)
  143. __asm__ volatile (
  144. "divl %4"
  145. : "=a"(*quotient_out), "=d"(*rem_out)
  146. : "a"(n1), "d"(n0), "g"(d0)
  147. : "cc" );
  148. #elif !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) && defined(__GNUC__)
  149. __asm__ volatile (
  150. "divq %4"
  151. : "=a"(*quotient_out), "=d"(*rem_out)
  152. : "a"(n1), "d"(n0), "g"(d0)
  153. : "cc" );
  154. #else
  155. #if defined(BN_ULLONG)
  156. BN_ULLONG n = (((BN_ULLONG)n0) << BN_BITS2) | n1;
  157. *quotient_out = (BN_ULONG)(n / d0);
  158. #else
  159. *quotient_out = bn_div_words(n0, n1, d0);
  160. #endif
  161. *rem_out = n1 - (*quotient_out * d0);
  162. #endif
  163. }
  164. /* BN_div computes dv := num / divisor, rounding towards
  165. * zero, and sets up rm such that dv*divisor + rm = num holds.
  166. * Thus:
  167. * dv->neg == num->neg ^ divisor->neg (unless the result is zero)
  168. * rm->neg == num->neg (unless the remainder is zero)
  169. * If 'dv' or 'rm' is NULL, the respective value is not returned. */
  170. int BN_div(BIGNUM *dv, BIGNUM *rm, const BIGNUM *num, const BIGNUM *divisor,
  171. BN_CTX *ctx) {
  172. int norm_shift, i, loop;
  173. BIGNUM *tmp, wnum, *snum, *sdiv, *res;
  174. BN_ULONG *resp, *wnump;
  175. BN_ULONG d0, d1;
  176. int num_n, div_n;
  177. int no_branch = 0;
  178. /* Invalid zero-padding would have particularly bad consequences
  179. * so don't just rely on bn_check_top() here */
  180. if ((num->top > 0 && num->d[num->top - 1] == 0) ||
  181. (divisor->top > 0 && divisor->d[divisor->top - 1] == 0)) {
  182. OPENSSL_PUT_ERROR(BN, BN_R_NOT_INITIALIZED);
  183. return 0;
  184. }
  185. if ((num->flags & BN_FLG_CONSTTIME) != 0 ||
  186. (divisor->flags & BN_FLG_CONSTTIME) != 0) {
  187. no_branch = 1;
  188. }
  189. if (BN_is_zero(divisor)) {
  190. OPENSSL_PUT_ERROR(BN, BN_R_DIV_BY_ZERO);
  191. return 0;
  192. }
  193. if (!no_branch && BN_ucmp(num, divisor) < 0) {
  194. if (rm != NULL) {
  195. if (BN_copy(rm, num) == NULL) {
  196. return 0;
  197. }
  198. }
  199. if (dv != NULL) {
  200. BN_zero(dv);
  201. }
  202. return 1;
  203. }
  204. BN_CTX_start(ctx);
  205. tmp = BN_CTX_get(ctx);
  206. snum = BN_CTX_get(ctx);
  207. sdiv = BN_CTX_get(ctx);
  208. if (dv == NULL) {
  209. res = BN_CTX_get(ctx);
  210. } else {
  211. res = dv;
  212. }
  213. if (sdiv == NULL || res == NULL || tmp == NULL || snum == NULL) {
  214. goto err;
  215. }
  216. /* First we normalise the numbers */
  217. norm_shift = BN_BITS2 - ((BN_num_bits(divisor)) % BN_BITS2);
  218. if (!(BN_lshift(sdiv, divisor, norm_shift))) {
  219. goto err;
  220. }
  221. sdiv->neg = 0;
  222. norm_shift += BN_BITS2;
  223. if (!(BN_lshift(snum, num, norm_shift))) {
  224. goto err;
  225. }
  226. snum->neg = 0;
  227. if (no_branch) {
  228. /* Since we don't know whether snum is larger than sdiv,
  229. * we pad snum with enough zeroes without changing its
  230. * value.
  231. */
  232. if (snum->top <= sdiv->top + 1) {
  233. if (bn_wexpand(snum, sdiv->top + 2) == NULL) {
  234. goto err;
  235. }
  236. for (i = snum->top; i < sdiv->top + 2; i++) {
  237. snum->d[i] = 0;
  238. }
  239. snum->top = sdiv->top + 2;
  240. } else {
  241. if (bn_wexpand(snum, snum->top + 1) == NULL) {
  242. goto err;
  243. }
  244. snum->d[snum->top] = 0;
  245. snum->top++;
  246. }
  247. }
  248. div_n = sdiv->top;
  249. num_n = snum->top;
  250. loop = num_n - div_n;
  251. /* Lets setup a 'window' into snum
  252. * This is the part that corresponds to the current
  253. * 'area' being divided */
  254. wnum.neg = 0;
  255. wnum.d = &(snum->d[loop]);
  256. wnum.top = div_n;
  257. /* only needed when BN_ucmp messes up the values between top and max */
  258. wnum.dmax = snum->dmax - loop; /* so we don't step out of bounds */
  259. /* Get the top 2 words of sdiv */
  260. /* div_n=sdiv->top; */
  261. d0 = sdiv->d[div_n - 1];
  262. d1 = (div_n == 1) ? 0 : sdiv->d[div_n - 2];
  263. /* pointer to the 'top' of snum */
  264. wnump = &(snum->d[num_n - 1]);
  265. /* Setup to 'res' */
  266. res->neg = (num->neg ^ divisor->neg);
  267. if (!bn_wexpand(res, (loop + 1))) {
  268. goto err;
  269. }
  270. res->top = loop - no_branch;
  271. resp = &(res->d[loop - 1]);
  272. /* space for temp */
  273. if (!bn_wexpand(tmp, (div_n + 1))) {
  274. goto err;
  275. }
  276. if (!no_branch) {
  277. if (BN_ucmp(&wnum, sdiv) >= 0) {
  278. bn_sub_words(wnum.d, wnum.d, sdiv->d, div_n);
  279. *resp = 1;
  280. } else {
  281. res->top--;
  282. }
  283. }
  284. /* if res->top == 0 then clear the neg value otherwise decrease
  285. * the resp pointer */
  286. if (res->top == 0) {
  287. res->neg = 0;
  288. } else {
  289. resp--;
  290. }
  291. for (i = 0; i < loop - 1; i++, wnump--, resp--) {
  292. BN_ULONG q, l0;
  293. /* the first part of the loop uses the top two words of snum and sdiv to
  294. * calculate a BN_ULONG q such that | wnum - sdiv * q | < sdiv */
  295. BN_ULONG n0, n1, rem = 0;
  296. n0 = wnump[0];
  297. n1 = wnump[-1];
  298. if (n0 == d0) {
  299. q = BN_MASK2;
  300. } else {
  301. /* n0 < d0 */
  302. bn_div_rem_words(&q, &rem, n0, n1, d0);
  303. #ifdef BN_ULLONG
  304. BN_ULLONG t2 = (BN_ULLONG)d1 * q;
  305. for (;;) {
  306. if (t2 <= ((((BN_ULLONG)rem) << BN_BITS2) | wnump[-2])) {
  307. break;
  308. }
  309. q--;
  310. rem += d0;
  311. if (rem < d0) {
  312. break; /* don't let rem overflow */
  313. }
  314. t2 -= d1;
  315. }
  316. #else /* !BN_ULLONG */
  317. BN_ULONG t2l, t2h;
  318. BN_UMULT_LOHI(t2l, t2h, d1, q);
  319. for (;;) {
  320. if ((t2h < rem) || ((t2h == rem) && (t2l <= wnump[-2]))) {
  321. break;
  322. }
  323. q--;
  324. rem += d0;
  325. if (rem < d0) {
  326. break; /* don't let rem overflow */
  327. }
  328. if (t2l < d1) {
  329. t2h--;
  330. }
  331. t2l -= d1;
  332. }
  333. #endif /* !BN_ULLONG */
  334. }
  335. l0 = bn_mul_words(tmp->d, sdiv->d, div_n, q);
  336. tmp->d[div_n] = l0;
  337. wnum.d--;
  338. /* ingore top values of the bignums just sub the two
  339. * BN_ULONG arrays with bn_sub_words */
  340. if (bn_sub_words(wnum.d, wnum.d, tmp->d, div_n + 1)) {
  341. /* Note: As we have considered only the leading
  342. * two BN_ULONGs in the calculation of q, sdiv * q
  343. * might be greater than wnum (but then (q-1) * sdiv
  344. * is less or equal than wnum)
  345. */
  346. q--;
  347. if (bn_add_words(wnum.d, wnum.d, sdiv->d, div_n)) {
  348. /* we can't have an overflow here (assuming
  349. * that q != 0, but if q == 0 then tmp is
  350. * zero anyway) */
  351. (*wnump)++;
  352. }
  353. }
  354. /* store part of the result */
  355. *resp = q;
  356. }
  357. bn_correct_top(snum);
  358. if (rm != NULL) {
  359. /* Keep a copy of the neg flag in num because if rm==num
  360. * BN_rshift() will overwrite it.
  361. */
  362. int neg = num->neg;
  363. if (!BN_rshift(rm, snum, norm_shift)) {
  364. goto err;
  365. }
  366. if (!BN_is_zero(rm)) {
  367. rm->neg = neg;
  368. }
  369. }
  370. if (no_branch) {
  371. bn_correct_top(res);
  372. }
  373. BN_CTX_end(ctx);
  374. return 1;
  375. err:
  376. BN_CTX_end(ctx);
  377. return 0;
  378. }
  379. int BN_nnmod(BIGNUM *r, const BIGNUM *m, const BIGNUM *d, BN_CTX *ctx) {
  380. if (!(BN_mod(r, m, d, ctx))) {
  381. return 0;
  382. }
  383. if (!r->neg) {
  384. return 1;
  385. }
  386. /* now -|d| < r < 0, so we have to set r := r + |d|. */
  387. return (d->neg ? BN_sub : BN_add)(r, r, d);
  388. }
  389. int BN_mod_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
  390. BN_CTX *ctx) {
  391. if (!BN_add(r, a, b)) {
  392. return 0;
  393. }
  394. return BN_nnmod(r, r, m, ctx);
  395. }
  396. int BN_mod_add_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
  397. const BIGNUM *m) {
  398. if (!BN_uadd(r, a, b)) {
  399. return 0;
  400. }
  401. if (BN_ucmp(r, m) >= 0) {
  402. return BN_usub(r, r, m);
  403. }
  404. return 1;
  405. }
  406. int BN_mod_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
  407. BN_CTX *ctx) {
  408. if (!BN_sub(r, a, b)) {
  409. return 0;
  410. }
  411. return BN_nnmod(r, r, m, ctx);
  412. }
  413. /* BN_mod_sub variant that may be used if both a and b are non-negative
  414. * and less than m */
  415. int BN_mod_sub_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
  416. const BIGNUM *m) {
  417. if (!BN_sub(r, a, b)) {
  418. return 0;
  419. }
  420. if (r->neg) {
  421. return BN_add(r, r, m);
  422. }
  423. return 1;
  424. }
  425. int BN_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
  426. BN_CTX *ctx) {
  427. BIGNUM *t;
  428. int ret = 0;
  429. BN_CTX_start(ctx);
  430. t = BN_CTX_get(ctx);
  431. if (t == NULL) {
  432. goto err;
  433. }
  434. if (a == b) {
  435. if (!BN_sqr(t, a, ctx)) {
  436. goto err;
  437. }
  438. } else {
  439. if (!BN_mul(t, a, b, ctx)) {
  440. goto err;
  441. }
  442. }
  443. if (!BN_nnmod(r, t, m, ctx)) {
  444. goto err;
  445. }
  446. ret = 1;
  447. err:
  448. BN_CTX_end(ctx);
  449. return ret;
  450. }
  451. int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {
  452. if (!BN_sqr(r, a, ctx)) {
  453. return 0;
  454. }
  455. /* r->neg == 0, thus we don't need BN_nnmod */
  456. return BN_mod(r, r, m, ctx);
  457. }
  458. int BN_mod_lshift(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m,
  459. BN_CTX *ctx) {
  460. BIGNUM *abs_m = NULL;
  461. int ret;
  462. if (!BN_nnmod(r, a, m, ctx)) {
  463. return 0;
  464. }
  465. if (m->neg) {
  466. abs_m = BN_dup(m);
  467. if (abs_m == NULL) {
  468. return 0;
  469. }
  470. abs_m->neg = 0;
  471. }
  472. ret = BN_mod_lshift_quick(r, r, n, (abs_m ? abs_m : m));
  473. BN_free(abs_m);
  474. return ret;
  475. }
  476. int BN_mod_lshift_quick(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m) {
  477. if (r != a) {
  478. if (BN_copy(r, a) == NULL) {
  479. return 0;
  480. }
  481. }
  482. while (n > 0) {
  483. int max_shift;
  484. /* 0 < r < m */
  485. max_shift = BN_num_bits(m) - BN_num_bits(r);
  486. /* max_shift >= 0 */
  487. if (max_shift < 0) {
  488. OPENSSL_PUT_ERROR(BN, BN_R_INPUT_NOT_REDUCED);
  489. return 0;
  490. }
  491. if (max_shift > n) {
  492. max_shift = n;
  493. }
  494. if (max_shift) {
  495. if (!BN_lshift(r, r, max_shift)) {
  496. return 0;
  497. }
  498. n -= max_shift;
  499. } else {
  500. if (!BN_lshift1(r, r)) {
  501. return 0;
  502. }
  503. --n;
  504. }
  505. /* BN_num_bits(r) <= BN_num_bits(m) */
  506. if (BN_cmp(r, m) >= 0) {
  507. if (!BN_sub(r, r, m)) {
  508. return 0;
  509. }
  510. }
  511. }
  512. return 1;
  513. }
  514. int BN_mod_lshift1(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {
  515. if (!BN_lshift1(r, a)) {
  516. return 0;
  517. }
  518. return BN_nnmod(r, r, m, ctx);
  519. }
  520. int BN_mod_lshift1_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *m) {
  521. if (!BN_lshift1(r, a)) {
  522. return 0;
  523. }
  524. if (BN_cmp(r, m) >= 0) {
  525. return BN_sub(r, r, m);
  526. }
  527. return 1;
  528. }
  529. BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w) {
  530. BN_ULONG ret = 0;
  531. int i, j;
  532. w &= BN_MASK2;
  533. if (!w) {
  534. /* actually this an error (division by zero) */
  535. return (BN_ULONG) - 1;
  536. }
  537. if (a->top == 0) {
  538. return 0;
  539. }
  540. /* normalize input for |bn_div_rem_words|. */
  541. j = BN_BITS2 - BN_num_bits_word(w);
  542. w <<= j;
  543. if (!BN_lshift(a, a, j)) {
  544. return (BN_ULONG) - 1;
  545. }
  546. for (i = a->top - 1; i >= 0; i--) {
  547. BN_ULONG l = a->d[i];
  548. BN_ULONG d;
  549. BN_ULONG unused_rem;
  550. bn_div_rem_words(&d, &unused_rem, ret, l, w);
  551. ret = (l - ((d * w) & BN_MASK2)) & BN_MASK2;
  552. a->d[i] = d;
  553. }
  554. if ((a->top > 0) && (a->d[a->top - 1] == 0)) {
  555. a->top--;
  556. }
  557. ret >>= j;
  558. return ret;
  559. }
  560. BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w) {
  561. #ifndef BN_ULLONG
  562. BN_ULONG ret = 0;
  563. #else
  564. BN_ULLONG ret = 0;
  565. #endif
  566. int i;
  567. if (w == 0) {
  568. return (BN_ULONG) -1;
  569. }
  570. w &= BN_MASK2;
  571. for (i = a->top - 1; i >= 0; i--) {
  572. #ifndef BN_ULLONG
  573. ret = ((ret << BN_BITS4) | ((a->d[i] >> BN_BITS4) & BN_MASK2l)) % w;
  574. ret = ((ret << BN_BITS4) | (a->d[i] & BN_MASK2l)) % w;
  575. #else
  576. ret = (BN_ULLONG)(((ret << (BN_ULLONG)BN_BITS2) | a->d[i]) % (BN_ULLONG)w);
  577. #endif
  578. }
  579. return (BN_ULONG)ret;
  580. }