bn_div.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. /*
  2. * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <openssl/bn.h>
  10. #include "internal/cryptlib.h"
  11. #include "bn_lcl.h"
  12. /* The old slow way */
  13. #if 0
  14. int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d,
  15. BN_CTX *ctx)
  16. {
  17. int i, nm, nd;
  18. int ret = 0;
  19. BIGNUM *D;
  20. bn_check_top(m);
  21. bn_check_top(d);
  22. if (BN_is_zero(d)) {
  23. BNerr(BN_F_BN_DIV, BN_R_DIV_BY_ZERO);
  24. return (0);
  25. }
  26. if (BN_ucmp(m, d) < 0) {
  27. if (rem != NULL) {
  28. if (BN_copy(rem, m) == NULL)
  29. return (0);
  30. }
  31. if (dv != NULL)
  32. BN_zero(dv);
  33. return (1);
  34. }
  35. BN_CTX_start(ctx);
  36. D = BN_CTX_get(ctx);
  37. if (dv == NULL)
  38. dv = BN_CTX_get(ctx);
  39. if (rem == NULL)
  40. rem = BN_CTX_get(ctx);
  41. if (D == NULL || dv == NULL || rem == NULL)
  42. goto end;
  43. nd = BN_num_bits(d);
  44. nm = BN_num_bits(m);
  45. if (BN_copy(D, d) == NULL)
  46. goto end;
  47. if (BN_copy(rem, m) == NULL)
  48. goto end;
  49. /*
  50. * The next 2 are needed so we can do a dv->d[0]|=1 later since
  51. * BN_lshift1 will only work once there is a value :-)
  52. */
  53. BN_zero(dv);
  54. if (bn_wexpand(dv, 1) == NULL)
  55. goto end;
  56. dv->top = 1;
  57. if (!BN_lshift(D, D, nm - nd))
  58. goto end;
  59. for (i = nm - nd; i >= 0; i--) {
  60. if (!BN_lshift1(dv, dv))
  61. goto end;
  62. if (BN_ucmp(rem, D) >= 0) {
  63. dv->d[0] |= 1;
  64. if (!BN_usub(rem, rem, D))
  65. goto end;
  66. }
  67. /* CAN IMPROVE (and have now :=) */
  68. if (!BN_rshift1(D, D))
  69. goto end;
  70. }
  71. rem->neg = BN_is_zero(rem) ? 0 : m->neg;
  72. dv->neg = m->neg ^ d->neg;
  73. ret = 1;
  74. end:
  75. BN_CTX_end(ctx);
  76. return (ret);
  77. }
  78. #else
  79. # if !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) \
  80. && !defined(PEDANTIC) && !defined(BN_DIV3W)
  81. # if defined(__GNUC__) && __GNUC__>=2
  82. # if defined(__i386) || defined (__i386__)
  83. /*-
  84. * There were two reasons for implementing this template:
  85. * - GNU C generates a call to a function (__udivdi3 to be exact)
  86. * in reply to ((((BN_ULLONG)n0)<<BN_BITS2)|n1)/d0 (I fail to
  87. * understand why...);
  88. * - divl doesn't only calculate quotient, but also leaves
  89. * remainder in %edx which we can definitely use here:-)
  90. *
  91. * <appro@fy.chalmers.se>
  92. */
  93. # undef bn_div_words
  94. # define bn_div_words(n0,n1,d0) \
  95. ({ asm volatile ( \
  96. "divl %4" \
  97. : "=a"(q), "=d"(rem) \
  98. : "a"(n1), "d"(n0), "r"(d0) \
  99. : "cc"); \
  100. q; \
  101. })
  102. # define REMAINDER_IS_ALREADY_CALCULATED
  103. # elif defined(__x86_64) && defined(SIXTY_FOUR_BIT_LONG)
  104. /*
  105. * Same story here, but it's 128-bit by 64-bit division. Wow!
  106. * <appro@fy.chalmers.se>
  107. */
  108. # undef bn_div_words
  109. # define bn_div_words(n0,n1,d0) \
  110. ({ asm volatile ( \
  111. "divq %4" \
  112. : "=a"(q), "=d"(rem) \
  113. : "a"(n1), "d"(n0), "r"(d0) \
  114. : "cc"); \
  115. q; \
  116. })
  117. # define REMAINDER_IS_ALREADY_CALCULATED
  118. # endif /* __<cpu> */
  119. # endif /* __GNUC__ */
  120. # endif /* OPENSSL_NO_ASM */
  121. /*-
  122. * BN_div computes dv := num / divisor, rounding towards
  123. * zero, and sets up rm such that dv*divisor + rm = num holds.
  124. * Thus:
  125. * dv->neg == num->neg ^ divisor->neg (unless the result is zero)
  126. * rm->neg == num->neg (unless the remainder is zero)
  127. * If 'dv' or 'rm' is NULL, the respective value is not returned.
  128. */
  129. int BN_div(BIGNUM *dv, BIGNUM *rm, const BIGNUM *num, const BIGNUM *divisor,
  130. BN_CTX *ctx)
  131. {
  132. int norm_shift, i, loop;
  133. BIGNUM *tmp, wnum, *snum, *sdiv, *res;
  134. BN_ULONG *resp, *wnump;
  135. BN_ULONG d0, d1;
  136. int num_n, div_n;
  137. int no_branch = 0;
  138. /*
  139. * Invalid zero-padding would have particularly bad consequences so don't
  140. * just rely on bn_check_top() here (bn_check_top() works only for
  141. * BN_DEBUG builds)
  142. */
  143. if ((num->top > 0 && num->d[num->top - 1] == 0) ||
  144. (divisor->top > 0 && divisor->d[divisor->top - 1] == 0)) {
  145. BNerr(BN_F_BN_DIV, BN_R_NOT_INITIALIZED);
  146. return 0;
  147. }
  148. bn_check_top(num);
  149. bn_check_top(divisor);
  150. if ((BN_get_flags(num, BN_FLG_CONSTTIME) != 0)
  151. || (BN_get_flags(divisor, BN_FLG_CONSTTIME) != 0)) {
  152. no_branch = 1;
  153. }
  154. bn_check_top(dv);
  155. bn_check_top(rm);
  156. /*- bn_check_top(num); *//*
  157. * 'num' has been checked already
  158. */
  159. /*- bn_check_top(divisor); *//*
  160. * 'divisor' has been checked already
  161. */
  162. if (BN_is_zero(divisor)) {
  163. BNerr(BN_F_BN_DIV, BN_R_DIV_BY_ZERO);
  164. return (0);
  165. }
  166. if (!no_branch && BN_ucmp(num, divisor) < 0) {
  167. if (rm != NULL) {
  168. if (BN_copy(rm, num) == NULL)
  169. return (0);
  170. }
  171. if (dv != NULL)
  172. BN_zero(dv);
  173. return (1);
  174. }
  175. BN_CTX_start(ctx);
  176. tmp = BN_CTX_get(ctx);
  177. snum = BN_CTX_get(ctx);
  178. sdiv = BN_CTX_get(ctx);
  179. if (dv == NULL)
  180. res = BN_CTX_get(ctx);
  181. else
  182. res = dv;
  183. if (sdiv == NULL || res == NULL || tmp == NULL || snum == NULL)
  184. goto err;
  185. /* First we normalise the numbers */
  186. norm_shift = BN_BITS2 - ((BN_num_bits(divisor)) % BN_BITS2);
  187. if (!(BN_lshift(sdiv, divisor, norm_shift)))
  188. goto err;
  189. sdiv->neg = 0;
  190. norm_shift += BN_BITS2;
  191. if (!(BN_lshift(snum, num, norm_shift)))
  192. goto err;
  193. snum->neg = 0;
  194. if (no_branch) {
  195. /*
  196. * Since we don't know whether snum is larger than sdiv, we pad snum
  197. * with enough zeroes without changing its value.
  198. */
  199. if (snum->top <= sdiv->top + 1) {
  200. if (bn_wexpand(snum, sdiv->top + 2) == NULL)
  201. goto err;
  202. for (i = snum->top; i < sdiv->top + 2; i++)
  203. snum->d[i] = 0;
  204. snum->top = sdiv->top + 2;
  205. } else {
  206. if (bn_wexpand(snum, snum->top + 1) == NULL)
  207. goto err;
  208. snum->d[snum->top] = 0;
  209. snum->top++;
  210. }
  211. }
  212. div_n = sdiv->top;
  213. num_n = snum->top;
  214. loop = num_n - div_n;
  215. /*
  216. * Lets setup a 'window' into snum This is the part that corresponds to
  217. * the current 'area' being divided
  218. */
  219. wnum.neg = 0;
  220. wnum.d = &(snum->d[loop]);
  221. wnum.top = div_n;
  222. /*
  223. * only needed when BN_ucmp messes up the values between top and max
  224. */
  225. wnum.dmax = snum->dmax - loop; /* so we don't step out of bounds */
  226. /* Get the top 2 words of sdiv */
  227. /* div_n=sdiv->top; */
  228. d0 = sdiv->d[div_n - 1];
  229. d1 = (div_n == 1) ? 0 : sdiv->d[div_n - 2];
  230. /* pointer to the 'top' of snum */
  231. wnump = &(snum->d[num_n - 1]);
  232. /* Setup to 'res' */
  233. if (!bn_wexpand(res, (loop + 1)))
  234. goto err;
  235. res->neg = (num->neg ^ divisor->neg);
  236. res->top = loop - no_branch;
  237. resp = &(res->d[loop - 1]);
  238. /* space for temp */
  239. if (!bn_wexpand(tmp, (div_n + 1)))
  240. goto err;
  241. if (!no_branch) {
  242. if (BN_ucmp(&wnum, sdiv) >= 0) {
  243. /*
  244. * If BN_DEBUG_RAND is defined BN_ucmp changes (via bn_pollute)
  245. * the const bignum arguments => clean the values between top and
  246. * max again
  247. */
  248. bn_clear_top2max(&wnum);
  249. bn_sub_words(wnum.d, wnum.d, sdiv->d, div_n);
  250. *resp = 1;
  251. } else
  252. res->top--;
  253. }
  254. /* Increase the resp pointer so that we never create an invalid pointer. */
  255. resp++;
  256. /*
  257. * if res->top == 0 then clear the neg value otherwise decrease the resp
  258. * pointer
  259. */
  260. if (res->top == 0)
  261. res->neg = 0;
  262. else
  263. resp--;
  264. for (i = 0; i < loop - 1; i++, wnump--) {
  265. BN_ULONG q, l0;
  266. /*
  267. * the first part of the loop uses the top two words of snum and sdiv
  268. * to calculate a BN_ULONG q such that | wnum - sdiv * q | < sdiv
  269. */
  270. # if defined(BN_DIV3W) && !defined(OPENSSL_NO_ASM)
  271. BN_ULONG bn_div_3_words(BN_ULONG *, BN_ULONG, BN_ULONG);
  272. q = bn_div_3_words(wnump, d1, d0);
  273. # else
  274. BN_ULONG n0, n1, rem = 0;
  275. n0 = wnump[0];
  276. n1 = wnump[-1];
  277. if (n0 == d0)
  278. q = BN_MASK2;
  279. else { /* n0 < d0 */
  280. # ifdef BN_LLONG
  281. BN_ULLONG t2;
  282. # if defined(BN_LLONG) && defined(BN_DIV2W) && !defined(bn_div_words)
  283. q = (BN_ULONG)(((((BN_ULLONG) n0) << BN_BITS2) | n1) / d0);
  284. # else
  285. q = bn_div_words(n0, n1, d0);
  286. # endif
  287. # ifndef REMAINDER_IS_ALREADY_CALCULATED
  288. /*
  289. * rem doesn't have to be BN_ULLONG. The least we
  290. * know it's less that d0, isn't it?
  291. */
  292. rem = (n1 - q * d0) & BN_MASK2;
  293. # endif
  294. t2 = (BN_ULLONG) d1 *q;
  295. for (;;) {
  296. if (t2 <= ((((BN_ULLONG) rem) << BN_BITS2) | wnump[-2]))
  297. break;
  298. q--;
  299. rem += d0;
  300. if (rem < d0)
  301. break; /* don't let rem overflow */
  302. t2 -= d1;
  303. }
  304. # else /* !BN_LLONG */
  305. BN_ULONG t2l, t2h;
  306. q = bn_div_words(n0, n1, d0);
  307. # ifndef REMAINDER_IS_ALREADY_CALCULATED
  308. rem = (n1 - q * d0) & BN_MASK2;
  309. # endif
  310. # if defined(BN_UMULT_LOHI)
  311. BN_UMULT_LOHI(t2l, t2h, d1, q);
  312. # elif defined(BN_UMULT_HIGH)
  313. t2l = d1 * q;
  314. t2h = BN_UMULT_HIGH(d1, q);
  315. # else
  316. {
  317. BN_ULONG ql, qh;
  318. t2l = LBITS(d1);
  319. t2h = HBITS(d1);
  320. ql = LBITS(q);
  321. qh = HBITS(q);
  322. mul64(t2l, t2h, ql, qh); /* t2=(BN_ULLONG)d1*q; */
  323. }
  324. # endif
  325. for (;;) {
  326. if ((t2h < rem) || ((t2h == rem) && (t2l <= wnump[-2])))
  327. break;
  328. q--;
  329. rem += d0;
  330. if (rem < d0)
  331. break; /* don't let rem overflow */
  332. if (t2l < d1)
  333. t2h--;
  334. t2l -= d1;
  335. }
  336. # endif /* !BN_LLONG */
  337. }
  338. # endif /* !BN_DIV3W */
  339. l0 = bn_mul_words(tmp->d, sdiv->d, div_n, q);
  340. tmp->d[div_n] = l0;
  341. wnum.d--;
  342. /*
  343. * ingore top values of the bignums just sub the two BN_ULONG arrays
  344. * with bn_sub_words
  345. */
  346. if (bn_sub_words(wnum.d, wnum.d, tmp->d, div_n + 1)) {
  347. /*
  348. * Note: As we have considered only the leading two BN_ULONGs in
  349. * the calculation of q, sdiv * q might be greater than wnum (but
  350. * then (q-1) * sdiv is less or equal than wnum)
  351. */
  352. q--;
  353. if (bn_add_words(wnum.d, wnum.d, sdiv->d, div_n))
  354. /*
  355. * we can't have an overflow here (assuming that q != 0, but
  356. * if q == 0 then tmp is zero anyway)
  357. */
  358. (*wnump)++;
  359. }
  360. /* store part of the result */
  361. resp--;
  362. *resp = q;
  363. }
  364. bn_correct_top(snum);
  365. if (rm != NULL) {
  366. /*
  367. * Keep a copy of the neg flag in num because if rm==num BN_rshift()
  368. * will overwrite it.
  369. */
  370. int neg = num->neg;
  371. BN_rshift(rm, snum, norm_shift);
  372. if (!BN_is_zero(rm))
  373. rm->neg = neg;
  374. bn_check_top(rm);
  375. }
  376. if (no_branch)
  377. bn_correct_top(res);
  378. BN_CTX_end(ctx);
  379. return (1);
  380. err:
  381. bn_check_top(rm);
  382. BN_CTX_end(ctx);
  383. return (0);
  384. }
  385. #endif