bn_mont.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. /* crypto/bn/bn_mont.c */
  2. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  3. * All rights reserved.
  4. *
  5. * This package is an SSL implementation written
  6. * by Eric Young (eay@cryptsoft.com).
  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 (tjh@cryptsoft.com).
  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 (eay@cryptsoft.com)"
  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 (tjh@cryptsoft.com)"
  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-2006 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. * openssl-core@openssl.org.
  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. * (eay@cryptsoft.com). This product includes software written by Tim
  108. * Hudson (tjh@cryptsoft.com).
  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. #if defined(MONT_WORD) && defined(OPENSSL_BN_ASM_MONT) && (BN_BITS2<=32)
  122. /*
  123. * This condition means we have a specific non-default build: In the 0.9.8
  124. * branch, OPENSSL_BN_ASM_MONT is normally not set for any BN_BITS2<=32
  125. * platform; an explicit "enable-montasm" is required. I.e., if we are here,
  126. * the user intentionally deviates from the normal stable build to get better
  127. * Montgomery performance from the 0.9.9-dev backport. In this case only, we
  128. * also enable BN_from_montgomery_word() (another non-stable feature from
  129. * 0.9.9-dev).
  130. */
  131. # define MONT_FROM_WORD___NON_DEFAULT_0_9_8_BUILD
  132. #endif
  133. #ifdef MONT_FROM_WORD___NON_DEFAULT_0_9_8_BUILD
  134. static int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont);
  135. #endif
  136. int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
  137. BN_MONT_CTX *mont, BN_CTX *ctx)
  138. {
  139. BIGNUM *tmp;
  140. int ret = 0;
  141. #if defined(OPENSSL_BN_ASM_MONT) && defined(MONT_WORD)
  142. int num = mont->N.top;
  143. if (num > 1 && a->top == num && b->top == num) {
  144. if (bn_wexpand(r, num) == NULL)
  145. return (0);
  146. # if 0 /* for OpenSSL 0.9.9 mont->n0 */
  147. if (bn_mul_mont(r->d, a->d, b->d, mont->N.d, mont->n0, num))
  148. # else
  149. if (bn_mul_mont(r->d, a->d, b->d, mont->N.d, &mont->n0, num))
  150. # endif
  151. {
  152. r->neg = a->neg ^ b->neg;
  153. r->top = num;
  154. bn_correct_top(r);
  155. return (1);
  156. }
  157. }
  158. #endif
  159. BN_CTX_start(ctx);
  160. tmp = BN_CTX_get(ctx);
  161. if (tmp == NULL)
  162. goto err;
  163. bn_check_top(tmp);
  164. if (a == b) {
  165. if (!BN_sqr(tmp, a, ctx))
  166. goto err;
  167. } else {
  168. if (!BN_mul(tmp, a, b, ctx))
  169. goto err;
  170. }
  171. /* reduce from aRR to aR */
  172. #ifdef MONT_FROM_WORD___NON_DEFAULT_0_9_8_BUILD
  173. if (!BN_from_montgomery_word(r, tmp, mont))
  174. goto err;
  175. #else
  176. if (!BN_from_montgomery(r, tmp, mont, ctx))
  177. goto err;
  178. #endif
  179. bn_check_top(r);
  180. ret = 1;
  181. err:
  182. BN_CTX_end(ctx);
  183. return (ret);
  184. }
  185. #ifdef MONT_FROM_WORD___NON_DEFAULT_0_9_8_BUILD
  186. static int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont)
  187. {
  188. BIGNUM *n;
  189. BN_ULONG *ap, *np, *rp, n0, v, *nrp;
  190. int al, nl, max, i, x, ri;
  191. n = &(mont->N);
  192. /*
  193. * mont->ri is the size of mont->N in bits (rounded up to the word size)
  194. */
  195. al = ri = mont->ri / BN_BITS2;
  196. nl = n->top;
  197. if ((al == 0) || (nl == 0)) {
  198. ret->top = 0;
  199. return (1);
  200. }
  201. max = (nl + al + 1); /* allow for overflow (no?) XXX */
  202. if (bn_wexpand(r, max) == NULL)
  203. return (0);
  204. r->neg ^= n->neg;
  205. np = n->d;
  206. rp = r->d;
  207. nrp = &(r->d[nl]);
  208. /* clear the top words of T */
  209. for (i = r->top; i < max; i++) /* memset? XXX */
  210. r->d[i] = 0;
  211. r->top = max;
  212. # if 0 /* for OpenSSL 0.9.9 mont->n0 */
  213. n0 = mont->n0[0];
  214. # else
  215. n0 = mont->n0;
  216. # endif
  217. # ifdef BN_COUNT
  218. fprintf(stderr, "word BN_from_montgomery_word %d * %d\n", nl, nl);
  219. # endif
  220. for (i = 0; i < nl; i++) {
  221. # ifdef __TANDEM
  222. {
  223. long long t1;
  224. long long t2;
  225. long long t3;
  226. t1 = rp[0] * (n0 & 0177777);
  227. t2 = 037777600000l;
  228. t2 = n0 & t2;
  229. t3 = rp[0] & 0177777;
  230. t2 = (t3 * t2) & BN_MASK2;
  231. t1 = t1 + t2;
  232. v = bn_mul_add_words(rp, np, nl, (BN_ULONG)t1);
  233. }
  234. # else
  235. v = bn_mul_add_words(rp, np, nl, (rp[0] * n0) & BN_MASK2);
  236. # endif
  237. nrp++;
  238. rp++;
  239. if (((nrp[-1] += v) & BN_MASK2) >= v)
  240. continue;
  241. else {
  242. if (((++nrp[0]) & BN_MASK2) != 0)
  243. continue;
  244. if (((++nrp[1]) & BN_MASK2) != 0)
  245. continue;
  246. for (x = 2; (((++nrp[x]) & BN_MASK2) == 0); x++) ;
  247. }
  248. }
  249. bn_correct_top(r);
  250. /*
  251. * mont->ri will be a multiple of the word size and below code is kind of
  252. * BN_rshift(ret,r,mont->ri) equivalent
  253. */
  254. if (r->top <= ri) {
  255. ret->top = 0;
  256. return (1);
  257. }
  258. al = r->top - ri;
  259. if (bn_wexpand(ret, ri) == NULL)
  260. return (0);
  261. x = 0 - (((al - ri) >> (sizeof(al) * 8 - 1)) & 1);
  262. ret->top = x = (ri & ~x) | (al & x); /* min(ri,al) */
  263. ret->neg = r->neg;
  264. rp = ret->d;
  265. ap = &(r->d[ri]);
  266. {
  267. size_t m1, m2;
  268. v = bn_sub_words(rp, ap, np, ri);
  269. /*
  270. * this ----------------^^ works even in al<ri case thanks to zealous
  271. * zeroing of top of the vector in the beginning.
  272. */
  273. /* if (al==ri && !v) || al>ri) nrp=rp; else nrp=ap; */
  274. /*
  275. * in other words if subtraction result is real, then trick
  276. * unconditional memcpy below to perform in-place "refresh" instead
  277. * of actual copy.
  278. */
  279. m1 = 0 - (size_t)(((al - ri) >> (sizeof(al) * 8 - 1)) & 1); /* al<ri */
  280. m2 = 0 - (size_t)(((ri - al) >> (sizeof(al) * 8 - 1)) & 1); /* al>ri */
  281. m1 |= m2; /* (al!=ri) */
  282. m1 |= (0 - (size_t)v); /* (al!=ri || v) */
  283. m1 &= ~m2; /* (al!=ri || v) && !al>ri */
  284. nrp = (BN_ULONG *)(((size_t)rp & ~m1) | ((size_t)ap & m1));
  285. }
  286. /*
  287. * 'i<ri' is chosen to eliminate dependency on input data, even though it
  288. * results in redundant copy in al<ri case.
  289. */
  290. for (i = 0, ri -= 4; i < ri; i += 4) {
  291. BN_ULONG t1, t2, t3, t4;
  292. t1 = nrp[i + 0];
  293. t2 = nrp[i + 1];
  294. t3 = nrp[i + 2];
  295. ap[i + 0] = 0;
  296. t4 = nrp[i + 3];
  297. ap[i + 1] = 0;
  298. rp[i + 0] = t1;
  299. ap[i + 2] = 0;
  300. rp[i + 1] = t2;
  301. ap[i + 3] = 0;
  302. rp[i + 2] = t3;
  303. rp[i + 3] = t4;
  304. }
  305. for (ri += 4; i < ri; i++)
  306. rp[i] = nrp[i], ap[i] = 0;
  307. bn_correct_top(r);
  308. bn_correct_top(ret);
  309. bn_check_top(ret);
  310. return (1);
  311. }
  312. int BN_from_montgomery(BIGNUM *ret, const BIGNUM *a, BN_MONT_CTX *mont,
  313. BN_CTX *ctx)
  314. {
  315. int retn = 0;
  316. BIGNUM *t;
  317. BN_CTX_start(ctx);
  318. if ((t = BN_CTX_get(ctx)) && BN_copy(t, a))
  319. retn = BN_from_montgomery_word(ret, t, mont);
  320. BN_CTX_end(ctx);
  321. return retn;
  322. }
  323. #else /* !MONT_FROM_WORD___NON_DEFAULT_0_9_8_BUILD */
  324. int BN_from_montgomery(BIGNUM *ret, const BIGNUM *a, BN_MONT_CTX *mont,
  325. BN_CTX *ctx)
  326. {
  327. int retn = 0;
  328. # ifdef MONT_WORD
  329. BIGNUM *n, *r;
  330. BN_ULONG *ap, *np, *rp, n0, v, *nrp;
  331. int al, nl, max, i, x, ri;
  332. BN_CTX_start(ctx);
  333. if ((r = BN_CTX_get(ctx)) == NULL)
  334. goto err;
  335. if (!BN_copy(r, a))
  336. goto err;
  337. n = &(mont->N);
  338. ap = a->d;
  339. /*
  340. * mont->ri is the size of mont->N in bits (rounded up to the word size)
  341. */
  342. al = ri = mont->ri / BN_BITS2;
  343. nl = n->top;
  344. if ((al == 0) || (nl == 0)) {
  345. r->top = 0;
  346. return (1);
  347. }
  348. max = (nl + al + 1); /* allow for overflow (no?) XXX */
  349. if (bn_wexpand(r, max) == NULL)
  350. goto err;
  351. r->neg = a->neg ^ n->neg;
  352. np = n->d;
  353. rp = r->d;
  354. nrp = &(r->d[nl]);
  355. /* clear the top words of T */
  356. # if 1
  357. for (i = r->top; i < max; i++) /* memset? XXX */
  358. r->d[i] = 0;
  359. # else
  360. memset(&(r->d[r->top]), 0, (max - r->top) * sizeof(BN_ULONG));
  361. # endif
  362. r->top = max;
  363. n0 = mont->n0;
  364. # ifdef BN_COUNT
  365. fprintf(stderr, "word BN_from_montgomery %d * %d\n", nl, nl);
  366. # endif
  367. for (i = 0; i < nl; i++) {
  368. # ifdef __TANDEM
  369. {
  370. long long t1;
  371. long long t2;
  372. long long t3;
  373. t1 = rp[0] * (n0 & 0177777);
  374. t2 = 037777600000l;
  375. t2 = n0 & t2;
  376. t3 = rp[0] & 0177777;
  377. t2 = (t3 * t2) & BN_MASK2;
  378. t1 = t1 + t2;
  379. v = bn_mul_add_words(rp, np, nl, (BN_ULONG)t1);
  380. }
  381. # else
  382. v = bn_mul_add_words(rp, np, nl, (rp[0] * n0) & BN_MASK2);
  383. # endif
  384. nrp++;
  385. rp++;
  386. if (((nrp[-1] += v) & BN_MASK2) >= v)
  387. continue;
  388. else {
  389. if (((++nrp[0]) & BN_MASK2) != 0)
  390. continue;
  391. if (((++nrp[1]) & BN_MASK2) != 0)
  392. continue;
  393. for (x = 2; (((++nrp[x]) & BN_MASK2) == 0); x++) ;
  394. }
  395. }
  396. bn_correct_top(r);
  397. /*
  398. * mont->ri will be a multiple of the word size and below code is kind of
  399. * BN_rshift(ret,r,mont->ri) equivalent
  400. */
  401. if (r->top <= ri) {
  402. ret->top = 0;
  403. retn = 1;
  404. goto err;
  405. }
  406. al = r->top - ri;
  407. # define BRANCH_FREE 1
  408. # if BRANCH_FREE
  409. if (bn_wexpand(ret, ri) == NULL)
  410. goto err;
  411. x = 0 - (((al - ri) >> (sizeof(al) * 8 - 1)) & 1);
  412. ret->top = x = (ri & ~x) | (al & x); /* min(ri,al) */
  413. ret->neg = r->neg;
  414. rp = ret->d;
  415. ap = &(r->d[ri]);
  416. {
  417. size_t m1, m2;
  418. v = bn_sub_words(rp, ap, np, ri);
  419. /*
  420. * this ----------------^^ works even in al<ri case thanks to zealous
  421. * zeroing of top of the vector in the beginning.
  422. */
  423. /* if (al==ri && !v) || al>ri) nrp=rp; else nrp=ap; */
  424. /*
  425. * in other words if subtraction result is real, then trick
  426. * unconditional memcpy below to perform in-place "refresh" instead
  427. * of actual copy.
  428. */
  429. m1 = 0 - (size_t)(((al - ri) >> (sizeof(al) * 8 - 1)) & 1); /* al<ri */
  430. m2 = 0 - (size_t)(((ri - al) >> (sizeof(al) * 8 - 1)) & 1); /* al>ri */
  431. m1 |= m2; /* (al!=ri) */
  432. m1 |= (0 - (size_t)v); /* (al!=ri || v) */
  433. m1 &= ~m2; /* (al!=ri || v) && !al>ri */
  434. nrp = (BN_ULONG *)(((size_t)rp & ~m1) | ((size_t)ap & m1));
  435. }
  436. /*
  437. * 'i<ri' is chosen to eliminate dependency on input data, even though it
  438. * results in redundant copy in al<ri case.
  439. */
  440. for (i = 0, ri -= 4; i < ri; i += 4) {
  441. BN_ULONG t1, t2, t3, t4;
  442. t1 = nrp[i + 0];
  443. t2 = nrp[i + 1];
  444. t3 = nrp[i + 2];
  445. ap[i + 0] = 0;
  446. t4 = nrp[i + 3];
  447. ap[i + 1] = 0;
  448. rp[i + 0] = t1;
  449. ap[i + 2] = 0;
  450. rp[i + 1] = t2;
  451. ap[i + 3] = 0;
  452. rp[i + 2] = t3;
  453. rp[i + 3] = t4;
  454. }
  455. for (ri += 4; i < ri; i++)
  456. rp[i] = nrp[i], ap[i] = 0;
  457. bn_correct_top(r);
  458. bn_correct_top(ret);
  459. # else
  460. if (bn_wexpand(ret, al) == NULL)
  461. goto err;
  462. ret->top = al;
  463. ret->neg = r->neg;
  464. rp = ret->d;
  465. ap = &(r->d[ri]);
  466. al -= 4;
  467. for (i = 0; i < al; i += 4) {
  468. BN_ULONG t1, t2, t3, t4;
  469. t1 = ap[i + 0];
  470. t2 = ap[i + 1];
  471. t3 = ap[i + 2];
  472. t4 = ap[i + 3];
  473. rp[i + 0] = t1;
  474. rp[i + 1] = t2;
  475. rp[i + 2] = t3;
  476. rp[i + 3] = t4;
  477. }
  478. al += 4;
  479. for (; i < al; i++)
  480. rp[i] = ap[i];
  481. # endif
  482. # else /* !MONT_WORD */
  483. BIGNUM *t1, *t2;
  484. BN_CTX_start(ctx);
  485. t1 = BN_CTX_get(ctx);
  486. t2 = BN_CTX_get(ctx);
  487. if (t1 == NULL || t2 == NULL)
  488. goto err;
  489. if (!BN_copy(t1, a))
  490. goto err;
  491. BN_mask_bits(t1, mont->ri);
  492. if (!BN_mul(t2, t1, &mont->Ni, ctx))
  493. goto err;
  494. BN_mask_bits(t2, mont->ri);
  495. if (!BN_mul(t1, t2, &mont->N, ctx))
  496. goto err;
  497. if (!BN_add(t2, a, t1))
  498. goto err;
  499. if (!BN_rshift(ret, t2, mont->ri))
  500. goto err;
  501. # endif /* MONT_WORD */
  502. # if !defined(BRANCH_FREE) || BRANCH_FREE==0
  503. if (BN_ucmp(ret, &(mont->N)) >= 0) {
  504. if (!BN_usub(ret, ret, &(mont->N)))
  505. goto err;
  506. }
  507. # endif
  508. retn = 1;
  509. bn_check_top(ret);
  510. err:
  511. BN_CTX_end(ctx);
  512. return (retn);
  513. }
  514. #endif /* MONT_FROM_WORD___NON_DEFAULT_0_9_8_BUILD */
  515. BN_MONT_CTX *BN_MONT_CTX_new(void)
  516. {
  517. BN_MONT_CTX *ret;
  518. if ((ret = (BN_MONT_CTX *)OPENSSL_malloc(sizeof(BN_MONT_CTX))) == NULL)
  519. return (NULL);
  520. BN_MONT_CTX_init(ret);
  521. ret->flags = BN_FLG_MALLOCED;
  522. return (ret);
  523. }
  524. void BN_MONT_CTX_init(BN_MONT_CTX *ctx)
  525. {
  526. ctx->ri = 0;
  527. BN_init(&(ctx->RR));
  528. BN_init(&(ctx->N));
  529. BN_init(&(ctx->Ni));
  530. #if 0 /* for OpenSSL 0.9.9 mont->n0 */
  531. ctx->n0[0] = ctx->n0[1] = 0;
  532. #else
  533. ctx->n0 = 0;
  534. #endif
  535. ctx->flags = 0;
  536. }
  537. void BN_MONT_CTX_free(BN_MONT_CTX *mont)
  538. {
  539. if (mont == NULL)
  540. return;
  541. BN_free(&(mont->RR));
  542. BN_free(&(mont->N));
  543. BN_free(&(mont->Ni));
  544. if (mont->flags & BN_FLG_MALLOCED)
  545. OPENSSL_free(mont);
  546. }
  547. int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx)
  548. {
  549. int ret = 0;
  550. BIGNUM *Ri, *R;
  551. BN_CTX_start(ctx);
  552. if ((Ri = BN_CTX_get(ctx)) == NULL)
  553. goto err;
  554. R = &(mont->RR); /* grab RR as a temp */
  555. if (!BN_copy(&(mont->N), mod))
  556. goto err; /* Set N */
  557. mont->N.neg = 0;
  558. #ifdef MONT_WORD
  559. {
  560. BIGNUM tmod;
  561. BN_ULONG buf[2];
  562. mont->ri = (BN_num_bits(mod) + (BN_BITS2 - 1)) / BN_BITS2 * BN_BITS2;
  563. BN_zero(R);
  564. # if 0 /* for OpenSSL 0.9.9 mont->n0, would be "#if
  565. * defined(OPENSSL_BN_ASM_MONT) &&
  566. * (BN_BITS2<=32)", only certain BN_BITS2<=32
  567. * platforms actually need this */
  568. if (!(BN_set_bit(R, 2 * BN_BITS2)))
  569. goto err; /* R */
  570. # else
  571. if (!(BN_set_bit(R, BN_BITS2)))
  572. goto err; /* R */
  573. # endif
  574. buf[0] = mod->d[0]; /* tmod = N mod word size */
  575. buf[1] = 0;
  576. BN_init(&tmod);
  577. tmod.d = buf;
  578. tmod.top = buf[0] != 0 ? 1 : 0;
  579. tmod.dmax = 2;
  580. tmod.neg = 0;
  581. # if 0 /* for OpenSSL 0.9.9 mont->n0, would be "#if
  582. * defined(OPENSSL_BN_ASM_MONT) &&
  583. * (BN_BITS2<=32)"; only certain BN_BITS2<=32
  584. * platforms actually need this */
  585. tmod.top = 0;
  586. if ((buf[0] = mod->d[0]))
  587. tmod.top = 1;
  588. if ((buf[1] = mod->top > 1 ? mod->d[1] : 0))
  589. tmod.top = 2;
  590. if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL)
  591. goto err;
  592. if (!BN_lshift(Ri, Ri, 2 * BN_BITS2))
  593. goto err; /* R*Ri */
  594. if (!BN_is_zero(Ri)) {
  595. if (!BN_sub_word(Ri, 1))
  596. goto err;
  597. } else { /* if N mod word size == 1 */
  598. if (bn_expand(Ri, (int)sizeof(BN_ULONG) * 2) == NULL)
  599. goto err;
  600. /* Ri-- (mod double word size) */
  601. Ri->neg = 0;
  602. Ri->d[0] = BN_MASK2;
  603. Ri->d[1] = BN_MASK2;
  604. Ri->top = 2;
  605. }
  606. if (!BN_div(Ri, NULL, Ri, &tmod, ctx))
  607. goto err;
  608. /*
  609. * Ni = (R*Ri-1)/N, keep only couple of least significant words:
  610. */
  611. mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0;
  612. mont->n0[1] = (Ri->top > 1) ? Ri->d[1] : 0;
  613. # else
  614. /* Ri = R^-1 mod N */
  615. if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL)
  616. goto err;
  617. if (!BN_lshift(Ri, Ri, BN_BITS2))
  618. goto err; /* R*Ri */
  619. if (!BN_is_zero(Ri)) {
  620. if (!BN_sub_word(Ri, 1))
  621. goto err;
  622. } else { /* if N mod word size == 1 */
  623. if (!BN_set_word(Ri, BN_MASK2))
  624. goto err; /* Ri-- (mod word size) */
  625. }
  626. if (!BN_div(Ri, NULL, Ri, &tmod, ctx))
  627. goto err;
  628. /*
  629. * Ni = (R*Ri-1)/N, keep only least significant word:
  630. */
  631. # if 0 /* for OpenSSL 0.9.9 mont->n0 */
  632. mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0;
  633. mont->n0[1] = 0;
  634. # else
  635. mont->n0 = (Ri->top > 0) ? Ri->d[0] : 0;
  636. # endif
  637. # endif
  638. }
  639. #else /* !MONT_WORD */
  640. { /* bignum version */
  641. mont->ri = BN_num_bits(&mont->N);
  642. BN_zero(R);
  643. if (!BN_set_bit(R, mont->ri))
  644. goto err; /* R = 2^ri */
  645. /* Ri = R^-1 mod N */
  646. if ((BN_mod_inverse(Ri, R, &mont->N, ctx)) == NULL)
  647. goto err;
  648. if (!BN_lshift(Ri, Ri, mont->ri))
  649. goto err; /* R*Ri */
  650. if (!BN_sub_word(Ri, 1))
  651. goto err;
  652. /*
  653. * Ni = (R*Ri-1) / N
  654. */
  655. if (!BN_div(&(mont->Ni), NULL, Ri, &mont->N, ctx))
  656. goto err;
  657. }
  658. #endif
  659. /* setup RR for conversions */
  660. BN_zero(&(mont->RR));
  661. if (!BN_set_bit(&(mont->RR), mont->ri * 2))
  662. goto err;
  663. if (!BN_mod(&(mont->RR), &(mont->RR), &(mont->N), ctx))
  664. goto err;
  665. ret = 1;
  666. err:
  667. BN_CTX_end(ctx);
  668. return ret;
  669. }
  670. BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from)
  671. {
  672. if (to == from)
  673. return (to);
  674. if (!BN_copy(&(to->RR), &(from->RR)))
  675. return NULL;
  676. if (!BN_copy(&(to->N), &(from->N)))
  677. return NULL;
  678. if (!BN_copy(&(to->Ni), &(from->Ni)))
  679. return NULL;
  680. to->ri = from->ri;
  681. #if 0 /* for OpenSSL 0.9.9 mont->n0 */
  682. to->n0[0] = from->n0[0];
  683. to->n0[1] = from->n0[1];
  684. #else
  685. to->n0 = from->n0;
  686. #endif
  687. return (to);
  688. }
  689. BN_MONT_CTX *BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, int lock,
  690. const BIGNUM *mod, BN_CTX *ctx)
  691. {
  692. BN_MONT_CTX *ret;
  693. CRYPTO_r_lock(lock);
  694. ret = *pmont;
  695. CRYPTO_r_unlock(lock);
  696. if (ret)
  697. return ret;
  698. /*
  699. * We don't want to serialise globally while doing our lazy-init math in
  700. * BN_MONT_CTX_set. That punishes threads that are doing independent
  701. * things. Instead, punish the case where more than one thread tries to
  702. * lazy-init the same 'pmont', by having each do the lazy-init math work
  703. * independently and only use the one from the thread that wins the race
  704. * (the losers throw away the work they've done).
  705. */
  706. ret = BN_MONT_CTX_new();
  707. if (!ret)
  708. return NULL;
  709. if (!BN_MONT_CTX_set(ret, mod, ctx)) {
  710. BN_MONT_CTX_free(ret);
  711. return NULL;
  712. }
  713. /* The locked compare-and-set, after the local work is done. */
  714. CRYPTO_w_lock(lock);
  715. if (*pmont) {
  716. BN_MONT_CTX_free(ret);
  717. ret = *pmont;
  718. } else
  719. *pmont = ret;
  720. CRYPTO_w_unlock(lock);
  721. return ret;
  722. }