Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

1563 рядки
42 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. */
  57. /* ====================================================================
  58. * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
  59. *
  60. * Redistribution and use in source and binary forms, with or without
  61. * modification, are permitted provided that the following conditions
  62. * are met:
  63. *
  64. * 1. Redistributions of source code must retain the above copyright
  65. * notice, this list of conditions and the following disclaimer.
  66. *
  67. * 2. Redistributions in binary form must reproduce the above copyright
  68. * notice, this list of conditions and the following disclaimer in
  69. * the documentation and/or other materials provided with the
  70. * distribution.
  71. *
  72. * 3. All advertising materials mentioning features or use of this
  73. * software must display the following acknowledgment:
  74. * "This product includes software developed by the OpenSSL Project
  75. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  76. *
  77. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  78. * endorse or promote products derived from this software without
  79. * prior written permission. For written permission, please contact
  80. * openssl-core@openssl.org.
  81. *
  82. * 5. Products derived from this software may not be called "OpenSSL"
  83. * nor may "OpenSSL" appear in their names without prior written
  84. * permission of the OpenSSL Project.
  85. *
  86. * 6. Redistributions of any form whatsoever must retain the following
  87. * acknowledgment:
  88. * "This product includes software developed by the OpenSSL Project
  89. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  90. *
  91. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  92. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  93. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  94. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  95. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  96. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  97. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  98. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  99. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  100. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  101. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  102. * OF THE POSSIBILITY OF SUCH DAMAGE.
  103. * ====================================================================
  104. *
  105. * This product includes cryptographic software written by Eric Young
  106. * (eay@cryptsoft.com). This product includes software written by Tim
  107. * Hudson (tjh@cryptsoft.com). */
  108. #include <openssl/bn.h>
  109. #include <assert.h>
  110. #include <string.h>
  111. #include <openssl/cpu.h>
  112. #include <openssl/err.h>
  113. #include <openssl/mem.h>
  114. #include "internal.h"
  115. #if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64)
  116. #define OPENSSL_BN_ASM_MONT5
  117. #define RSAZ_ENABLED
  118. #include "rsaz_exp.h"
  119. #endif
  120. int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) {
  121. int i, bits, ret = 0;
  122. BIGNUM *v, *rr;
  123. if ((p->flags & BN_FLG_CONSTTIME) != 0) {
  124. /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
  125. OPENSSL_PUT_ERROR(BN, BN_exp, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  126. return 0;
  127. }
  128. BN_CTX_start(ctx);
  129. if (r == a || r == p) {
  130. rr = BN_CTX_get(ctx);
  131. } else {
  132. rr = r;
  133. }
  134. v = BN_CTX_get(ctx);
  135. if (rr == NULL || v == NULL) {
  136. goto err;
  137. }
  138. if (BN_copy(v, a) == NULL) {
  139. goto err;
  140. }
  141. bits = BN_num_bits(p);
  142. if (BN_is_odd(p)) {
  143. if (BN_copy(rr, a) == NULL) {
  144. goto err;
  145. }
  146. } else {
  147. if (!BN_one(rr)) {
  148. goto err;
  149. }
  150. }
  151. for (i = 1; i < bits; i++) {
  152. if (!BN_sqr(v, v, ctx)) {
  153. goto err;
  154. }
  155. if (BN_is_bit_set(p, i)) {
  156. if (!BN_mul(rr, rr, v, ctx)) {
  157. goto err;
  158. }
  159. }
  160. }
  161. if (r != rr) {
  162. BN_copy(r, rr);
  163. }
  164. ret = 1;
  165. err:
  166. BN_CTX_end(ctx);
  167. return ret;
  168. }
  169. /* maximum precomputation table size for *variable* sliding windows */
  170. #define TABLE_SIZE 32
  171. typedef struct bn_recp_ctx_st {
  172. BIGNUM N; /* the divisor */
  173. BIGNUM Nr; /* the reciprocal */
  174. int num_bits;
  175. int shift;
  176. int flags;
  177. } BN_RECP_CTX;
  178. static void BN_RECP_CTX_init(BN_RECP_CTX *recp) {
  179. BN_init(&recp->N);
  180. BN_init(&recp->Nr);
  181. recp->num_bits = 0;
  182. recp->flags = 0;
  183. }
  184. static void BN_RECP_CTX_free(BN_RECP_CTX *recp) {
  185. if (recp == NULL) {
  186. return;
  187. }
  188. BN_free(&recp->N);
  189. BN_free(&recp->Nr);
  190. }
  191. static int BN_RECP_CTX_set(BN_RECP_CTX *recp, const BIGNUM *d, BN_CTX *ctx) {
  192. if (!BN_copy(&(recp->N), d)) {
  193. return 0;
  194. }
  195. BN_zero(&recp->Nr);
  196. recp->num_bits = BN_num_bits(d);
  197. recp->shift = 0;
  198. return 1;
  199. }
  200. /* len is the expected size of the result We actually calculate with an extra
  201. * word of precision, so we can do faster division if the remainder is not
  202. * required.
  203. * r := 2^len / m */
  204. static int BN_reciprocal(BIGNUM *r, const BIGNUM *m, int len, BN_CTX *ctx) {
  205. int ret = -1;
  206. BIGNUM *t;
  207. BN_CTX_start(ctx);
  208. t = BN_CTX_get(ctx);
  209. if (t == NULL) {
  210. goto err;
  211. }
  212. if (!BN_set_bit(t, len)) {
  213. goto err;
  214. }
  215. if (!BN_div(r, NULL, t, m, ctx)) {
  216. goto err;
  217. }
  218. ret = len;
  219. err:
  220. BN_CTX_end(ctx);
  221. return ret;
  222. }
  223. static int BN_div_recp(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m,
  224. BN_RECP_CTX *recp, BN_CTX *ctx) {
  225. int i, j, ret = 0;
  226. BIGNUM *a, *b, *d, *r;
  227. BN_CTX_start(ctx);
  228. a = BN_CTX_get(ctx);
  229. b = BN_CTX_get(ctx);
  230. if (dv != NULL) {
  231. d = dv;
  232. } else {
  233. d = BN_CTX_get(ctx);
  234. }
  235. if (rem != NULL) {
  236. r = rem;
  237. } else {
  238. r = BN_CTX_get(ctx);
  239. }
  240. if (a == NULL || b == NULL || d == NULL || r == NULL) {
  241. goto err;
  242. }
  243. if (BN_ucmp(m, &(recp->N)) < 0) {
  244. BN_zero(d);
  245. if (!BN_copy(r, m)) {
  246. return 0;
  247. }
  248. BN_CTX_end(ctx);
  249. return 1;
  250. }
  251. /* We want the remainder
  252. * Given input of ABCDEF / ab
  253. * we need multiply ABCDEF by 3 digests of the reciprocal of ab */
  254. /* i := max(BN_num_bits(m), 2*BN_num_bits(N)) */
  255. i = BN_num_bits(m);
  256. j = recp->num_bits << 1;
  257. if (j > i) {
  258. i = j;
  259. }
  260. /* Nr := round(2^i / N) */
  261. if (i != recp->shift) {
  262. recp->shift =
  263. BN_reciprocal(&(recp->Nr), &(recp->N), i,
  264. ctx); /* BN_reciprocal returns i, or -1 for an error */
  265. }
  266. if (recp->shift == -1) {
  267. goto err;
  268. }
  269. /* d := |round(round(m / 2^BN_num_bits(N)) * recp->Nr / 2^(i -
  270. * BN_num_bits(N)))|
  271. * = |round(round(m / 2^BN_num_bits(N)) * round(2^i / N) / 2^(i -
  272. * BN_num_bits(N)))|
  273. * <= |(m / 2^BN_num_bits(N)) * (2^i / N) * (2^BN_num_bits(N) / 2^i)|
  274. * = |m/N| */
  275. if (!BN_rshift(a, m, recp->num_bits)) {
  276. goto err;
  277. }
  278. if (!BN_mul(b, a, &(recp->Nr), ctx)) {
  279. goto err;
  280. }
  281. if (!BN_rshift(d, b, i - recp->num_bits)) {
  282. goto err;
  283. }
  284. d->neg = 0;
  285. if (!BN_mul(b, &(recp->N), d, ctx)) {
  286. goto err;
  287. }
  288. if (!BN_usub(r, m, b)) {
  289. goto err;
  290. }
  291. r->neg = 0;
  292. j = 0;
  293. while (BN_ucmp(r, &(recp->N)) >= 0) {
  294. if (j++ > 2) {
  295. OPENSSL_PUT_ERROR(BN, BN_div_recp, BN_R_BAD_RECIPROCAL);
  296. goto err;
  297. }
  298. if (!BN_usub(r, r, &(recp->N))) {
  299. goto err;
  300. }
  301. if (!BN_add_word(d, 1)) {
  302. goto err;
  303. }
  304. }
  305. r->neg = BN_is_zero(r) ? 0 : m->neg;
  306. d->neg = m->neg ^ recp->N.neg;
  307. ret = 1;
  308. err:
  309. BN_CTX_end(ctx);
  310. return ret;
  311. }
  312. static int BN_mod_mul_reciprocal(BIGNUM *r, const BIGNUM *x, const BIGNUM *y,
  313. BN_RECP_CTX *recp, BN_CTX *ctx) {
  314. int ret = 0;
  315. BIGNUM *a;
  316. const BIGNUM *ca;
  317. BN_CTX_start(ctx);
  318. a = BN_CTX_get(ctx);
  319. if (a == NULL) {
  320. goto err;
  321. }
  322. if (y != NULL) {
  323. if (x == y) {
  324. if (!BN_sqr(a, x, ctx)) {
  325. goto err;
  326. }
  327. } else {
  328. if (!BN_mul(a, x, y, ctx)) {
  329. goto err;
  330. }
  331. }
  332. ca = a;
  333. } else {
  334. ca = x; /* Just do the mod */
  335. }
  336. ret = BN_div_recp(NULL, r, ca, recp, ctx);
  337. err:
  338. BN_CTX_end(ctx);
  339. return ret;
  340. }
  341. /* BN_window_bits_for_exponent_size -- macro for sliding window mod_exp
  342. * functions
  343. *
  344. * For window size 'w' (w >= 2) and a random 'b' bits exponent, the number of
  345. * multiplications is a constant plus on average
  346. *
  347. * 2^(w-1) + (b-w)/(w+1);
  348. *
  349. * here 2^(w-1) is for precomputing the table (we actually need entries only
  350. * for windows that have the lowest bit set), and (b-w)/(w+1) is an
  351. * approximation for the expected number of w-bit windows, not counting the
  352. * first one.
  353. *
  354. * Thus we should use
  355. *
  356. * w >= 6 if b > 671
  357. * w = 5 if 671 > b > 239
  358. * w = 4 if 239 > b > 79
  359. * w = 3 if 79 > b > 23
  360. * w <= 2 if 23 > b
  361. *
  362. * (with draws in between). Very small exponents are often selected
  363. * with low Hamming weight, so we use w = 1 for b <= 23. */
  364. #define BN_window_bits_for_exponent_size(b) \
  365. ((b) > 671 ? 6 : \
  366. (b) > 239 ? 5 : \
  367. (b) > 79 ? 4 : \
  368. (b) > 23 ? 3 : 1)
  369. static int mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
  370. const BIGNUM *m, BN_CTX *ctx) {
  371. int i, j, bits, ret = 0, wstart, window;
  372. int start = 1;
  373. BIGNUM *aa;
  374. /* Table of variables obtained from 'ctx' */
  375. BIGNUM *val[TABLE_SIZE];
  376. BN_RECP_CTX recp;
  377. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
  378. /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
  379. OPENSSL_PUT_ERROR(BN, mod_exp_recp, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  380. return 0;
  381. }
  382. bits = BN_num_bits(p);
  383. if (bits == 0) {
  384. ret = BN_one(r);
  385. return ret;
  386. }
  387. BN_CTX_start(ctx);
  388. aa = BN_CTX_get(ctx);
  389. val[0] = BN_CTX_get(ctx);
  390. if (!aa || !val[0]) {
  391. goto err;
  392. }
  393. BN_RECP_CTX_init(&recp);
  394. if (m->neg) {
  395. /* ignore sign of 'm' */
  396. if (!BN_copy(aa, m)) {
  397. goto err;
  398. }
  399. aa->neg = 0;
  400. if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0) {
  401. goto err;
  402. }
  403. } else {
  404. if (BN_RECP_CTX_set(&recp, m, ctx) <= 0) {
  405. goto err;
  406. }
  407. }
  408. if (!BN_nnmod(val[0], a, m, ctx)) {
  409. goto err; /* 1 */
  410. }
  411. if (BN_is_zero(val[0])) {
  412. BN_zero(r);
  413. ret = 1;
  414. goto err;
  415. }
  416. window = BN_window_bits_for_exponent_size(bits);
  417. if (window > 1) {
  418. if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx)) {
  419. goto err; /* 2 */
  420. }
  421. j = 1 << (window - 1);
  422. for (i = 1; i < j; i++) {
  423. if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
  424. !BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx)) {
  425. goto err;
  426. }
  427. }
  428. }
  429. start = 1; /* This is used to avoid multiplication etc
  430. * when there is only the value '1' in the
  431. * buffer. */
  432. wstart = bits - 1; /* The top bit of the window */
  433. if (!BN_one(r)) {
  434. goto err;
  435. }
  436. for (;;) {
  437. int wvalue; /* The 'value' of the window */
  438. int wend; /* The bottom bit of the window */
  439. if (BN_is_bit_set(p, wstart) == 0) {
  440. if (!start) {
  441. if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx)) {
  442. goto err;
  443. }
  444. }
  445. if (wstart == 0) {
  446. break;
  447. }
  448. wstart--;
  449. continue;
  450. }
  451. /* We now have wstart on a 'set' bit, we now need to work out
  452. * how bit a window to do. To do this we need to scan
  453. * forward until the last set bit before the end of the
  454. * window */
  455. wvalue = 1;
  456. wend = 0;
  457. for (i = 1; i < window; i++) {
  458. if (wstart - i < 0) {
  459. break;
  460. }
  461. if (BN_is_bit_set(p, wstart - i)) {
  462. wvalue <<= (i - wend);
  463. wvalue |= 1;
  464. wend = i;
  465. }
  466. }
  467. /* wend is the size of the current window */
  468. j = wend + 1;
  469. /* add the 'bytes above' */
  470. if (!start) {
  471. for (i = 0; i < j; i++) {
  472. if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx)) {
  473. goto err;
  474. }
  475. }
  476. }
  477. /* wvalue will be an odd number < 2^window */
  478. if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx)) {
  479. goto err;
  480. }
  481. /* move the 'window' down further */
  482. wstart -= wend + 1;
  483. start = 0;
  484. if (wstart < 0) {
  485. break;
  486. }
  487. }
  488. ret = 1;
  489. err:
  490. BN_CTX_end(ctx);
  491. BN_RECP_CTX_free(&recp);
  492. return ret;
  493. }
  494. int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m,
  495. BN_CTX *ctx) {
  496. /* For even modulus m = 2^k*m_odd, it might make sense to compute
  497. * a^p mod m_odd and a^p mod 2^k separately (with Montgomery
  498. * exponentiation for the odd part), using appropriate exponent
  499. * reductions, and combine the results using the CRT.
  500. *
  501. * For now, we use Montgomery only if the modulus is odd; otherwise,
  502. * exponentiation using the reciprocal-based quick remaindering
  503. * algorithm is used.
  504. *
  505. * (Timing obtained with expspeed.c [computations a^p mod m
  506. * where a, p, m are of the same length: 256, 512, 1024, 2048,
  507. * 4096, 8192 bits], compared to the running time of the
  508. * standard algorithm:
  509. *
  510. * BN_mod_exp_mont 33 .. 40 % [AMD K6-2, Linux, debug configuration]
  511. * 55 .. 77 % [UltraSparc processor, but
  512. * debug-solaris-sparcv8-gcc conf.]
  513. *
  514. * BN_mod_exp_recp 50 .. 70 % [AMD K6-2, Linux, debug configuration]
  515. * 62 .. 118 % [UltraSparc, debug-solaris-sparcv8-gcc]
  516. *
  517. * On the Sparc, BN_mod_exp_recp was faster than BN_mod_exp_mont
  518. * at 2048 and more bits, but at 512 and 1024 bits, it was
  519. * slower even than the standard algorithm!
  520. *
  521. * "Real" timings [linux-elf, solaris-sparcv9-gcc configurations]
  522. * should be obtained when the new Montgomery reduction code
  523. * has been integrated into OpenSSL.) */
  524. if (BN_is_odd(m)) {
  525. if (a->top == 1 && !a->neg && BN_get_flags(p, BN_FLG_CONSTTIME) == 0) {
  526. BN_ULONG A = a->d[0];
  527. return BN_mod_exp_mont_word(r, A, p, m, ctx, NULL);
  528. }
  529. return BN_mod_exp_mont(r, a, p, m, ctx, NULL);
  530. }
  531. return mod_exp_recp(r, a, p, m, ctx);
  532. }
  533. int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
  534. const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont) {
  535. int i, j, bits, ret = 0, wstart, window;
  536. int start = 1;
  537. BIGNUM *d, *r;
  538. const BIGNUM *aa;
  539. /* Table of variables obtained from 'ctx' */
  540. BIGNUM *val[TABLE_SIZE];
  541. BN_MONT_CTX *mont = NULL;
  542. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
  543. return BN_mod_exp_mont_consttime(rr, a, p, m, ctx, in_mont);
  544. }
  545. if (!BN_is_odd(m)) {
  546. OPENSSL_PUT_ERROR(BN, BN_mod_exp_mont, BN_R_CALLED_WITH_EVEN_MODULUS);
  547. return 0;
  548. }
  549. bits = BN_num_bits(p);
  550. if (bits == 0) {
  551. ret = BN_one(rr);
  552. return ret;
  553. }
  554. BN_CTX_start(ctx);
  555. d = BN_CTX_get(ctx);
  556. r = BN_CTX_get(ctx);
  557. val[0] = BN_CTX_get(ctx);
  558. if (!d || !r || !val[0]) {
  559. goto err;
  560. }
  561. /* If this is not done, things will break in the montgomery part */
  562. if (in_mont != NULL) {
  563. mont = in_mont;
  564. } else {
  565. mont = BN_MONT_CTX_new();
  566. if (mont == NULL) {
  567. goto err;
  568. }
  569. if (!BN_MONT_CTX_set(mont, m, ctx)) {
  570. goto err;
  571. }
  572. }
  573. if (a->neg || BN_ucmp(a, m) >= 0) {
  574. if (!BN_nnmod(val[0], a, m, ctx)) {
  575. goto err;
  576. }
  577. aa = val[0];
  578. } else {
  579. aa = a;
  580. }
  581. if (BN_is_zero(aa)) {
  582. BN_zero(rr);
  583. ret = 1;
  584. goto err;
  585. }
  586. if (!BN_to_montgomery(val[0], aa, mont, ctx)) {
  587. goto err; /* 1 */
  588. }
  589. window = BN_window_bits_for_exponent_size(bits);
  590. if (window > 1) {
  591. if (!BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx)) {
  592. goto err; /* 2 */
  593. }
  594. j = 1 << (window - 1);
  595. for (i = 1; i < j; i++) {
  596. if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
  597. !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx)) {
  598. goto err;
  599. }
  600. }
  601. }
  602. start = 1; /* This is used to avoid multiplication etc
  603. * when there is only the value '1' in the
  604. * buffer. */
  605. wstart = bits - 1; /* The top bit of the window */
  606. j = m->top; /* borrow j */
  607. if (m->d[j - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
  608. if (bn_wexpand(r, j) == NULL) {
  609. goto err;
  610. }
  611. /* 2^(top*BN_BITS2) - m */
  612. r->d[0] = (0 - m->d[0]) & BN_MASK2;
  613. for (i = 1; i < j; i++) {
  614. r->d[i] = (~m->d[i]) & BN_MASK2;
  615. }
  616. r->top = j;
  617. /* Upper words will be zero if the corresponding words of 'm'
  618. * were 0xfff[...], so decrement r->top accordingly. */
  619. bn_correct_top(r);
  620. } else if (!BN_to_montgomery(r, BN_value_one(), mont, ctx)) {
  621. goto err;
  622. }
  623. for (;;) {
  624. int wvalue; /* The 'value' of the window */
  625. int wend; /* The bottom bit of the window */
  626. if (BN_is_bit_set(p, wstart) == 0) {
  627. if (!start && !BN_mod_mul_montgomery(r, r, r, mont, ctx)) {
  628. goto err;
  629. }
  630. if (wstart == 0) {
  631. break;
  632. }
  633. wstart--;
  634. continue;
  635. }
  636. /* We now have wstart on a 'set' bit, we now need to work out how bit a
  637. * window to do. To do this we need to scan forward until the last set bit
  638. * before the end of the window */
  639. wvalue = 1;
  640. wend = 0;
  641. for (i = 1; i < window; i++) {
  642. if (wstart - i < 0) {
  643. break;
  644. }
  645. if (BN_is_bit_set(p, wstart - i)) {
  646. wvalue <<= (i - wend);
  647. wvalue |= 1;
  648. wend = i;
  649. }
  650. }
  651. /* wend is the size of the current window */
  652. j = wend + 1;
  653. /* add the 'bytes above' */
  654. if (!start) {
  655. for (i = 0; i < j; i++) {
  656. if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) {
  657. goto err;
  658. }
  659. }
  660. }
  661. /* wvalue will be an odd number < 2^window */
  662. if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx)) {
  663. goto err;
  664. }
  665. /* move the 'window' down further */
  666. wstart -= wend + 1;
  667. start = 0;
  668. if (wstart < 0) {
  669. break;
  670. }
  671. }
  672. if (!BN_from_montgomery(rr, r, mont, ctx)) {
  673. goto err;
  674. }
  675. ret = 1;
  676. err:
  677. if (in_mont == NULL) {
  678. BN_MONT_CTX_free(mont);
  679. }
  680. BN_CTX_end(ctx);
  681. return ret;
  682. }
  683. /* BN_mod_exp_mont_consttime() stores the precomputed powers in a specific
  684. * layout so that accessing any of these table values shows the same access
  685. * pattern as far as cache lines are concerned. The following functions are
  686. * used to transfer a BIGNUM from/to that table. */
  687. static int copy_to_prebuf(const BIGNUM *b, int top, unsigned char *buf, int idx,
  688. int width) {
  689. size_t i, j;
  690. if (top > b->top) {
  691. top = b->top; /* this works because 'buf' is explicitly zeroed */
  692. }
  693. for (i = 0, j = idx; i < top * sizeof b->d[0]; i++, j += width) {
  694. buf[j] = ((unsigned char *)b->d)[i];
  695. }
  696. return 1;
  697. }
  698. static int copy_from_prebuf(BIGNUM *b, int top, unsigned char *buf, int idx,
  699. int width) {
  700. size_t i, j;
  701. if (bn_wexpand(b, top) == NULL) {
  702. return 0;
  703. }
  704. for (i = 0, j = idx; i < top * sizeof b->d[0]; i++, j += width) {
  705. ((unsigned char *)b->d)[i] = buf[j];
  706. }
  707. b->top = top;
  708. bn_correct_top(b);
  709. return 1;
  710. }
  711. /* BN_mod_exp_mont_conttime is based on the assumption that the L1 data cache
  712. * line width of the target processor is at least the following value. */
  713. #define MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH (64)
  714. #define MOD_EXP_CTIME_MIN_CACHE_LINE_MASK \
  715. (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - 1)
  716. /* Window sizes optimized for fixed window size modular exponentiation
  717. * algorithm (BN_mod_exp_mont_consttime).
  718. *
  719. * To achieve the security goals of BN_mode_exp_mont_consttime, the maximum
  720. * size of the window must not exceed
  721. * log_2(MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH).
  722. *
  723. * Window size thresholds are defined for cache line sizes of 32 and 64, cache
  724. * line sizes where log_2(32)=5 and log_2(64)=6 respectively. A window size of
  725. * 7 should only be used on processors that have a 128 byte or greater cache
  726. * line size. */
  727. #if MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH == 64
  728. #define BN_window_bits_for_ctime_exponent_size(b) \
  729. ((b) > 937 ? 6 : (b) > 306 ? 5 : (b) > 89 ? 4 : (b) > 22 ? 3 : 1)
  730. #define BN_MAX_WINDOW_BITS_FOR_CTIME_EXPONENT_SIZE (6)
  731. #elif MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH == 32
  732. #define BN_window_bits_for_ctime_exponent_size(b) \
  733. ((b) > 306 ? 5 : (b) > 89 ? 4 : (b) > 22 ? 3 : 1)
  734. #define BN_MAX_WINDOW_BITS_FOR_CTIME_EXPONENT_SIZE (5)
  735. #endif
  736. /* Given a pointer value, compute the next address that is a cache line
  737. * multiple. */
  738. #define MOD_EXP_CTIME_ALIGN(x_) \
  739. ((unsigned char *)(x_) + \
  740. (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - \
  741. (((size_t)(x_)) & (MOD_EXP_CTIME_MIN_CACHE_LINE_MASK))))
  742. /* This variant of BN_mod_exp_mont() uses fixed windows and the special
  743. * precomputation memory layout to limit data-dependency to a minimum
  744. * to protect secret exponents (cf. the hyper-threading timing attacks
  745. * pointed out by Colin Percival,
  746. * http://www.daemonology.net/hyperthreading-considered-harmful/)
  747. */
  748. int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
  749. const BIGNUM *m, BN_CTX *ctx,
  750. BN_MONT_CTX *in_mont) {
  751. int i, bits, ret = 0, window, wvalue;
  752. int top;
  753. BN_MONT_CTX *mont = NULL;
  754. int numPowers;
  755. unsigned char *powerbufFree = NULL;
  756. int powerbufLen = 0;
  757. unsigned char *powerbuf = NULL;
  758. BIGNUM tmp, am;
  759. top = m->top;
  760. if (!(m->d[0] & 1)) {
  761. OPENSSL_PUT_ERROR(BN, BN_mod_exp_mont_consttime,
  762. BN_R_CALLED_WITH_EVEN_MODULUS);
  763. return 0;
  764. }
  765. bits = BN_num_bits(p);
  766. if (bits == 0) {
  767. ret = BN_one(rr);
  768. return ret;
  769. }
  770. BN_CTX_start(ctx);
  771. /* Allocate a montgomery context if it was not supplied by the caller.
  772. * If this is not done, things will break in the montgomery part. */
  773. if (in_mont != NULL) {
  774. mont = in_mont;
  775. } else {
  776. mont = BN_MONT_CTX_new();
  777. if (mont == NULL || !BN_MONT_CTX_set(mont, m, ctx)) {
  778. goto err;
  779. }
  780. }
  781. #ifdef RSAZ_ENABLED
  782. /* If the size of the operands allow it, perform the optimized
  783. * RSAZ exponentiation. For further information see
  784. * crypto/bn/rsaz_exp.c and accompanying assembly modules. */
  785. if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024) &&
  786. rsaz_avx2_eligible()) {
  787. if (NULL == bn_wexpand(rr, 16)) {
  788. goto err;
  789. }
  790. RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d, mont->n0[0]);
  791. rr->top = 16;
  792. rr->neg = 0;
  793. bn_correct_top(rr);
  794. ret = 1;
  795. goto err;
  796. } else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) {
  797. if (NULL == bn_wexpand(rr, 8)) {
  798. goto err;
  799. }
  800. RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d);
  801. rr->top = 8;
  802. rr->neg = 0;
  803. bn_correct_top(rr);
  804. ret = 1;
  805. goto err;
  806. }
  807. #endif
  808. /* Get the window size to use with size of p. */
  809. window = BN_window_bits_for_ctime_exponent_size(bits);
  810. #if defined(OPENSSL_BN_ASM_MONT5)
  811. if (window >= 5) {
  812. window = 5; /* ~5% improvement for RSA2048 sign, and even for RSA4096 */
  813. if ((top & 7) == 0) {
  814. powerbufLen += 2 * top * sizeof(m->d[0]);
  815. }
  816. }
  817. #endif
  818. (void)0;
  819. /* Allocate a buffer large enough to hold all of the pre-computed
  820. * powers of am, am itself and tmp.
  821. */
  822. numPowers = 1 << window;
  823. powerbufLen +=
  824. sizeof(m->d[0]) *
  825. (top * numPowers + ((2 * top) > numPowers ? (2 * top) : numPowers));
  826. #ifdef alloca
  827. if (powerbufLen < 3072) {
  828. powerbufFree = alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH);
  829. } else
  830. #endif
  831. {
  832. if ((powerbufFree = (unsigned char *)OPENSSL_malloc(
  833. powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH)) == NULL) {
  834. goto err;
  835. }
  836. }
  837. powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree);
  838. memset(powerbuf, 0, powerbufLen);
  839. #ifdef alloca
  840. if (powerbufLen < 3072) {
  841. powerbufFree = NULL;
  842. }
  843. #endif
  844. /* lay down tmp and am right after powers table */
  845. tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers);
  846. am.d = tmp.d + top;
  847. tmp.top = am.top = 0;
  848. tmp.dmax = am.dmax = top;
  849. tmp.neg = am.neg = 0;
  850. tmp.flags = am.flags = BN_FLG_STATIC_DATA;
  851. /* prepare a^0 in Montgomery domain */
  852. /* by Shay Gueron's suggestion */
  853. if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
  854. /* 2^(top*BN_BITS2) - m */
  855. tmp.d[0] = (0 - m->d[0]) & BN_MASK2;
  856. for (i = 1; i < top; i++) {
  857. tmp.d[i] = (~m->d[i]) & BN_MASK2;
  858. }
  859. tmp.top = top;
  860. } else if (!BN_to_montgomery(&tmp, BN_value_one(), mont, ctx)) {
  861. goto err;
  862. }
  863. /* prepare a^1 in Montgomery domain */
  864. if (a->neg || BN_ucmp(a, m) >= 0) {
  865. if (!BN_mod(&am, a, m, ctx) ||
  866. !BN_to_montgomery(&am, &am, mont, ctx)) {
  867. goto err;
  868. }
  869. } else if (!BN_to_montgomery(&am, a, mont, ctx)) {
  870. goto err;
  871. }
  872. #if defined(OPENSSL_BN_ASM_MONT5)
  873. /* This optimization uses ideas from http://eprint.iacr.org/2011/239,
  874. * specifically optimization of cache-timing attack countermeasures
  875. * and pre-computation optimization. */
  876. /* Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as
  877. * 512-bit RSA is hardly relevant, we omit it to spare size... */
  878. if (window == 5 && top > 1) {
  879. void bn_mul_mont_gather5(BN_ULONG * rp, const BN_ULONG * ap,
  880. const void * table, const BN_ULONG * np,
  881. const BN_ULONG * n0, int num, int power);
  882. void bn_scatter5(const BN_ULONG * inp, size_t num, void * table,
  883. size_t power);
  884. void bn_gather5(BN_ULONG * out, size_t num, void * table, size_t power);
  885. void bn_power5(BN_ULONG * rp, const BN_ULONG * ap, const void * table,
  886. const BN_ULONG * np, const BN_ULONG * n0, int num,
  887. int power);
  888. int bn_from_montgomery(BN_ULONG * rp, const BN_ULONG * ap,
  889. const BN_ULONG * not_used, const BN_ULONG * np,
  890. const BN_ULONG * n0, int num);
  891. BN_ULONG *np = mont->N.d, *n0 = mont->n0, *np2;
  892. /* BN_to_montgomery can contaminate words above .top
  893. * [in BN_DEBUG[_DEBUG] build]... */
  894. for (i = am.top; i < top; i++) {
  895. am.d[i] = 0;
  896. }
  897. for (i = tmp.top; i < top; i++) {
  898. tmp.d[i] = 0;
  899. }
  900. if (top & 7) {
  901. np2 = np;
  902. } else {
  903. for (np2 = am.d + top, i = 0; i < top; i++) {
  904. np2[2 * i] = np[i];
  905. }
  906. }
  907. bn_scatter5(tmp.d, top, powerbuf, 0);
  908. bn_scatter5(am.d, am.top, powerbuf, 1);
  909. bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);
  910. bn_scatter5(tmp.d, top, powerbuf, 2);
  911. /* same as above, but uses squaring for 1/2 of operations */
  912. for (i = 4; i < 32; i *= 2) {
  913. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  914. bn_scatter5(tmp.d, top, powerbuf, i);
  915. }
  916. for (i = 3; i < 8; i += 2) {
  917. int j;
  918. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np2, n0, top, i - 1);
  919. bn_scatter5(tmp.d, top, powerbuf, i);
  920. for (j = 2 * i; j < 32; j *= 2) {
  921. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  922. bn_scatter5(tmp.d, top, powerbuf, j);
  923. }
  924. }
  925. for (; i < 16; i += 2) {
  926. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np2, n0, top, i - 1);
  927. bn_scatter5(tmp.d, top, powerbuf, i);
  928. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  929. bn_scatter5(tmp.d, top, powerbuf, 2 * i);
  930. }
  931. for (; i < 32; i += 2) {
  932. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np2, n0, top, i - 1);
  933. bn_scatter5(tmp.d, top, powerbuf, i);
  934. }
  935. bits--;
  936. for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--) {
  937. wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
  938. }
  939. bn_gather5(tmp.d, top, powerbuf, wvalue);
  940. /* At this point |bits| is 4 mod 5 and at least -1. (|bits| is the first bit
  941. * that has not been read yet.) */
  942. assert(bits >= -1 && (bits == -1 || bits % 5 == 4));
  943. /* Scan the exponent one window at a time starting from the most
  944. * significant bits.
  945. */
  946. if (top & 7) {
  947. while (bits >= 0) {
  948. for (wvalue = 0, i = 0; i < 5; i++, bits--) {
  949. wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
  950. }
  951. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  952. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  953. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  954. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  955. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  956. bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue);
  957. }
  958. } else {
  959. const uint8_t *p_bytes = (const uint8_t *)p->d;
  960. int max_bits = p->top * BN_BITS2;
  961. assert(bits < max_bits);
  962. /* |p = 0| has been handled as a special case, so |max_bits| is at least
  963. * one word. */
  964. assert(max_bits >= 64);
  965. /* If the first bit to be read lands in the last byte, unroll the first
  966. * iteration to avoid reading past the bounds of |p->d|. (After the first
  967. * iteration, we are guaranteed to be past the last byte.) Note |bits|
  968. * here is the top bit, inclusive. */
  969. if (bits - 4 >= max_bits - 8) {
  970. /* Read five bits from |bits-4| through |bits|, inclusive. */
  971. wvalue = p_bytes[p->top * BN_BYTES - 1];
  972. wvalue >>= (bits - 4) & 7;
  973. wvalue &= 0x1f;
  974. bits -= 5;
  975. bn_power5(tmp.d, tmp.d, powerbuf, np2, n0, top, wvalue);
  976. }
  977. while (bits >= 0) {
  978. /* Read five bits from |bits-4| through |bits|, inclusive. */
  979. int first_bit = bits - 4;
  980. wvalue = *(const uint16_t *) (p_bytes + (first_bit >> 3));
  981. wvalue >>= first_bit & 7;
  982. wvalue &= 0x1f;
  983. bits -= 5;
  984. bn_power5(tmp.d, tmp.d, powerbuf, np2, n0, top, wvalue);
  985. }
  986. }
  987. ret = bn_from_montgomery(tmp.d, tmp.d, NULL, np2, n0, top);
  988. tmp.top = top;
  989. bn_correct_top(&tmp);
  990. if (ret) {
  991. if (!BN_copy(rr, &tmp)) {
  992. ret = 0;
  993. }
  994. goto err; /* non-zero ret means it's not error */
  995. }
  996. } else
  997. #endif
  998. {
  999. if (!copy_to_prebuf(&tmp, top, powerbuf, 0, numPowers) ||
  1000. !copy_to_prebuf(&am, top, powerbuf, 1, numPowers)) {
  1001. goto err;
  1002. }
  1003. /* If the window size is greater than 1, then calculate
  1004. * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1)
  1005. * (even powers could instead be computed as (a^(i/2))^2
  1006. * to use the slight performance advantage of sqr over mul).
  1007. */
  1008. if (window > 1) {
  1009. if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx) ||
  1010. !copy_to_prebuf(&tmp, top, powerbuf, 2, numPowers)) {
  1011. goto err;
  1012. }
  1013. for (i = 3; i < numPowers; i++) {
  1014. /* Calculate a^i = a^(i-1) * a */
  1015. if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx) ||
  1016. !copy_to_prebuf(&tmp, top, powerbuf, i, numPowers)) {
  1017. goto err;
  1018. }
  1019. }
  1020. }
  1021. bits--;
  1022. for (wvalue = 0, i = bits % window; i >= 0; i--, bits--) {
  1023. wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
  1024. }
  1025. if (!copy_from_prebuf(&tmp, top, powerbuf, wvalue, numPowers)) {
  1026. goto err;
  1027. }
  1028. /* Scan the exponent one window at a time starting from the most
  1029. * significant bits.
  1030. */
  1031. while (bits >= 0) {
  1032. wvalue = 0; /* The 'value' of the window */
  1033. /* Scan the window, squaring the result as we go */
  1034. for (i = 0; i < window; i++, bits--) {
  1035. if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx)) {
  1036. goto err;
  1037. }
  1038. wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
  1039. }
  1040. /* Fetch the appropriate pre-computed value from the pre-buf */
  1041. if (!copy_from_prebuf(&am, top, powerbuf, wvalue, numPowers)) {
  1042. goto err;
  1043. }
  1044. /* Multiply the result into the intermediate result */
  1045. if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx)) {
  1046. goto err;
  1047. }
  1048. }
  1049. }
  1050. /* Convert the final result from montgomery to standard format */
  1051. if (!BN_from_montgomery(rr, &tmp, mont, ctx)) {
  1052. goto err;
  1053. }
  1054. ret = 1;
  1055. err:
  1056. if (in_mont == NULL) {
  1057. BN_MONT_CTX_free(mont);
  1058. }
  1059. if (powerbuf != NULL) {
  1060. OPENSSL_cleanse(powerbuf, powerbufLen);
  1061. OPENSSL_free(powerbufFree);
  1062. }
  1063. BN_CTX_end(ctx);
  1064. return (ret);
  1065. }
  1066. int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
  1067. const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont) {
  1068. BN_MONT_CTX *mont = NULL;
  1069. int b, bits, ret = 0;
  1070. int r_is_one;
  1071. BN_ULONG w, next_w;
  1072. BIGNUM *d, *r, *t;
  1073. BIGNUM *swap_tmp;
  1074. #define BN_MOD_MUL_WORD(r, w, m) \
  1075. (BN_mul_word(r, (w)) && \
  1076. (/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \
  1077. (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1))))
  1078. /* BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is
  1079. * probably more overhead than always using BN_mod (which uses BN_copy if a
  1080. * similar test returns true). We can use BN_mod and do not need BN_nnmod
  1081. * because our accumulator is never negative (the result of BN_mod does not
  1082. * depend on the sign of the modulus). */
  1083. #define BN_TO_MONTGOMERY_WORD(r, w, mont) \
  1084. (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx))
  1085. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
  1086. /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
  1087. OPENSSL_PUT_ERROR(BN, BN_mod_exp_mont_word,
  1088. ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  1089. return 0;
  1090. }
  1091. if (!BN_is_odd(m)) {
  1092. OPENSSL_PUT_ERROR(BN, BN_mod_exp_mont_word, BN_R_CALLED_WITH_EVEN_MODULUS);
  1093. return 0;
  1094. }
  1095. if (m->top == 1) {
  1096. a %= m->d[0]; /* make sure that 'a' is reduced */
  1097. }
  1098. bits = BN_num_bits(p);
  1099. if (bits == 0) {
  1100. /* x**0 mod 1 is still zero. */
  1101. if (BN_is_one(m)) {
  1102. ret = 1;
  1103. BN_zero(rr);
  1104. } else {
  1105. ret = BN_one(rr);
  1106. }
  1107. return ret;
  1108. }
  1109. if (a == 0) {
  1110. BN_zero(rr);
  1111. ret = 1;
  1112. return ret;
  1113. }
  1114. BN_CTX_start(ctx);
  1115. d = BN_CTX_get(ctx);
  1116. r = BN_CTX_get(ctx);
  1117. t = BN_CTX_get(ctx);
  1118. if (d == NULL || r == NULL || t == NULL) {
  1119. goto err;
  1120. }
  1121. if (in_mont != NULL) {
  1122. mont = in_mont;
  1123. } else {
  1124. mont = BN_MONT_CTX_new();
  1125. if (mont == NULL || !BN_MONT_CTX_set(mont, m, ctx)) {
  1126. goto err;
  1127. }
  1128. }
  1129. r_is_one = 1; /* except for Montgomery factor */
  1130. /* bits-1 >= 0 */
  1131. /* The result is accumulated in the product r*w. */
  1132. w = a; /* bit 'bits-1' of 'p' is always set */
  1133. for (b = bits - 2; b >= 0; b--) {
  1134. /* First, square r*w. */
  1135. next_w = w * w;
  1136. if ((next_w / w) != w) {
  1137. /* overflow */
  1138. if (r_is_one) {
  1139. if (!BN_TO_MONTGOMERY_WORD(r, w, mont)) {
  1140. goto err;
  1141. }
  1142. r_is_one = 0;
  1143. } else {
  1144. if (!BN_MOD_MUL_WORD(r, w, m)) {
  1145. goto err;
  1146. }
  1147. }
  1148. next_w = 1;
  1149. }
  1150. w = next_w;
  1151. if (!r_is_one) {
  1152. if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) {
  1153. goto err;
  1154. }
  1155. }
  1156. /* Second, multiply r*w by 'a' if exponent bit is set. */
  1157. if (BN_is_bit_set(p, b)) {
  1158. next_w = w * a;
  1159. if ((next_w / a) != w) {
  1160. /* overflow */
  1161. if (r_is_one) {
  1162. if (!BN_TO_MONTGOMERY_WORD(r, w, mont)) {
  1163. goto err;
  1164. }
  1165. r_is_one = 0;
  1166. } else {
  1167. if (!BN_MOD_MUL_WORD(r, w, m)) {
  1168. goto err;
  1169. }
  1170. }
  1171. next_w = a;
  1172. }
  1173. w = next_w;
  1174. }
  1175. }
  1176. /* Finally, set r:=r*w. */
  1177. if (w != 1) {
  1178. if (r_is_one) {
  1179. if (!BN_TO_MONTGOMERY_WORD(r, w, mont)) {
  1180. goto err;
  1181. }
  1182. r_is_one = 0;
  1183. } else {
  1184. if (!BN_MOD_MUL_WORD(r, w, m)) {
  1185. goto err;
  1186. }
  1187. }
  1188. }
  1189. if (r_is_one) {
  1190. /* can happen only if a == 1*/
  1191. if (!BN_one(rr)) {
  1192. goto err;
  1193. }
  1194. } else {
  1195. if (!BN_from_montgomery(rr, r, mont, ctx)) {
  1196. goto err;
  1197. }
  1198. }
  1199. ret = 1;
  1200. err:
  1201. if (in_mont == NULL) {
  1202. BN_MONT_CTX_free(mont);
  1203. }
  1204. BN_CTX_end(ctx);
  1205. return ret;
  1206. }
  1207. #define TABLE_SIZE 32
  1208. int BN_mod_exp2_mont(BIGNUM *rr, const BIGNUM *a1, const BIGNUM *p1,
  1209. const BIGNUM *a2, const BIGNUM *p2, const BIGNUM *m,
  1210. BN_CTX *ctx, BN_MONT_CTX *in_mont) {
  1211. int i, j, bits, b, bits1, bits2, ret = 0, wpos1, wpos2, window1, window2,
  1212. wvalue1, wvalue2;
  1213. int r_is_one = 1;
  1214. BIGNUM *d, *r;
  1215. const BIGNUM *a_mod_m;
  1216. /* Tables of variables obtained from 'ctx' */
  1217. BIGNUM *val1[TABLE_SIZE], *val2[TABLE_SIZE];
  1218. BN_MONT_CTX *mont = NULL;
  1219. if (!(m->d[0] & 1)) {
  1220. OPENSSL_PUT_ERROR(BN, BN_mod_exp2_mont, BN_R_CALLED_WITH_EVEN_MODULUS);
  1221. return 0;
  1222. }
  1223. bits1 = BN_num_bits(p1);
  1224. bits2 = BN_num_bits(p2);
  1225. if (bits1 == 0 && bits2 == 0) {
  1226. ret = BN_one(rr);
  1227. return ret;
  1228. }
  1229. bits = (bits1 > bits2) ? bits1 : bits2;
  1230. BN_CTX_start(ctx);
  1231. d = BN_CTX_get(ctx);
  1232. r = BN_CTX_get(ctx);
  1233. val1[0] = BN_CTX_get(ctx);
  1234. val2[0] = BN_CTX_get(ctx);
  1235. if (!d || !r || !val1[0] || !val2[0]) {
  1236. goto err;
  1237. }
  1238. if (in_mont != NULL) {
  1239. mont = in_mont;
  1240. } else {
  1241. mont = BN_MONT_CTX_new();
  1242. if (mont == NULL) {
  1243. goto err;
  1244. }
  1245. if (!BN_MONT_CTX_set(mont, m, ctx)) {
  1246. goto err;
  1247. }
  1248. }
  1249. window1 = BN_window_bits_for_exponent_size(bits1);
  1250. window2 = BN_window_bits_for_exponent_size(bits2);
  1251. /* Build table for a1: val1[i] := a1^(2*i + 1) mod m for i = 0 ..
  1252. * 2^(window1-1) */
  1253. if (a1->neg || BN_ucmp(a1, m) >= 0) {
  1254. if (!BN_mod(val1[0], a1, m, ctx)) {
  1255. goto err;
  1256. }
  1257. a_mod_m = val1[0];
  1258. } else {
  1259. a_mod_m = a1;
  1260. }
  1261. if (BN_is_zero(a_mod_m)) {
  1262. BN_zero(rr);
  1263. ret = 1;
  1264. goto err;
  1265. }
  1266. if (!BN_to_montgomery(val1[0], a_mod_m, mont, ctx)) {
  1267. goto err;
  1268. }
  1269. if (window1 > 1) {
  1270. if (!BN_mod_mul_montgomery(d, val1[0], val1[0], mont, ctx)) {
  1271. goto err;
  1272. }
  1273. j = 1 << (window1 - 1);
  1274. for (i = 1; i < j; i++) {
  1275. if (((val1[i] = BN_CTX_get(ctx)) == NULL) ||
  1276. !BN_mod_mul_montgomery(val1[i], val1[i - 1], d, mont, ctx)) {
  1277. goto err;
  1278. }
  1279. }
  1280. }
  1281. /* Build table for a2: val2[i] := a2^(2*i + 1) mod m for i = 0 ..
  1282. * 2^(window2-1) */
  1283. if (a2->neg || BN_ucmp(a2, m) >= 0) {
  1284. if (!BN_mod(val2[0], a2, m, ctx)) {
  1285. goto err;
  1286. }
  1287. a_mod_m = val2[0];
  1288. } else {
  1289. a_mod_m = a2;
  1290. }
  1291. if (BN_is_zero(a_mod_m)) {
  1292. BN_zero(rr);
  1293. ret = 1;
  1294. goto err;
  1295. }
  1296. if (!BN_to_montgomery(val2[0], a_mod_m, mont, ctx)) {
  1297. goto err;
  1298. }
  1299. if (window2 > 1) {
  1300. if (!BN_mod_mul_montgomery(d, val2[0], val2[0], mont, ctx)) {
  1301. goto err;
  1302. }
  1303. j = 1 << (window2 - 1);
  1304. for (i = 1; i < j; i++) {
  1305. if (((val2[i] = BN_CTX_get(ctx)) == NULL) ||
  1306. !BN_mod_mul_montgomery(val2[i], val2[i - 1], d, mont, ctx)) {
  1307. goto err;
  1308. }
  1309. }
  1310. }
  1311. /* Now compute the power product, using independent windows. */
  1312. r_is_one = 1;
  1313. wvalue1 = 0; /* The 'value' of the first window */
  1314. wvalue2 = 0; /* The 'value' of the second window */
  1315. wpos1 = 0; /* If wvalue1 > 0, the bottom bit of the first window */
  1316. wpos2 = 0; /* If wvalue2 > 0, the bottom bit of the second window */
  1317. if (!BN_to_montgomery(r, BN_value_one(), mont, ctx)) {
  1318. goto err;
  1319. }
  1320. for (b = bits - 1; b >= 0; b--) {
  1321. if (!r_is_one) {
  1322. if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) {
  1323. goto err;
  1324. }
  1325. }
  1326. if (!wvalue1 && BN_is_bit_set(p1, b)) {
  1327. /* consider bits b-window1+1 .. b for this window */
  1328. i = b - window1 + 1;
  1329. /* works for i<0 */
  1330. while (!BN_is_bit_set(p1, i)) {
  1331. i++;
  1332. }
  1333. wpos1 = i;
  1334. wvalue1 = 1;
  1335. for (i = b - 1; i >= wpos1; i--) {
  1336. wvalue1 <<= 1;
  1337. if (BN_is_bit_set(p1, i)) {
  1338. wvalue1++;
  1339. }
  1340. }
  1341. }
  1342. if (!wvalue2 && BN_is_bit_set(p2, b)) {
  1343. /* consider bits b-window2+1 .. b for this window */
  1344. i = b - window2 + 1;
  1345. while (!BN_is_bit_set(p2, i)) {
  1346. i++;
  1347. }
  1348. wpos2 = i;
  1349. wvalue2 = 1;
  1350. for (i = b - 1; i >= wpos2; i--) {
  1351. wvalue2 <<= 1;
  1352. if (BN_is_bit_set(p2, i)) {
  1353. wvalue2++;
  1354. }
  1355. }
  1356. }
  1357. if (wvalue1 && b == wpos1) {
  1358. /* wvalue1 is odd and < 2^window1 */
  1359. if (!BN_mod_mul_montgomery(r, r, val1[wvalue1 >> 1], mont, ctx)) {
  1360. goto err;
  1361. }
  1362. wvalue1 = 0;
  1363. r_is_one = 0;
  1364. }
  1365. if (wvalue2 && b == wpos2) {
  1366. /* wvalue2 is odd and < 2^window2 */
  1367. if (!BN_mod_mul_montgomery(r, r, val2[wvalue2 >> 1], mont, ctx)) {
  1368. goto err;
  1369. }
  1370. wvalue2 = 0;
  1371. r_is_one = 0;
  1372. }
  1373. }
  1374. if (!BN_from_montgomery(rr, r, mont, ctx)) {
  1375. goto err;
  1376. }
  1377. ret = 1;
  1378. err:
  1379. if (in_mont == NULL) {
  1380. BN_MONT_CTX_free(mont);
  1381. }
  1382. BN_CTX_end(ctx);
  1383. return ret;
  1384. }