You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

626 line
15 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 <limits.h>
  58. #include <openssl/err.h>
  59. #include "internal.h"
  60. #define asm __asm__
  61. #if !defined(OPENSSL_NO_ASM)
  62. # if defined(__GNUC__) && __GNUC__>=2
  63. # if defined(OPENSSL_X86)
  64. /*
  65. * There were two reasons for implementing this template:
  66. * - GNU C generates a call to a function (__udivdi3 to be exact)
  67. * in reply to ((((BN_ULLONG)n0)<<BN_BITS2)|n1)/d0 (I fail to
  68. * understand why...);
  69. * - divl doesn't only calculate quotient, but also leaves
  70. * remainder in %edx which we can definitely use here:-)
  71. *
  72. * <appro@fy.chalmers.se>
  73. */
  74. #undef div_asm
  75. # define div_asm(n0,n1,d0) \
  76. ({ asm volatile ( \
  77. "divl %4" \
  78. : "=a"(q), "=d"(rem) \
  79. : "a"(n1), "d"(n0), "g"(d0) \
  80. : "cc"); \
  81. q; \
  82. })
  83. # define REMAINDER_IS_ALREADY_CALCULATED
  84. # elif defined(OPENSSL_X86_64)
  85. /*
  86. * Same story here, but it's 128-bit by 64-bit division. Wow!
  87. * <appro@fy.chalmers.se>
  88. */
  89. # undef div_asm
  90. # define div_asm(n0,n1,d0) \
  91. ({ asm volatile ( \
  92. "divq %4" \
  93. : "=a"(q), "=d"(rem) \
  94. : "a"(n1), "d"(n0), "g"(d0) \
  95. : "cc"); \
  96. q; \
  97. })
  98. # define REMAINDER_IS_ALREADY_CALCULATED
  99. # endif /* __<cpu> */
  100. # endif /* __GNUC__ */
  101. #endif /* OPENSSL_NO_ASM */
  102. /* BN_div computes dv := num / divisor, rounding towards
  103. * zero, and sets up rm such that dv*divisor + rm = num holds.
  104. * Thus:
  105. * dv->neg == num->neg ^ divisor->neg (unless the result is zero)
  106. * rm->neg == num->neg (unless the remainder is zero)
  107. * If 'dv' or 'rm' is NULL, the respective value is not returned. */
  108. int BN_div(BIGNUM *dv, BIGNUM *rm, const BIGNUM *num, const BIGNUM *divisor,
  109. BN_CTX *ctx) {
  110. int norm_shift, i, loop;
  111. BIGNUM *tmp, wnum, *snum, *sdiv, *res;
  112. BN_ULONG *resp, *wnump;
  113. BN_ULONG d0, d1;
  114. int num_n, div_n;
  115. int no_branch = 0;
  116. /* Invalid zero-padding would have particularly bad consequences
  117. * so don't just rely on bn_check_top() here */
  118. if ((num->top > 0 && num->d[num->top - 1] == 0) ||
  119. (divisor->top > 0 && divisor->d[divisor->top - 1] == 0)) {
  120. OPENSSL_PUT_ERROR(BN, BN_div, BN_R_NOT_INITIALIZED);
  121. return 0;
  122. }
  123. if ((num->flags & BN_FLG_CONSTTIME) != 0 ||
  124. (divisor->flags & BN_FLG_CONSTTIME) != 0) {
  125. no_branch = 1;
  126. }
  127. if (BN_is_zero(divisor)) {
  128. OPENSSL_PUT_ERROR(BN, BN_div, BN_R_DIV_BY_ZERO);
  129. return 0;
  130. }
  131. if (!no_branch && BN_ucmp(num, divisor) < 0) {
  132. if (rm != NULL) {
  133. if (BN_copy(rm, num) == NULL) {
  134. return 0;
  135. }
  136. }
  137. if (dv != NULL) {
  138. BN_zero(dv);
  139. }
  140. return 1;
  141. }
  142. BN_CTX_start(ctx);
  143. tmp = BN_CTX_get(ctx);
  144. snum = BN_CTX_get(ctx);
  145. sdiv = BN_CTX_get(ctx);
  146. if (dv == NULL) {
  147. res = BN_CTX_get(ctx);
  148. } else {
  149. res = dv;
  150. }
  151. if (sdiv == NULL || res == NULL || tmp == NULL || snum == NULL) {
  152. goto err;
  153. }
  154. /* First we normalise the numbers */
  155. norm_shift = BN_BITS2 - ((BN_num_bits(divisor)) % BN_BITS2);
  156. if (!(BN_lshift(sdiv, divisor, norm_shift))) {
  157. goto err;
  158. }
  159. sdiv->neg = 0;
  160. norm_shift += BN_BITS2;
  161. if (!(BN_lshift(snum, num, norm_shift))) {
  162. goto err;
  163. }
  164. snum->neg = 0;
  165. if (no_branch) {
  166. /* Since we don't know whether snum is larger than sdiv,
  167. * we pad snum with enough zeroes without changing its
  168. * value.
  169. */
  170. if (snum->top <= sdiv->top + 1) {
  171. if (bn_wexpand(snum, sdiv->top + 2) == NULL) {
  172. goto err;
  173. }
  174. for (i = snum->top; i < sdiv->top + 2; i++) {
  175. snum->d[i] = 0;
  176. }
  177. snum->top = sdiv->top + 2;
  178. } else {
  179. if (bn_wexpand(snum, snum->top + 1) == NULL) {
  180. goto err;
  181. }
  182. snum->d[snum->top] = 0;
  183. snum->top++;
  184. }
  185. }
  186. div_n = sdiv->top;
  187. num_n = snum->top;
  188. loop = num_n - div_n;
  189. /* Lets setup a 'window' into snum
  190. * This is the part that corresponds to the current
  191. * 'area' being divided */
  192. wnum.neg = 0;
  193. wnum.d = &(snum->d[loop]);
  194. wnum.top = div_n;
  195. /* only needed when BN_ucmp messes up the values between top and max */
  196. wnum.dmax = snum->dmax - loop; /* so we don't step out of bounds */
  197. /* Get the top 2 words of sdiv */
  198. /* div_n=sdiv->top; */
  199. d0 = sdiv->d[div_n - 1];
  200. d1 = (div_n == 1) ? 0 : sdiv->d[div_n - 2];
  201. /* pointer to the 'top' of snum */
  202. wnump = &(snum->d[num_n - 1]);
  203. /* Setup to 'res' */
  204. res->neg = (num->neg ^ divisor->neg);
  205. if (!bn_wexpand(res, (loop + 1))) {
  206. goto err;
  207. }
  208. res->top = loop - no_branch;
  209. resp = &(res->d[loop - 1]);
  210. /* space for temp */
  211. if (!bn_wexpand(tmp, (div_n + 1))) {
  212. goto err;
  213. }
  214. if (!no_branch) {
  215. if (BN_ucmp(&wnum, sdiv) >= 0) {
  216. bn_sub_words(wnum.d, wnum.d, sdiv->d, div_n);
  217. *resp = 1;
  218. } else {
  219. res->top--;
  220. }
  221. }
  222. /* if res->top == 0 then clear the neg value otherwise decrease
  223. * the resp pointer */
  224. if (res->top == 0) {
  225. res->neg = 0;
  226. } else {
  227. resp--;
  228. }
  229. for (i = 0; i < loop - 1; i++, wnump--, resp--) {
  230. BN_ULONG q, l0;
  231. /* the first part of the loop uses the top two words of snum and sdiv to
  232. * calculate a BN_ULONG q such that | wnum - sdiv * q | < sdiv */
  233. BN_ULONG n0, n1, rem = 0;
  234. n0 = wnump[0];
  235. n1 = wnump[-1];
  236. if (n0 == d0) {
  237. q = BN_MASK2;
  238. } else {
  239. /* n0 < d0 */
  240. #ifdef BN_LLONG
  241. BN_ULLONG t2;
  242. #if defined(BN_LLONG) && !defined(div_asm)
  243. q = (BN_ULONG)(((((BN_ULLONG)n0) << BN_BITS2) | n1) / d0);
  244. #else
  245. q = div_asm(n0, n1, d0);
  246. #endif
  247. #ifndef REMAINDER_IS_ALREADY_CALCULATED
  248. /* rem doesn't have to be BN_ULLONG. The least we know it's less that d0,
  249. * isn't it? */
  250. rem = (n1 - q * d0) & BN_MASK2;
  251. #endif
  252. t2 = (BN_ULLONG)d1 * q;
  253. for (;;) {
  254. if (t2 <= ((((BN_ULLONG)rem) << BN_BITS2) | wnump[-2])) {
  255. break;
  256. }
  257. q--;
  258. rem += d0;
  259. if (rem < d0) {
  260. break; /* don't let rem overflow */
  261. }
  262. t2 -= d1;
  263. }
  264. #else /* !BN_LLONG */
  265. BN_ULONG t2l, t2h;
  266. #if defined(div_asm)
  267. q = div_asm(n0, n1, d0);
  268. #else
  269. q = bn_div_words(n0, n1, d0);
  270. #endif
  271. #ifndef REMAINDER_IS_ALREADY_CALCULATED
  272. rem = (n1 - q * d0) & BN_MASK2;
  273. #endif
  274. #if defined(BN_UMULT_LOHI)
  275. BN_UMULT_LOHI(t2l, t2h, d1, q);
  276. #elif defined(BN_UMULT_HIGH)
  277. t2l = d1 * q;
  278. t2h = BN_UMULT_HIGH(d1, q);
  279. #else
  280. {
  281. BN_ULONG ql, qh;
  282. t2l = LBITS(d1);
  283. t2h = HBITS(d1);
  284. ql = LBITS(q);
  285. qh = HBITS(q);
  286. mul64(t2l, t2h, ql, qh); /* t2=(BN_ULLONG)d1*q; */
  287. }
  288. #endif
  289. for (;;) {
  290. if ((t2h < rem) || ((t2h == rem) && (t2l <= wnump[-2]))) {
  291. break;
  292. }
  293. q--;
  294. rem += d0;
  295. if (rem < d0) {
  296. break; /* don't let rem overflow */
  297. }
  298. if (t2l < d1) {
  299. t2h--;
  300. }
  301. t2l -= d1;
  302. }
  303. #endif /* !BN_LLONG */
  304. }
  305. l0 = bn_mul_words(tmp->d, sdiv->d, div_n, q);
  306. tmp->d[div_n] = l0;
  307. wnum.d--;
  308. /* ingore top values of the bignums just sub the two
  309. * BN_ULONG arrays with bn_sub_words */
  310. if (bn_sub_words(wnum.d, wnum.d, tmp->d, div_n + 1)) {
  311. /* Note: As we have considered only the leading
  312. * two BN_ULONGs in the calculation of q, sdiv * q
  313. * might be greater than wnum (but then (q-1) * sdiv
  314. * is less or equal than wnum)
  315. */
  316. q--;
  317. if (bn_add_words(wnum.d, wnum.d, sdiv->d, div_n)) {
  318. /* we can't have an overflow here (assuming
  319. * that q != 0, but if q == 0 then tmp is
  320. * zero anyway) */
  321. (*wnump)++;
  322. }
  323. }
  324. /* store part of the result */
  325. *resp = q;
  326. }
  327. bn_correct_top(snum);
  328. if (rm != NULL) {
  329. /* Keep a copy of the neg flag in num because if rm==num
  330. * BN_rshift() will overwrite it.
  331. */
  332. int neg = num->neg;
  333. if (!BN_rshift(rm, snum, norm_shift)) {
  334. goto err;
  335. }
  336. if (!BN_is_zero(rm)) {
  337. rm->neg = neg;
  338. }
  339. }
  340. if (no_branch) {
  341. bn_correct_top(res);
  342. }
  343. BN_CTX_end(ctx);
  344. return 1;
  345. err:
  346. BN_CTX_end(ctx);
  347. return 0;
  348. }
  349. int BN_nnmod(BIGNUM *r, const BIGNUM *m, const BIGNUM *d, BN_CTX *ctx) {
  350. if (!(BN_mod(r, m, d, ctx))) {
  351. return 0;
  352. }
  353. if (!r->neg) {
  354. return 1;
  355. }
  356. /* now -|d| < r < 0, so we have to set r := r + |d|. */
  357. return (d->neg ? BN_sub : BN_add)(r, r, d);
  358. }
  359. int BN_mod_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
  360. BN_CTX *ctx) {
  361. if (!BN_add(r, a, b)) {
  362. return 0;
  363. }
  364. return BN_nnmod(r, r, m, ctx);
  365. }
  366. int BN_mod_add_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
  367. const BIGNUM *m) {
  368. if (!BN_uadd(r, a, b)) {
  369. return 0;
  370. }
  371. if (BN_ucmp(r, m) >= 0) {
  372. return BN_usub(r, r, m);
  373. }
  374. return 1;
  375. }
  376. int BN_mod_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
  377. BN_CTX *ctx) {
  378. if (!BN_sub(r, a, b)) {
  379. return 0;
  380. }
  381. return BN_nnmod(r, r, m, ctx);
  382. }
  383. /* BN_mod_sub variant that may be used if both a and b are non-negative
  384. * and less than m */
  385. int BN_mod_sub_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
  386. const BIGNUM *m) {
  387. if (!BN_sub(r, a, b)) {
  388. return 0;
  389. }
  390. if (r->neg) {
  391. return BN_add(r, r, m);
  392. }
  393. return 1;
  394. }
  395. int BN_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
  396. BN_CTX *ctx) {
  397. BIGNUM *t;
  398. int ret = 0;
  399. BN_CTX_start(ctx);
  400. t = BN_CTX_get(ctx);
  401. if (t == NULL) {
  402. goto err;
  403. }
  404. if (a == b) {
  405. if (!BN_sqr(t, a, ctx)) {
  406. goto err;
  407. }
  408. } else {
  409. if (!BN_mul(t, a, b, ctx)) {
  410. goto err;
  411. }
  412. }
  413. if (!BN_nnmod(r, t, m, ctx)) {
  414. goto err;
  415. }
  416. ret = 1;
  417. err:
  418. BN_CTX_end(ctx);
  419. return ret;
  420. }
  421. int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {
  422. if (!BN_sqr(r, a, ctx)) {
  423. return 0;
  424. }
  425. /* r->neg == 0, thus we don't need BN_nnmod */
  426. return BN_mod(r, r, m, ctx);
  427. }
  428. int BN_mod_lshift(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m,
  429. BN_CTX *ctx) {
  430. BIGNUM *abs_m = NULL;
  431. int ret;
  432. if (!BN_nnmod(r, a, m, ctx)) {
  433. return 0;
  434. }
  435. if (m->neg) {
  436. abs_m = BN_dup(m);
  437. if (abs_m == NULL) {
  438. return 0;
  439. }
  440. abs_m->neg = 0;
  441. }
  442. ret = BN_mod_lshift_quick(r, r, n, (abs_m ? abs_m : m));
  443. BN_free(abs_m);
  444. return ret;
  445. }
  446. int BN_mod_lshift_quick(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m) {
  447. if (r != a) {
  448. if (BN_copy(r, a) == NULL) {
  449. return 0;
  450. }
  451. }
  452. while (n > 0) {
  453. int max_shift;
  454. /* 0 < r < m */
  455. max_shift = BN_num_bits(m) - BN_num_bits(r);
  456. /* max_shift >= 0 */
  457. if (max_shift < 0) {
  458. OPENSSL_PUT_ERROR(BN, BN_mod_lshift_quick, BN_R_INPUT_NOT_REDUCED);
  459. return 0;
  460. }
  461. if (max_shift > n) {
  462. max_shift = n;
  463. }
  464. if (max_shift) {
  465. if (!BN_lshift(r, r, max_shift)) {
  466. return 0;
  467. }
  468. n -= max_shift;
  469. } else {
  470. if (!BN_lshift1(r, r)) {
  471. return 0;
  472. }
  473. --n;
  474. }
  475. /* BN_num_bits(r) <= BN_num_bits(m) */
  476. if (BN_cmp(r, m) >= 0) {
  477. if (!BN_sub(r, r, m)) {
  478. return 0;
  479. }
  480. }
  481. }
  482. return 1;
  483. }
  484. int BN_mod_lshift1(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {
  485. if (!BN_lshift1(r, a)) {
  486. return 0;
  487. }
  488. return BN_nnmod(r, r, m, ctx);
  489. }
  490. int BN_mod_lshift1_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *m) {
  491. if (!BN_lshift1(r, a)) {
  492. return 0;
  493. }
  494. if (BN_cmp(r, m) >= 0) {
  495. return BN_sub(r, r, m);
  496. }
  497. return 1;
  498. }
  499. BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w) {
  500. BN_ULONG ret = 0;
  501. int i, j;
  502. w &= BN_MASK2;
  503. if (!w) {
  504. /* actually this an error (division by zero) */
  505. return (BN_ULONG) - 1;
  506. }
  507. if (a->top == 0) {
  508. return 0;
  509. }
  510. /* normalize input (so bn_div_words doesn't complain) */
  511. j = BN_BITS2 - BN_num_bits_word(w);
  512. w <<= j;
  513. if (!BN_lshift(a, a, j)) {
  514. return (BN_ULONG) - 1;
  515. }
  516. for (i = a->top - 1; i >= 0; i--) {
  517. BN_ULONG l, d;
  518. l = a->d[i];
  519. d = bn_div_words(ret, l, w);
  520. ret = (l - ((d * w) & BN_MASK2)) & BN_MASK2;
  521. a->d[i] = d;
  522. }
  523. if ((a->top > 0) && (a->d[a->top - 1] == 0)) {
  524. a->top--;
  525. }
  526. ret >>= j;
  527. return ret;
  528. }
  529. BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w) {
  530. #ifndef BN_LLONG
  531. BN_ULONG ret = 0;
  532. #else
  533. BN_ULLONG ret = 0;
  534. #endif
  535. int i;
  536. if (w == 0) {
  537. return (BN_ULONG) -1;
  538. }
  539. w &= BN_MASK2;
  540. for (i = a->top - 1; i >= 0; i--) {
  541. #ifndef BN_LLONG
  542. ret = ((ret << BN_BITS4) | ((a->d[i] >> BN_BITS4) & BN_MASK2l)) % w;
  543. ret = ((ret << BN_BITS4) | (a->d[i] & BN_MASK2l)) % w;
  544. #else
  545. ret = (BN_ULLONG)(((ret << (BN_ULLONG)BN_BITS2) | a->d[i]) % (BN_ULLONG)w);
  546. #endif
  547. }
  548. return (BN_ULONG)ret;
  549. }