div.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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_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_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_ULLONG
  241. BN_ULLONG t2;
  242. #if defined(BN_ULLONG) && !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_ULLONG */
  265. BN_ULONG t2l, t2h;
  266. q = bn_div_words(n0, n1, d0);
  267. rem = (n1 - q * d0) & BN_MASK2;
  268. BN_UMULT_LOHI(t2l, t2h, d1, q);
  269. for (;;) {
  270. if ((t2h < rem) || ((t2h == rem) && (t2l <= wnump[-2]))) {
  271. break;
  272. }
  273. q--;
  274. rem += d0;
  275. if (rem < d0) {
  276. break; /* don't let rem overflow */
  277. }
  278. if (t2l < d1) {
  279. t2h--;
  280. }
  281. t2l -= d1;
  282. }
  283. #endif /* !BN_ULLONG */
  284. }
  285. l0 = bn_mul_words(tmp->d, sdiv->d, div_n, q);
  286. tmp->d[div_n] = l0;
  287. wnum.d--;
  288. /* ingore top values of the bignums just sub the two
  289. * BN_ULONG arrays with bn_sub_words */
  290. if (bn_sub_words(wnum.d, wnum.d, tmp->d, div_n + 1)) {
  291. /* Note: As we have considered only the leading
  292. * two BN_ULONGs in the calculation of q, sdiv * q
  293. * might be greater than wnum (but then (q-1) * sdiv
  294. * is less or equal than wnum)
  295. */
  296. q--;
  297. if (bn_add_words(wnum.d, wnum.d, sdiv->d, div_n)) {
  298. /* we can't have an overflow here (assuming
  299. * that q != 0, but if q == 0 then tmp is
  300. * zero anyway) */
  301. (*wnump)++;
  302. }
  303. }
  304. /* store part of the result */
  305. *resp = q;
  306. }
  307. bn_correct_top(snum);
  308. if (rm != NULL) {
  309. /* Keep a copy of the neg flag in num because if rm==num
  310. * BN_rshift() will overwrite it.
  311. */
  312. int neg = num->neg;
  313. if (!BN_rshift(rm, snum, norm_shift)) {
  314. goto err;
  315. }
  316. if (!BN_is_zero(rm)) {
  317. rm->neg = neg;
  318. }
  319. }
  320. if (no_branch) {
  321. bn_correct_top(res);
  322. }
  323. BN_CTX_end(ctx);
  324. return 1;
  325. err:
  326. BN_CTX_end(ctx);
  327. return 0;
  328. }
  329. int BN_nnmod(BIGNUM *r, const BIGNUM *m, const BIGNUM *d, BN_CTX *ctx) {
  330. if (!(BN_mod(r, m, d, ctx))) {
  331. return 0;
  332. }
  333. if (!r->neg) {
  334. return 1;
  335. }
  336. /* now -|d| < r < 0, so we have to set r := r + |d|. */
  337. return (d->neg ? BN_sub : BN_add)(r, r, d);
  338. }
  339. int BN_mod_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
  340. BN_CTX *ctx) {
  341. if (!BN_add(r, a, b)) {
  342. return 0;
  343. }
  344. return BN_nnmod(r, r, m, ctx);
  345. }
  346. int BN_mod_add_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
  347. const BIGNUM *m) {
  348. if (!BN_uadd(r, a, b)) {
  349. return 0;
  350. }
  351. if (BN_ucmp(r, m) >= 0) {
  352. return BN_usub(r, r, m);
  353. }
  354. return 1;
  355. }
  356. int BN_mod_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
  357. BN_CTX *ctx) {
  358. if (!BN_sub(r, a, b)) {
  359. return 0;
  360. }
  361. return BN_nnmod(r, r, m, ctx);
  362. }
  363. /* BN_mod_sub variant that may be used if both a and b are non-negative
  364. * and less than m */
  365. int BN_mod_sub_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
  366. const BIGNUM *m) {
  367. if (!BN_sub(r, a, b)) {
  368. return 0;
  369. }
  370. if (r->neg) {
  371. return BN_add(r, r, m);
  372. }
  373. return 1;
  374. }
  375. int BN_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
  376. BN_CTX *ctx) {
  377. BIGNUM *t;
  378. int ret = 0;
  379. BN_CTX_start(ctx);
  380. t = BN_CTX_get(ctx);
  381. if (t == NULL) {
  382. goto err;
  383. }
  384. if (a == b) {
  385. if (!BN_sqr(t, a, ctx)) {
  386. goto err;
  387. }
  388. } else {
  389. if (!BN_mul(t, a, b, ctx)) {
  390. goto err;
  391. }
  392. }
  393. if (!BN_nnmod(r, t, m, ctx)) {
  394. goto err;
  395. }
  396. ret = 1;
  397. err:
  398. BN_CTX_end(ctx);
  399. return ret;
  400. }
  401. int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {
  402. if (!BN_sqr(r, a, ctx)) {
  403. return 0;
  404. }
  405. /* r->neg == 0, thus we don't need BN_nnmod */
  406. return BN_mod(r, r, m, ctx);
  407. }
  408. int BN_mod_lshift(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m,
  409. BN_CTX *ctx) {
  410. BIGNUM *abs_m = NULL;
  411. int ret;
  412. if (!BN_nnmod(r, a, m, ctx)) {
  413. return 0;
  414. }
  415. if (m->neg) {
  416. abs_m = BN_dup(m);
  417. if (abs_m == NULL) {
  418. return 0;
  419. }
  420. abs_m->neg = 0;
  421. }
  422. ret = BN_mod_lshift_quick(r, r, n, (abs_m ? abs_m : m));
  423. BN_free(abs_m);
  424. return ret;
  425. }
  426. int BN_mod_lshift_quick(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m) {
  427. if (r != a) {
  428. if (BN_copy(r, a) == NULL) {
  429. return 0;
  430. }
  431. }
  432. while (n > 0) {
  433. int max_shift;
  434. /* 0 < r < m */
  435. max_shift = BN_num_bits(m) - BN_num_bits(r);
  436. /* max_shift >= 0 */
  437. if (max_shift < 0) {
  438. OPENSSL_PUT_ERROR(BN, BN_R_INPUT_NOT_REDUCED);
  439. return 0;
  440. }
  441. if (max_shift > n) {
  442. max_shift = n;
  443. }
  444. if (max_shift) {
  445. if (!BN_lshift(r, r, max_shift)) {
  446. return 0;
  447. }
  448. n -= max_shift;
  449. } else {
  450. if (!BN_lshift1(r, r)) {
  451. return 0;
  452. }
  453. --n;
  454. }
  455. /* BN_num_bits(r) <= BN_num_bits(m) */
  456. if (BN_cmp(r, m) >= 0) {
  457. if (!BN_sub(r, r, m)) {
  458. return 0;
  459. }
  460. }
  461. }
  462. return 1;
  463. }
  464. int BN_mod_lshift1(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {
  465. if (!BN_lshift1(r, a)) {
  466. return 0;
  467. }
  468. return BN_nnmod(r, r, m, ctx);
  469. }
  470. int BN_mod_lshift1_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *m) {
  471. if (!BN_lshift1(r, a)) {
  472. return 0;
  473. }
  474. if (BN_cmp(r, m) >= 0) {
  475. return BN_sub(r, r, m);
  476. }
  477. return 1;
  478. }
  479. BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w) {
  480. BN_ULONG ret = 0;
  481. int i, j;
  482. w &= BN_MASK2;
  483. if (!w) {
  484. /* actually this an error (division by zero) */
  485. return (BN_ULONG) - 1;
  486. }
  487. if (a->top == 0) {
  488. return 0;
  489. }
  490. /* normalize input (so bn_div_words doesn't complain) */
  491. j = BN_BITS2 - BN_num_bits_word(w);
  492. w <<= j;
  493. if (!BN_lshift(a, a, j)) {
  494. return (BN_ULONG) - 1;
  495. }
  496. for (i = a->top - 1; i >= 0; i--) {
  497. BN_ULONG l, d;
  498. l = a->d[i];
  499. d = bn_div_words(ret, l, w);
  500. ret = (l - ((d * w) & BN_MASK2)) & BN_MASK2;
  501. a->d[i] = d;
  502. }
  503. if ((a->top > 0) && (a->d[a->top - 1] == 0)) {
  504. a->top--;
  505. }
  506. ret >>= j;
  507. return ret;
  508. }
  509. BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w) {
  510. #ifndef BN_ULLONG
  511. BN_ULONG ret = 0;
  512. #else
  513. BN_ULLONG ret = 0;
  514. #endif
  515. int i;
  516. if (w == 0) {
  517. return (BN_ULONG) -1;
  518. }
  519. w &= BN_MASK2;
  520. for (i = a->top - 1; i >= 0; i--) {
  521. #ifndef BN_ULLONG
  522. ret = ((ret << BN_BITS4) | ((a->d[i] >> BN_BITS4) & BN_MASK2l)) % w;
  523. ret = ((ret << BN_BITS4) | (a->d[i] & BN_MASK2l)) % w;
  524. #else
  525. ret = (BN_ULLONG)(((ret << (BN_ULLONG)BN_BITS2) | a->d[i]) % (BN_ULLONG)w);
  526. #endif
  527. }
  528. return (BN_ULONG)ret;
  529. }