bn_mont.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. /* crypto/bn/bn_mont.c */
  2. /* Copyright (C) 1995-1998 Eric Young ([email protected])
  3. * All rights reserved.
  4. *
  5. * This package is an SSL implementation written
  6. * by Eric Young ([email protected]).
  7. * The implementation was written so as to conform with Netscapes SSL.
  8. *
  9. * This library is free for commercial and non-commercial use as long as
  10. * the following conditions are aheared to. The following conditions
  11. * apply to all code found in this distribution, be it the RC4, RSA,
  12. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  13. * included with this distribution is covered by the same copyright terms
  14. * except that the holder is Tim Hudson ([email protected]).
  15. *
  16. * Copyright remains Eric Young's, and as such any Copyright notices in
  17. * the code are not to be removed.
  18. * If this package is used in a product, Eric Young should be given attribution
  19. * as the author of the parts of the library used.
  20. * This can be in the form of a textual message at program startup or
  21. * in documentation (online or textual) provided with the package.
  22. *
  23. * Redistribution and use in source and binary forms, with or without
  24. * modification, are permitted provided that the following conditions
  25. * are met:
  26. * 1. Redistributions of source code must retain the copyright
  27. * notice, this list of conditions and the following disclaimer.
  28. * 2. Redistributions in binary form must reproduce the above copyright
  29. * notice, this list of conditions and the following disclaimer in the
  30. * documentation and/or other materials provided with the distribution.
  31. * 3. All advertising materials mentioning features or use of this software
  32. * must display the following acknowledgement:
  33. * "This product includes cryptographic software written by
  34. * Eric Young ([email protected])"
  35. * The word 'cryptographic' can be left out if the rouines from the library
  36. * being used are not cryptographic related :-).
  37. * 4. If you include any Windows specific code (or a derivative thereof) from
  38. * the apps directory (application code) you must include an acknowledgement:
  39. * "This product includes software written by Tim Hudson ([email protected])"
  40. *
  41. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  42. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  43. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  44. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  45. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  46. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  47. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  48. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  49. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  50. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  51. * SUCH DAMAGE.
  52. *
  53. * The licence and distribution terms for any publically available version or
  54. * derivative of this code cannot be changed. i.e. this code cannot simply be
  55. * copied and put under another distribution licence
  56. * [including the GNU Public Licence.]
  57. */
  58. /* ====================================================================
  59. * Copyright (c) 1998-2018 The OpenSSL Project. All rights reserved.
  60. *
  61. * Redistribution and use in source and binary forms, with or without
  62. * modification, are permitted provided that the following conditions
  63. * are met:
  64. *
  65. * 1. Redistributions of source code must retain the above copyright
  66. * notice, this list of conditions and the following disclaimer.
  67. *
  68. * 2. Redistributions in binary form must reproduce the above copyright
  69. * notice, this list of conditions and the following disclaimer in
  70. * the documentation and/or other materials provided with the
  71. * distribution.
  72. *
  73. * 3. All advertising materials mentioning features or use of this
  74. * software must display the following acknowledgment:
  75. * "This product includes software developed by the OpenSSL Project
  76. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  77. *
  78. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  79. * endorse or promote products derived from this software without
  80. * prior written permission. For written permission, please contact
  81. * [email protected].
  82. *
  83. * 5. Products derived from this software may not be called "OpenSSL"
  84. * nor may "OpenSSL" appear in their names without prior written
  85. * permission of the OpenSSL Project.
  86. *
  87. * 6. Redistributions of any form whatsoever must retain the following
  88. * acknowledgment:
  89. * "This product includes software developed by the OpenSSL Project
  90. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  91. *
  92. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  93. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  94. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  95. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  96. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  97. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  98. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  99. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  100. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  101. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  102. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  103. * OF THE POSSIBILITY OF SUCH DAMAGE.
  104. * ====================================================================
  105. *
  106. * This product includes cryptographic software written by Eric Young
  107. * ([email protected]). This product includes software written by Tim
  108. * Hudson ([email protected]).
  109. *
  110. */
  111. /*
  112. * Details about Montgomery multiplication algorithms can be found at
  113. * http://security.ece.orst.edu/publications.html, e.g.
  114. * http://security.ece.orst.edu/koc/papers/j37acmon.pdf and
  115. * sections 3.8 and 4.2 in http://security.ece.orst.edu/koc/papers/r01rsasw.pdf
  116. */
  117. #include <stdio.h>
  118. #include "cryptlib.h"
  119. #include "bn_lcl.h"
  120. #define MONT_WORD /* use the faster word-based algorithm */
  121. #ifdef MONT_WORD
  122. static int bn_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont);
  123. #endif
  124. int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
  125. BN_MONT_CTX *mont, BN_CTX *ctx)
  126. {
  127. int ret = bn_mul_mont_fixed_top(r, a, b, mont, ctx);
  128. bn_correct_top(r);
  129. bn_check_top(r);
  130. return ret;
  131. }
  132. int bn_mul_mont_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
  133. BN_MONT_CTX *mont, BN_CTX *ctx)
  134. {
  135. BIGNUM *tmp;
  136. int ret = 0;
  137. #if defined(OPENSSL_BN_ASM_MONT) && defined(MONT_WORD)
  138. int num = mont->N.top;
  139. if (num > 1 && a->top == num && b->top == num) {
  140. if (bn_wexpand(r, num) == NULL)
  141. return (0);
  142. if (bn_mul_mont(r->d, a->d, b->d, mont->N.d, mont->n0, num)) {
  143. r->neg = a->neg ^ b->neg;
  144. r->top = num;
  145. r->flags |= BN_FLG_FIXED_TOP;
  146. return 1;
  147. }
  148. }
  149. #endif
  150. BN_CTX_start(ctx);
  151. tmp = BN_CTX_get(ctx);
  152. if (tmp == NULL)
  153. goto err;
  154. bn_check_top(tmp);
  155. if (a == b) {
  156. if (!bn_sqr_fixed_top(tmp, a, ctx))
  157. goto err;
  158. } else {
  159. if (!bn_mul_fixed_top(tmp, a, b, ctx))
  160. goto err;
  161. }
  162. /* reduce from aRR to aR */
  163. #ifdef MONT_WORD
  164. if (!bn_from_montgomery_word(r, tmp, mont))
  165. goto err;
  166. #else
  167. if (!BN_from_montgomery(r, tmp, mont, ctx))
  168. goto err;
  169. #endif
  170. ret = 1;
  171. err:
  172. BN_CTX_end(ctx);
  173. return (ret);
  174. }
  175. #ifdef MONT_WORD
  176. static int bn_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont)
  177. {
  178. BIGNUM *n;
  179. BN_ULONG *ap, *np, *rp, n0, v, carry;
  180. int nl, max, i;
  181. unsigned int rtop;
  182. n = &(mont->N);
  183. nl = n->top;
  184. if (nl == 0) {
  185. ret->top = 0;
  186. return (1);
  187. }
  188. max = (2 * nl); /* carry is stored separately */
  189. if (bn_wexpand(r, max) == NULL)
  190. return (0);
  191. r->neg ^= n->neg;
  192. np = n->d;
  193. rp = r->d;
  194. /* clear the top words of T */
  195. for (rtop = r->top, i = 0; i < max; i++) {
  196. v = (BN_ULONG)0 - ((i - rtop) >> (8 * sizeof(rtop) - 1));
  197. rp[i] &= v;
  198. }
  199. r->top = max;
  200. r->flags |= BN_FLG_FIXED_TOP;
  201. n0 = mont->n0[0];
  202. /*
  203. * Add multiples of |n| to |r| until R = 2^(nl * BN_BITS2) divides it. On
  204. * input, we had |r| < |n| * R, so now |r| < 2 * |n| * R. Note that |r|
  205. * includes |carry| which is stored separately.
  206. */
  207. for (carry = 0, i = 0; i < nl; i++, rp++) {
  208. v = bn_mul_add_words(rp, np, nl, (rp[0] * n0) & BN_MASK2);
  209. v = (v + carry + rp[nl]) & BN_MASK2;
  210. carry |= (v != rp[nl]);
  211. carry &= (v <= rp[nl]);
  212. rp[nl] = v;
  213. }
  214. if (bn_wexpand(ret, nl) == NULL)
  215. return (0);
  216. ret->top = nl;
  217. ret->flags |= BN_FLG_FIXED_TOP;
  218. ret->neg = r->neg;
  219. rp = ret->d;
  220. /*
  221. * Shift |nl| words to divide by R. We have |ap| < 2 * |n|. Note that |ap|
  222. * includes |carry| which is stored separately.
  223. */
  224. ap = &(r->d[nl]);
  225. carry -= bn_sub_words(rp, ap, np, nl);
  226. /*
  227. * |carry| is -1 if |ap| - |np| underflowed or zero if it did not. Note
  228. * |carry| cannot be 1. That would imply the subtraction did not fit in
  229. * |nl| words, and we know at most one subtraction is needed.
  230. */
  231. for (i = 0; i < nl; i++) {
  232. rp[i] = (carry & ap[i]) | (~carry & rp[i]);
  233. ap[i] = 0;
  234. }
  235. return (1);
  236. }
  237. #endif /* MONT_WORD */
  238. int BN_from_montgomery(BIGNUM *ret, const BIGNUM *a, BN_MONT_CTX *mont,
  239. BN_CTX *ctx)
  240. {
  241. int retn;
  242. retn = bn_from_mont_fixed_top(ret, a, mont, ctx);
  243. bn_correct_top(ret);
  244. bn_check_top(ret);
  245. return retn;
  246. }
  247. int bn_from_mont_fixed_top(BIGNUM *ret, const BIGNUM *a, BN_MONT_CTX *mont,
  248. BN_CTX *ctx)
  249. {
  250. int retn = 0;
  251. #ifdef MONT_WORD
  252. BIGNUM *t;
  253. BN_CTX_start(ctx);
  254. if ((t = BN_CTX_get(ctx)) && BN_copy(t, a)) {
  255. retn = bn_from_montgomery_word(ret, t, mont);
  256. }
  257. BN_CTX_end(ctx);
  258. #else /* !MONT_WORD */
  259. BIGNUM *t1, *t2;
  260. BN_CTX_start(ctx);
  261. t1 = BN_CTX_get(ctx);
  262. t2 = BN_CTX_get(ctx);
  263. if (t1 == NULL || t2 == NULL)
  264. goto err;
  265. if (!BN_copy(t1, a))
  266. goto err;
  267. BN_mask_bits(t1, mont->ri);
  268. if (!BN_mul(t2, t1, &mont->Ni, ctx))
  269. goto err;
  270. BN_mask_bits(t2, mont->ri);
  271. if (!BN_mul(t1, t2, &mont->N, ctx))
  272. goto err;
  273. if (!BN_add(t2, a, t1))
  274. goto err;
  275. if (!BN_rshift(ret, t2, mont->ri))
  276. goto err;
  277. if (BN_ucmp(ret, &(mont->N)) >= 0) {
  278. if (!BN_usub(ret, ret, &(mont->N)))
  279. goto err;
  280. }
  281. retn = 1;
  282. bn_check_top(ret);
  283. err:
  284. BN_CTX_end(ctx);
  285. #endif /* MONT_WORD */
  286. return (retn);
  287. }
  288. int bn_to_mont_fixed_top(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
  289. BN_CTX *ctx)
  290. {
  291. return bn_mul_mont_fixed_top(r, a, &(mont->RR), mont, ctx);
  292. }
  293. BN_MONT_CTX *BN_MONT_CTX_new(void)
  294. {
  295. BN_MONT_CTX *ret;
  296. if ((ret = (BN_MONT_CTX *)OPENSSL_malloc(sizeof(BN_MONT_CTX))) == NULL)
  297. return (NULL);
  298. BN_MONT_CTX_init(ret);
  299. ret->flags = BN_FLG_MALLOCED;
  300. return (ret);
  301. }
  302. void BN_MONT_CTX_init(BN_MONT_CTX *ctx)
  303. {
  304. ctx->ri = 0;
  305. BN_init(&(ctx->RR));
  306. BN_init(&(ctx->N));
  307. BN_init(&(ctx->Ni));
  308. ctx->n0[0] = ctx->n0[1] = 0;
  309. ctx->flags = 0;
  310. }
  311. void BN_MONT_CTX_free(BN_MONT_CTX *mont)
  312. {
  313. if (mont == NULL)
  314. return;
  315. BN_clear_free(&(mont->RR));
  316. BN_clear_free(&(mont->N));
  317. BN_clear_free(&(mont->Ni));
  318. if (mont->flags & BN_FLG_MALLOCED)
  319. OPENSSL_free(mont);
  320. }
  321. int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx)
  322. {
  323. int i, ret = 0;
  324. BIGNUM *Ri, *R;
  325. if (BN_is_zero(mod))
  326. return 0;
  327. BN_CTX_start(ctx);
  328. if ((Ri = BN_CTX_get(ctx)) == NULL)
  329. goto err;
  330. R = &(mont->RR); /* grab RR as a temp */
  331. if (!BN_copy(&(mont->N), mod))
  332. goto err; /* Set N */
  333. if (BN_get_flags(mod, BN_FLG_CONSTTIME) != 0)
  334. BN_set_flags(&(mont->N), BN_FLG_CONSTTIME);
  335. mont->N.neg = 0;
  336. #ifdef MONT_WORD
  337. {
  338. BIGNUM tmod;
  339. BN_ULONG buf[2];
  340. BN_init(&tmod);
  341. tmod.d = buf;
  342. tmod.dmax = 2;
  343. tmod.neg = 0;
  344. if (BN_get_flags(mod, BN_FLG_CONSTTIME) != 0)
  345. BN_set_flags(&tmod, BN_FLG_CONSTTIME);
  346. mont->ri = (BN_num_bits(mod) + (BN_BITS2 - 1)) / BN_BITS2 * BN_BITS2;
  347. # if defined(OPENSSL_BN_ASM_MONT) && (BN_BITS2<=32)
  348. /*
  349. * Only certain BN_BITS2<=32 platforms actually make use of n0[1],
  350. * and we could use the #else case (with a shorter R value) for the
  351. * others. However, currently only the assembler files do know which
  352. * is which.
  353. */
  354. BN_zero(R);
  355. if (!(BN_set_bit(R, 2 * BN_BITS2)))
  356. goto err;
  357. tmod.top = 0;
  358. if ((buf[0] = mod->d[0]))
  359. tmod.top = 1;
  360. if ((buf[1] = mod->top > 1 ? mod->d[1] : 0))
  361. tmod.top = 2;
  362. if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL)
  363. goto err;
  364. if (!BN_lshift(Ri, Ri, 2 * BN_BITS2))
  365. goto err; /* R*Ri */
  366. if (!BN_is_zero(Ri)) {
  367. if (!BN_sub_word(Ri, 1))
  368. goto err;
  369. } else { /* if N mod word size == 1 */
  370. if (bn_expand(Ri, (int)sizeof(BN_ULONG) * 2) == NULL)
  371. goto err;
  372. /* Ri-- (mod double word size) */
  373. Ri->neg = 0;
  374. Ri->d[0] = BN_MASK2;
  375. Ri->d[1] = BN_MASK2;
  376. Ri->top = 2;
  377. }
  378. if (!BN_div(Ri, NULL, Ri, &tmod, ctx))
  379. goto err;
  380. /*
  381. * Ni = (R*Ri-1)/N, keep only couple of least significant words:
  382. */
  383. mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0;
  384. mont->n0[1] = (Ri->top > 1) ? Ri->d[1] : 0;
  385. # else
  386. BN_zero(R);
  387. if (!(BN_set_bit(R, BN_BITS2)))
  388. goto err; /* R */
  389. buf[0] = mod->d[0]; /* tmod = N mod word size */
  390. buf[1] = 0;
  391. tmod.top = buf[0] != 0 ? 1 : 0;
  392. /* Ri = R^-1 mod N */
  393. if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL)
  394. goto err;
  395. if (!BN_lshift(Ri, Ri, BN_BITS2))
  396. goto err; /* R*Ri */
  397. if (!BN_is_zero(Ri)) {
  398. if (!BN_sub_word(Ri, 1))
  399. goto err;
  400. } else { /* if N mod word size == 1 */
  401. if (!BN_set_word(Ri, BN_MASK2))
  402. goto err; /* Ri-- (mod word size) */
  403. }
  404. if (!BN_div(Ri, NULL, Ri, &tmod, ctx))
  405. goto err;
  406. /*
  407. * Ni = (R*Ri-1)/N, keep only least significant word:
  408. */
  409. mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0;
  410. mont->n0[1] = 0;
  411. # endif
  412. }
  413. #else /* !MONT_WORD */
  414. { /* bignum version */
  415. mont->ri = BN_num_bits(&mont->N);
  416. BN_zero(R);
  417. if (!BN_set_bit(R, mont->ri))
  418. goto err; /* R = 2^ri */
  419. /* Ri = R^-1 mod N */
  420. if ((BN_mod_inverse(Ri, R, &mont->N, ctx)) == NULL)
  421. goto err;
  422. if (!BN_lshift(Ri, Ri, mont->ri))
  423. goto err; /* R*Ri */
  424. if (!BN_sub_word(Ri, 1))
  425. goto err;
  426. /*
  427. * Ni = (R*Ri-1) / N
  428. */
  429. if (!BN_div(&(mont->Ni), NULL, Ri, &mont->N, ctx))
  430. goto err;
  431. }
  432. #endif
  433. /* setup RR for conversions */
  434. BN_zero(&(mont->RR));
  435. if (!BN_set_bit(&(mont->RR), mont->ri * 2))
  436. goto err;
  437. if (!BN_mod(&(mont->RR), &(mont->RR), &(mont->N), ctx))
  438. goto err;
  439. for (i = mont->RR.top, ret = mont->N.top; i < ret; i++)
  440. mont->RR.d[i] = 0;
  441. mont->RR.top = ret;
  442. mont->RR.flags |= BN_FLG_FIXED_TOP;
  443. ret = 1;
  444. err:
  445. BN_CTX_end(ctx);
  446. return ret;
  447. }
  448. BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from)
  449. {
  450. if (to == from)
  451. return (to);
  452. if (!BN_copy(&(to->RR), &(from->RR)))
  453. return NULL;
  454. if (!BN_copy(&(to->N), &(from->N)))
  455. return NULL;
  456. if (!BN_copy(&(to->Ni), &(from->Ni)))
  457. return NULL;
  458. to->ri = from->ri;
  459. to->n0[0] = from->n0[0];
  460. to->n0[1] = from->n0[1];
  461. return (to);
  462. }
  463. BN_MONT_CTX *BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, int lock,
  464. const BIGNUM *mod, BN_CTX *ctx)
  465. {
  466. BN_MONT_CTX *ret;
  467. CRYPTO_r_lock(lock);
  468. ret = *pmont;
  469. CRYPTO_r_unlock(lock);
  470. if (ret)
  471. return ret;
  472. /*
  473. * We don't want to serialise globally while doing our lazy-init math in
  474. * BN_MONT_CTX_set. That punishes threads that are doing independent
  475. * things. Instead, punish the case where more than one thread tries to
  476. * lazy-init the same 'pmont', by having each do the lazy-init math work
  477. * independently and only use the one from the thread that wins the race
  478. * (the losers throw away the work they've done).
  479. */
  480. ret = BN_MONT_CTX_new();
  481. if (!ret)
  482. return NULL;
  483. if (!BN_MONT_CTX_set(ret, mod, ctx)) {
  484. BN_MONT_CTX_free(ret);
  485. return NULL;
  486. }
  487. /* The locked compare-and-set, after the local work is done. */
  488. CRYPTO_w_lock(lock);
  489. if (*pmont) {
  490. BN_MONT_CTX_free(ret);
  491. ret = *pmont;
  492. } else
  493. *pmont = ret;
  494. CRYPTO_w_unlock(lock);
  495. return ret;
  496. }