選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

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