div.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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), "rm"(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), "rm"(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. *
  171. * This was specifically designed to contain fewer branches that may leak
  172. * sensitive information; see "New Branch Prediction Vulnerabilities in OpenSSL
  173. * and Necessary Software Countermeasures" by Onur Acıçmez, Shay Gueron, and
  174. * Jean-Pierre Seifert. */
  175. int BN_div(BIGNUM *dv, BIGNUM *rm, const BIGNUM *num, const BIGNUM *divisor,
  176. BN_CTX *ctx) {
  177. int norm_shift, i, loop;
  178. BIGNUM *tmp, wnum, *snum, *sdiv, *res;
  179. BN_ULONG *resp, *wnump;
  180. BN_ULONG d0, d1;
  181. int num_n, div_n;
  182. /* Invalid zero-padding would have particularly bad consequences
  183. * so don't just rely on bn_check_top() here */
  184. if ((num->top > 0 && num->d[num->top - 1] == 0) ||
  185. (divisor->top > 0 && divisor->d[divisor->top - 1] == 0)) {
  186. OPENSSL_PUT_ERROR(BN, BN_R_NOT_INITIALIZED);
  187. return 0;
  188. }
  189. if (BN_is_zero(divisor)) {
  190. OPENSSL_PUT_ERROR(BN, BN_R_DIV_BY_ZERO);
  191. return 0;
  192. }
  193. BN_CTX_start(ctx);
  194. tmp = BN_CTX_get(ctx);
  195. snum = BN_CTX_get(ctx);
  196. sdiv = BN_CTX_get(ctx);
  197. if (dv == NULL) {
  198. res = BN_CTX_get(ctx);
  199. } else {
  200. res = dv;
  201. }
  202. if (sdiv == NULL || res == NULL || tmp == NULL || snum == NULL) {
  203. goto err;
  204. }
  205. /* First we normalise the numbers */
  206. norm_shift = BN_BITS2 - ((BN_num_bits(divisor)) % BN_BITS2);
  207. if (!(BN_lshift(sdiv, divisor, norm_shift))) {
  208. goto err;
  209. }
  210. sdiv->neg = 0;
  211. norm_shift += BN_BITS2;
  212. if (!(BN_lshift(snum, num, norm_shift))) {
  213. goto err;
  214. }
  215. snum->neg = 0;
  216. /* Since we don't want to have special-case logic for the case where snum is
  217. * larger than sdiv, we pad snum with enough zeroes without changing its
  218. * value. */
  219. if (snum->top <= sdiv->top + 1) {
  220. if (bn_wexpand(snum, sdiv->top + 2) == NULL) {
  221. goto err;
  222. }
  223. for (i = snum->top; i < sdiv->top + 2; i++) {
  224. snum->d[i] = 0;
  225. }
  226. snum->top = sdiv->top + 2;
  227. } else {
  228. if (bn_wexpand(snum, snum->top + 1) == NULL) {
  229. goto err;
  230. }
  231. snum->d[snum->top] = 0;
  232. snum->top++;
  233. }
  234. div_n = sdiv->top;
  235. num_n = snum->top;
  236. loop = num_n - div_n;
  237. /* Lets setup a 'window' into snum
  238. * This is the part that corresponds to the current
  239. * 'area' being divided */
  240. wnum.neg = 0;
  241. wnum.d = &(snum->d[loop]);
  242. wnum.top = div_n;
  243. /* only needed when BN_ucmp messes up the values between top and max */
  244. wnum.dmax = snum->dmax - loop; /* so we don't step out of bounds */
  245. /* Get the top 2 words of sdiv */
  246. /* div_n=sdiv->top; */
  247. d0 = sdiv->d[div_n - 1];
  248. d1 = (div_n == 1) ? 0 : sdiv->d[div_n - 2];
  249. /* pointer to the 'top' of snum */
  250. wnump = &(snum->d[num_n - 1]);
  251. /* Setup to 'res' */
  252. res->neg = (num->neg ^ divisor->neg);
  253. if (!bn_wexpand(res, (loop + 1))) {
  254. goto err;
  255. }
  256. res->top = loop - 1;
  257. resp = &(res->d[loop - 1]);
  258. /* space for temp */
  259. if (!bn_wexpand(tmp, (div_n + 1))) {
  260. goto err;
  261. }
  262. /* if res->top == 0 then clear the neg value otherwise decrease
  263. * the resp pointer */
  264. if (res->top == 0) {
  265. res->neg = 0;
  266. } else {
  267. resp--;
  268. }
  269. for (i = 0; i < loop - 1; i++, wnump--, resp--) {
  270. BN_ULONG q, l0;
  271. /* the first part of the loop uses the top two words of snum and sdiv to
  272. * calculate a BN_ULONG q such that | wnum - sdiv * q | < sdiv */
  273. BN_ULONG n0, n1, rem = 0;
  274. n0 = wnump[0];
  275. n1 = wnump[-1];
  276. if (n0 == d0) {
  277. q = BN_MASK2;
  278. } else {
  279. /* n0 < d0 */
  280. bn_div_rem_words(&q, &rem, n0, n1, d0);
  281. #ifdef BN_ULLONG
  282. BN_ULLONG t2 = (BN_ULLONG)d1 * q;
  283. for (;;) {
  284. if (t2 <= ((((BN_ULLONG)rem) << BN_BITS2) | wnump[-2])) {
  285. break;
  286. }
  287. q--;
  288. rem += d0;
  289. if (rem < d0) {
  290. break; /* don't let rem overflow */
  291. }
  292. t2 -= d1;
  293. }
  294. #else /* !BN_ULLONG */
  295. BN_ULONG t2l, t2h;
  296. BN_UMULT_LOHI(t2l, t2h, d1, q);
  297. for (;;) {
  298. if ((t2h < rem) || ((t2h == rem) && (t2l <= wnump[-2]))) {
  299. break;
  300. }
  301. q--;
  302. rem += d0;
  303. if (rem < d0) {
  304. break; /* don't let rem overflow */
  305. }
  306. if (t2l < d1) {
  307. t2h--;
  308. }
  309. t2l -= d1;
  310. }
  311. #endif /* !BN_ULLONG */
  312. }
  313. l0 = bn_mul_words(tmp->d, sdiv->d, div_n, q);
  314. tmp->d[div_n] = l0;
  315. wnum.d--;
  316. /* ingore top values of the bignums just sub the two
  317. * BN_ULONG arrays with bn_sub_words */
  318. if (bn_sub_words(wnum.d, wnum.d, tmp->d, div_n + 1)) {
  319. /* Note: As we have considered only the leading
  320. * two BN_ULONGs in the calculation of q, sdiv * q
  321. * might be greater than wnum (but then (q-1) * sdiv
  322. * is less or equal than wnum)
  323. */
  324. q--;
  325. if (bn_add_words(wnum.d, wnum.d, sdiv->d, div_n)) {
  326. /* we can't have an overflow here (assuming
  327. * that q != 0, but if q == 0 then tmp is
  328. * zero anyway) */
  329. (*wnump)++;
  330. }
  331. }
  332. /* store part of the result */
  333. *resp = q;
  334. }
  335. bn_correct_top(snum);
  336. if (rm != NULL) {
  337. /* Keep a copy of the neg flag in num because if rm==num
  338. * BN_rshift() will overwrite it.
  339. */
  340. int neg = num->neg;
  341. if (!BN_rshift(rm, snum, norm_shift)) {
  342. goto err;
  343. }
  344. if (!BN_is_zero(rm)) {
  345. rm->neg = neg;
  346. }
  347. }
  348. bn_correct_top(res);
  349. BN_CTX_end(ctx);
  350. return 1;
  351. err:
  352. BN_CTX_end(ctx);
  353. return 0;
  354. }
  355. int BN_nnmod(BIGNUM *r, const BIGNUM *m, const BIGNUM *d, BN_CTX *ctx) {
  356. if (!(BN_mod(r, m, d, ctx))) {
  357. return 0;
  358. }
  359. if (!r->neg) {
  360. return 1;
  361. }
  362. /* now -|d| < r < 0, so we have to set r := r + |d|. */
  363. return (d->neg ? BN_sub : BN_add)(r, r, d);
  364. }
  365. int BN_mod_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
  366. BN_CTX *ctx) {
  367. if (!BN_add(r, a, b)) {
  368. return 0;
  369. }
  370. return BN_nnmod(r, r, m, ctx);
  371. }
  372. int BN_mod_add_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
  373. const BIGNUM *m) {
  374. if (!BN_uadd(r, a, b)) {
  375. return 0;
  376. }
  377. if (BN_ucmp(r, m) >= 0) {
  378. return BN_usub(r, r, m);
  379. }
  380. return 1;
  381. }
  382. int BN_mod_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
  383. BN_CTX *ctx) {
  384. if (!BN_sub(r, a, b)) {
  385. return 0;
  386. }
  387. return BN_nnmod(r, r, m, ctx);
  388. }
  389. /* BN_mod_sub variant that may be used if both a and b are non-negative
  390. * and less than m */
  391. int BN_mod_sub_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
  392. const BIGNUM *m) {
  393. if (!BN_sub(r, a, b)) {
  394. return 0;
  395. }
  396. if (r->neg) {
  397. return BN_add(r, r, m);
  398. }
  399. return 1;
  400. }
  401. int BN_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
  402. BN_CTX *ctx) {
  403. BIGNUM *t;
  404. int ret = 0;
  405. BN_CTX_start(ctx);
  406. t = BN_CTX_get(ctx);
  407. if (t == NULL) {
  408. goto err;
  409. }
  410. if (a == b) {
  411. if (!BN_sqr(t, a, ctx)) {
  412. goto err;
  413. }
  414. } else {
  415. if (!BN_mul(t, a, b, ctx)) {
  416. goto err;
  417. }
  418. }
  419. if (!BN_nnmod(r, t, m, ctx)) {
  420. goto err;
  421. }
  422. ret = 1;
  423. err:
  424. BN_CTX_end(ctx);
  425. return ret;
  426. }
  427. int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {
  428. if (!BN_sqr(r, a, ctx)) {
  429. return 0;
  430. }
  431. /* r->neg == 0, thus we don't need BN_nnmod */
  432. return BN_mod(r, r, m, ctx);
  433. }
  434. int BN_mod_lshift(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m,
  435. BN_CTX *ctx) {
  436. BIGNUM *abs_m = NULL;
  437. int ret;
  438. if (!BN_nnmod(r, a, m, ctx)) {
  439. return 0;
  440. }
  441. if (m->neg) {
  442. abs_m = BN_dup(m);
  443. if (abs_m == NULL) {
  444. return 0;
  445. }
  446. abs_m->neg = 0;
  447. }
  448. ret = BN_mod_lshift_quick(r, r, n, (abs_m ? abs_m : m));
  449. BN_free(abs_m);
  450. return ret;
  451. }
  452. int BN_mod_lshift_quick(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m) {
  453. if (r != a) {
  454. if (BN_copy(r, a) == NULL) {
  455. return 0;
  456. }
  457. }
  458. while (n > 0) {
  459. int max_shift;
  460. /* 0 < r < m */
  461. max_shift = BN_num_bits(m) - BN_num_bits(r);
  462. /* max_shift >= 0 */
  463. if (max_shift < 0) {
  464. OPENSSL_PUT_ERROR(BN, BN_R_INPUT_NOT_REDUCED);
  465. return 0;
  466. }
  467. if (max_shift > n) {
  468. max_shift = n;
  469. }
  470. if (max_shift) {
  471. if (!BN_lshift(r, r, max_shift)) {
  472. return 0;
  473. }
  474. n -= max_shift;
  475. } else {
  476. if (!BN_lshift1(r, r)) {
  477. return 0;
  478. }
  479. --n;
  480. }
  481. /* BN_num_bits(r) <= BN_num_bits(m) */
  482. if (BN_cmp(r, m) >= 0) {
  483. if (!BN_sub(r, r, m)) {
  484. return 0;
  485. }
  486. }
  487. }
  488. return 1;
  489. }
  490. int BN_mod_lshift1(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {
  491. if (!BN_lshift1(r, a)) {
  492. return 0;
  493. }
  494. return BN_nnmod(r, r, m, ctx);
  495. }
  496. int BN_mod_lshift1_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *m) {
  497. if (!BN_lshift1(r, a)) {
  498. return 0;
  499. }
  500. if (BN_cmp(r, m) >= 0) {
  501. return BN_sub(r, r, m);
  502. }
  503. return 1;
  504. }
  505. BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w) {
  506. BN_ULONG ret = 0;
  507. int i, j;
  508. w &= BN_MASK2;
  509. if (!w) {
  510. /* actually this an error (division by zero) */
  511. return (BN_ULONG) - 1;
  512. }
  513. if (a->top == 0) {
  514. return 0;
  515. }
  516. /* normalize input for |bn_div_rem_words|. */
  517. j = BN_BITS2 - BN_num_bits_word(w);
  518. w <<= j;
  519. if (!BN_lshift(a, a, j)) {
  520. return (BN_ULONG) - 1;
  521. }
  522. for (i = a->top - 1; i >= 0; i--) {
  523. BN_ULONG l = a->d[i];
  524. BN_ULONG d;
  525. BN_ULONG unused_rem;
  526. bn_div_rem_words(&d, &unused_rem, ret, l, w);
  527. ret = (l - ((d * w) & BN_MASK2)) & BN_MASK2;
  528. a->d[i] = d;
  529. }
  530. if ((a->top > 0) && (a->d[a->top - 1] == 0)) {
  531. a->top--;
  532. }
  533. if (a->top == 0) {
  534. a->neg = 0;
  535. }
  536. ret >>= j;
  537. return ret;
  538. }
  539. BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w) {
  540. #ifndef BN_ULLONG
  541. BN_ULONG ret = 0;
  542. #else
  543. BN_ULLONG ret = 0;
  544. #endif
  545. int i;
  546. if (w == 0) {
  547. return (BN_ULONG) -1;
  548. }
  549. #ifndef BN_ULLONG
  550. /* If |w| is too long and we don't have |BN_ULLONG| then we need to fall back
  551. * to using |BN_div_word|. */
  552. if (w > ((BN_ULONG)1 << BN_BITS4)) {
  553. BIGNUM *tmp = BN_dup(a);
  554. if (tmp == NULL) {
  555. return (BN_ULONG)-1;
  556. }
  557. ret = BN_div_word(tmp, w);
  558. BN_free(tmp);
  559. return ret;
  560. }
  561. #endif
  562. w &= BN_MASK2;
  563. for (i = a->top - 1; i >= 0; i--) {
  564. #ifndef BN_ULLONG
  565. ret = ((ret << BN_BITS4) | ((a->d[i] >> BN_BITS4) & BN_MASK2l)) % w;
  566. ret = ((ret << BN_BITS4) | (a->d[i] & BN_MASK2l)) % w;
  567. #else
  568. ret = (BN_ULLONG)(((ret << (BN_ULLONG)BN_BITS2) | a->d[i]) % (BN_ULLONG)w);
  569. #endif
  570. }
  571. return (BN_ULONG)ret;
  572. }
  573. int BN_mod_pow2(BIGNUM *r, const BIGNUM *a, size_t e) {
  574. if (e == 0 || a->top == 0) {
  575. BN_zero(r);
  576. return 1;
  577. }
  578. size_t num_words = 1 + ((e - 1) / BN_BITS2);
  579. /* If |a| definitely has less than |e| bits, just BN_copy. */
  580. if ((size_t) a->top < num_words) {
  581. return BN_copy(r, a) != NULL;
  582. }
  583. /* Otherwise, first make sure we have enough space in |r|.
  584. * Note that this will fail if num_words > INT_MAX. */
  585. if (bn_wexpand(r, num_words) == NULL) {
  586. return 0;
  587. }
  588. /* Copy the content of |a| into |r|. */
  589. OPENSSL_memcpy(r->d, a->d, num_words * sizeof(BN_ULONG));
  590. /* If |e| isn't word-aligned, we have to mask off some of our bits. */
  591. size_t top_word_exponent = e % (sizeof(BN_ULONG) * 8);
  592. if (top_word_exponent != 0) {
  593. r->d[num_words - 1] &= (((BN_ULONG) 1) << top_word_exponent) - 1;
  594. }
  595. /* Fill in the remaining fields of |r|. */
  596. r->neg = a->neg;
  597. r->top = (int) num_words;
  598. bn_correct_top(r);
  599. return 1;
  600. }
  601. int BN_nnmod_pow2(BIGNUM *r, const BIGNUM *a, size_t e) {
  602. if (!BN_mod_pow2(r, a, e)) {
  603. return 0;
  604. }
  605. /* If the returned value was non-negative, we're done. */
  606. if (BN_is_zero(r) || !r->neg) {
  607. return 1;
  608. }
  609. size_t num_words = 1 + (e - 1) / BN_BITS2;
  610. /* Expand |r| to the size of our modulus. */
  611. if (bn_wexpand(r, num_words) == NULL) {
  612. return 0;
  613. }
  614. /* Clear the upper words of |r|. */
  615. OPENSSL_memset(&r->d[r->top], 0, (num_words - r->top) * BN_BYTES);
  616. /* Set parameters of |r|. */
  617. r->neg = 0;
  618. r->top = (int) num_words;
  619. /* Now, invert every word. The idea here is that we want to compute 2^e-|x|,
  620. * which is actually equivalent to the twos-complement representation of |x|
  621. * in |e| bits, which is -x = ~x + 1. */
  622. for (int i = 0; i < r->top; i++) {
  623. r->d[i] = ~r->d[i];
  624. }
  625. /* If our exponent doesn't span the top word, we have to mask the rest. */
  626. size_t top_word_exponent = e % BN_BITS2;
  627. if (top_word_exponent != 0) {
  628. r->d[r->top - 1] &= (((BN_ULONG) 1) << top_word_exponent) - 1;
  629. }
  630. /* Keep the correct_top invariant for BN_add. */
  631. bn_correct_top(r);
  632. /* Finally, add one, for the reason described above. */
  633. return BN_add(r, r, BN_value_one());
  634. }