bn_exp.c 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  1. /* crypto/bn/bn_exp.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-2005 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. #include "cryptlib.h"
  112. #include "constant_time_locl.h"
  113. #include "bn_lcl.h"
  114. #include <stdlib.h>
  115. #ifdef _WIN32
  116. # include <malloc.h>
  117. # ifndef alloca
  118. # define alloca _alloca
  119. # endif
  120. #elif defined(__GNUC__)
  121. # ifndef alloca
  122. # define alloca(s) __builtin_alloca((s))
  123. # endif
  124. #elif defined(__sun)
  125. # include <alloca.h>
  126. #endif
  127. #include "rsaz_exp.h"
  128. #undef SPARC_T4_MONT
  129. #if defined(OPENSSL_BN_ASM_MONT) && (defined(__sparc__) || defined(__sparc))
  130. # include "sparc_arch.h"
  131. extern unsigned int OPENSSL_sparcv9cap_P[];
  132. # define SPARC_T4_MONT
  133. #endif
  134. /* maximum precomputation table size for *variable* sliding windows */
  135. #define TABLE_SIZE 32
  136. /* this one works - simple but works */
  137. int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
  138. {
  139. int i, bits, ret = 0;
  140. BIGNUM *v, *rr;
  141. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
  142. /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
  143. BNerr(BN_F_BN_EXP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  144. return -1;
  145. }
  146. BN_CTX_start(ctx);
  147. if ((r == a) || (r == p))
  148. rr = BN_CTX_get(ctx);
  149. else
  150. rr = r;
  151. v = BN_CTX_get(ctx);
  152. if (rr == NULL || v == NULL)
  153. goto err;
  154. if (BN_copy(v, a) == NULL)
  155. goto err;
  156. bits = BN_num_bits(p);
  157. if (BN_is_odd(p)) {
  158. if (BN_copy(rr, a) == NULL)
  159. goto err;
  160. } else {
  161. if (!BN_one(rr))
  162. goto err;
  163. }
  164. for (i = 1; i < bits; i++) {
  165. if (!BN_sqr(v, v, ctx))
  166. goto err;
  167. if (BN_is_bit_set(p, i)) {
  168. if (!BN_mul(rr, rr, v, ctx))
  169. goto err;
  170. }
  171. }
  172. if (r != rr && BN_copy(r, rr) == NULL)
  173. goto err;
  174. ret = 1;
  175. err:
  176. BN_CTX_end(ctx);
  177. bn_check_top(r);
  178. return (ret);
  179. }
  180. int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m,
  181. BN_CTX *ctx)
  182. {
  183. int ret;
  184. bn_check_top(a);
  185. bn_check_top(p);
  186. bn_check_top(m);
  187. /*-
  188. * For even modulus m = 2^k*m_odd, it might make sense to compute
  189. * a^p mod m_odd and a^p mod 2^k separately (with Montgomery
  190. * exponentiation for the odd part), using appropriate exponent
  191. * reductions, and combine the results using the CRT.
  192. *
  193. * For now, we use Montgomery only if the modulus is odd; otherwise,
  194. * exponentiation using the reciprocal-based quick remaindering
  195. * algorithm is used.
  196. *
  197. * (Timing obtained with expspeed.c [computations a^p mod m
  198. * where a, p, m are of the same length: 256, 512, 1024, 2048,
  199. * 4096, 8192 bits], compared to the running time of the
  200. * standard algorithm:
  201. *
  202. * BN_mod_exp_mont 33 .. 40 % [AMD K6-2, Linux, debug configuration]
  203. * 55 .. 77 % [UltraSparc processor, but
  204. * debug-solaris-sparcv8-gcc conf.]
  205. *
  206. * BN_mod_exp_recp 50 .. 70 % [AMD K6-2, Linux, debug configuration]
  207. * 62 .. 118 % [UltraSparc, debug-solaris-sparcv8-gcc]
  208. *
  209. * On the Sparc, BN_mod_exp_recp was faster than BN_mod_exp_mont
  210. * at 2048 and more bits, but at 512 and 1024 bits, it was
  211. * slower even than the standard algorithm!
  212. *
  213. * "Real" timings [linux-elf, solaris-sparcv9-gcc configurations]
  214. * should be obtained when the new Montgomery reduction code
  215. * has been integrated into OpenSSL.)
  216. */
  217. #define MONT_MUL_MOD
  218. #define MONT_EXP_WORD
  219. #define RECP_MUL_MOD
  220. #ifdef MONT_MUL_MOD
  221. /*
  222. * I have finally been able to take out this pre-condition of the top bit
  223. * being set. It was caused by an error in BN_div with negatives. There
  224. * was also another problem when for a^b%m a >= m. eay 07-May-97
  225. */
  226. /* if ((m->d[m->top-1]&BN_TBIT) && BN_is_odd(m)) */
  227. if (BN_is_odd(m)) {
  228. # ifdef MONT_EXP_WORD
  229. if (a->top == 1 && !a->neg
  230. && (BN_get_flags(p, BN_FLG_CONSTTIME) == 0)) {
  231. BN_ULONG A = a->d[0];
  232. ret = BN_mod_exp_mont_word(r, A, p, m, ctx, NULL);
  233. } else
  234. # endif
  235. ret = BN_mod_exp_mont(r, a, p, m, ctx, NULL);
  236. } else
  237. #endif
  238. #ifdef RECP_MUL_MOD
  239. {
  240. ret = BN_mod_exp_recp(r, a, p, m, ctx);
  241. }
  242. #else
  243. {
  244. ret = BN_mod_exp_simple(r, a, p, m, ctx);
  245. }
  246. #endif
  247. bn_check_top(r);
  248. return (ret);
  249. }
  250. int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
  251. const BIGNUM *m, BN_CTX *ctx)
  252. {
  253. int i, j, bits, ret = 0, wstart, wend, window, wvalue;
  254. int start = 1;
  255. BIGNUM *aa;
  256. /* Table of variables obtained from 'ctx' */
  257. BIGNUM *val[TABLE_SIZE];
  258. BN_RECP_CTX recp;
  259. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
  260. /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
  261. BNerr(BN_F_BN_MOD_EXP_RECP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  262. return -1;
  263. }
  264. bits = BN_num_bits(p);
  265. if (bits == 0) {
  266. /* x**0 mod 1 is still zero. */
  267. if (BN_is_one(m)) {
  268. ret = 1;
  269. BN_zero(r);
  270. } else {
  271. ret = BN_one(r);
  272. }
  273. return ret;
  274. }
  275. BN_CTX_start(ctx);
  276. aa = BN_CTX_get(ctx);
  277. val[0] = BN_CTX_get(ctx);
  278. if (!aa || !val[0])
  279. goto err;
  280. BN_RECP_CTX_init(&recp);
  281. if (m->neg) {
  282. /* ignore sign of 'm' */
  283. if (!BN_copy(aa, m))
  284. goto err;
  285. aa->neg = 0;
  286. if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0)
  287. goto err;
  288. } else {
  289. if (BN_RECP_CTX_set(&recp, m, ctx) <= 0)
  290. goto err;
  291. }
  292. if (!BN_nnmod(val[0], a, m, ctx))
  293. goto err; /* 1 */
  294. if (BN_is_zero(val[0])) {
  295. BN_zero(r);
  296. ret = 1;
  297. goto err;
  298. }
  299. window = BN_window_bits_for_exponent_size(bits);
  300. if (window > 1) {
  301. if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx))
  302. goto err; /* 2 */
  303. j = 1 << (window - 1);
  304. for (i = 1; i < j; i++) {
  305. if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
  306. !BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx))
  307. goto err;
  308. }
  309. }
  310. start = 1; /* This is used to avoid multiplication etc
  311. * when there is only the value '1' in the
  312. * buffer. */
  313. wvalue = 0; /* The 'value' of the window */
  314. wstart = bits - 1; /* The top bit of the window */
  315. wend = 0; /* The bottom bit of the window */
  316. if (!BN_one(r))
  317. goto err;
  318. for (;;) {
  319. if (BN_is_bit_set(p, wstart) == 0) {
  320. if (!start)
  321. if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
  322. goto err;
  323. if (wstart == 0)
  324. break;
  325. wstart--;
  326. continue;
  327. }
  328. /*
  329. * We now have wstart on a 'set' bit, we now need to work out how bit
  330. * a window to do. To do this we need to scan forward until the last
  331. * set bit before the end of the window
  332. */
  333. j = wstart;
  334. wvalue = 1;
  335. wend = 0;
  336. for (i = 1; i < window; i++) {
  337. if (wstart - i < 0)
  338. break;
  339. if (BN_is_bit_set(p, wstart - i)) {
  340. wvalue <<= (i - wend);
  341. wvalue |= 1;
  342. wend = i;
  343. }
  344. }
  345. /* wend is the size of the current window */
  346. j = wend + 1;
  347. /* add the 'bytes above' */
  348. if (!start)
  349. for (i = 0; i < j; i++) {
  350. if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
  351. goto err;
  352. }
  353. /* wvalue will be an odd number < 2^window */
  354. if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx))
  355. goto err;
  356. /* move the 'window' down further */
  357. wstart -= wend + 1;
  358. wvalue = 0;
  359. start = 0;
  360. if (wstart < 0)
  361. break;
  362. }
  363. ret = 1;
  364. err:
  365. BN_CTX_end(ctx);
  366. BN_RECP_CTX_free(&recp);
  367. bn_check_top(r);
  368. return (ret);
  369. }
  370. int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
  371. const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
  372. {
  373. int i, j, bits, ret = 0, wstart, wend, window, wvalue;
  374. int start = 1;
  375. BIGNUM *d, *r;
  376. const BIGNUM *aa;
  377. /* Table of variables obtained from 'ctx' */
  378. BIGNUM *val[TABLE_SIZE];
  379. BN_MONT_CTX *mont = NULL;
  380. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
  381. return BN_mod_exp_mont_consttime(rr, a, p, m, ctx, in_mont);
  382. }
  383. bn_check_top(a);
  384. bn_check_top(p);
  385. bn_check_top(m);
  386. if (!BN_is_odd(m)) {
  387. BNerr(BN_F_BN_MOD_EXP_MONT, BN_R_CALLED_WITH_EVEN_MODULUS);
  388. return (0);
  389. }
  390. bits = BN_num_bits(p);
  391. if (bits == 0) {
  392. /* x**0 mod 1 is still zero. */
  393. if (BN_is_one(m)) {
  394. ret = 1;
  395. BN_zero(rr);
  396. } else {
  397. ret = BN_one(rr);
  398. }
  399. return ret;
  400. }
  401. BN_CTX_start(ctx);
  402. d = BN_CTX_get(ctx);
  403. r = BN_CTX_get(ctx);
  404. val[0] = BN_CTX_get(ctx);
  405. if (!d || !r || !val[0])
  406. goto err;
  407. /*
  408. * If this is not done, things will break in the montgomery part
  409. */
  410. if (in_mont != NULL)
  411. mont = in_mont;
  412. else {
  413. if ((mont = BN_MONT_CTX_new()) == NULL)
  414. goto err;
  415. if (!BN_MONT_CTX_set(mont, m, ctx))
  416. goto err;
  417. }
  418. if (a->neg || BN_ucmp(a, m) >= 0) {
  419. if (!BN_nnmod(val[0], a, m, ctx))
  420. goto err;
  421. aa = val[0];
  422. } else
  423. aa = a;
  424. if (BN_is_zero(aa)) {
  425. BN_zero(rr);
  426. ret = 1;
  427. goto err;
  428. }
  429. if (!BN_to_montgomery(val[0], aa, mont, ctx))
  430. goto err; /* 1 */
  431. window = BN_window_bits_for_exponent_size(bits);
  432. if (window > 1) {
  433. if (!BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx))
  434. goto err; /* 2 */
  435. j = 1 << (window - 1);
  436. for (i = 1; i < j; i++) {
  437. if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
  438. !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx))
  439. goto err;
  440. }
  441. }
  442. start = 1; /* This is used to avoid multiplication etc
  443. * when there is only the value '1' in the
  444. * buffer. */
  445. wvalue = 0; /* The 'value' of the window */
  446. wstart = bits - 1; /* The top bit of the window */
  447. wend = 0; /* The bottom bit of the window */
  448. #if 1 /* by Shay Gueron's suggestion */
  449. j = m->top; /* borrow j */
  450. if (m->d[j - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
  451. if (bn_wexpand(r, j) == NULL)
  452. goto err;
  453. /* 2^(top*BN_BITS2) - m */
  454. r->d[0] = (0 - m->d[0]) & BN_MASK2;
  455. for (i = 1; i < j; i++)
  456. r->d[i] = (~m->d[i]) & BN_MASK2;
  457. r->top = j;
  458. /*
  459. * Upper words will be zero if the corresponding words of 'm' were
  460. * 0xfff[...], so decrement r->top accordingly.
  461. */
  462. bn_correct_top(r);
  463. } else
  464. #endif
  465. if (!BN_to_montgomery(r, BN_value_one(), mont, ctx))
  466. goto err;
  467. for (;;) {
  468. if (BN_is_bit_set(p, wstart) == 0) {
  469. if (!start) {
  470. if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
  471. goto err;
  472. }
  473. if (wstart == 0)
  474. break;
  475. wstart--;
  476. continue;
  477. }
  478. /*
  479. * We now have wstart on a 'set' bit, we now need to work out how bit
  480. * a window to do. To do this we need to scan forward until the last
  481. * set bit before the end of the window
  482. */
  483. j = wstart;
  484. wvalue = 1;
  485. wend = 0;
  486. for (i = 1; i < window; i++) {
  487. if (wstart - i < 0)
  488. break;
  489. if (BN_is_bit_set(p, wstart - i)) {
  490. wvalue <<= (i - wend);
  491. wvalue |= 1;
  492. wend = i;
  493. }
  494. }
  495. /* wend is the size of the current window */
  496. j = wend + 1;
  497. /* add the 'bytes above' */
  498. if (!start)
  499. for (i = 0; i < j; i++) {
  500. if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
  501. goto err;
  502. }
  503. /* wvalue will be an odd number < 2^window */
  504. if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx))
  505. goto err;
  506. /* move the 'window' down further */
  507. wstart -= wend + 1;
  508. wvalue = 0;
  509. start = 0;
  510. if (wstart < 0)
  511. break;
  512. }
  513. #if defined(SPARC_T4_MONT)
  514. if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
  515. j = mont->N.top; /* borrow j */
  516. val[0]->d[0] = 1; /* borrow val[0] */
  517. for (i = 1; i < j; i++)
  518. val[0]->d[i] = 0;
  519. val[0]->top = j;
  520. if (!BN_mod_mul_montgomery(rr, r, val[0], mont, ctx))
  521. goto err;
  522. } else
  523. #endif
  524. if (!BN_from_montgomery(rr, r, mont, ctx))
  525. goto err;
  526. ret = 1;
  527. err:
  528. if ((in_mont == NULL) && (mont != NULL))
  529. BN_MONT_CTX_free(mont);
  530. BN_CTX_end(ctx);
  531. bn_check_top(rr);
  532. return (ret);
  533. }
  534. #if defined(SPARC_T4_MONT)
  535. static BN_ULONG bn_get_bits(const BIGNUM *a, int bitpos)
  536. {
  537. BN_ULONG ret = 0;
  538. int wordpos;
  539. wordpos = bitpos / BN_BITS2;
  540. bitpos %= BN_BITS2;
  541. if (wordpos >= 0 && wordpos < a->top) {
  542. ret = a->d[wordpos] & BN_MASK2;
  543. if (bitpos) {
  544. ret >>= bitpos;
  545. if (++wordpos < a->top)
  546. ret |= a->d[wordpos] << (BN_BITS2 - bitpos);
  547. }
  548. }
  549. return ret & BN_MASK2;
  550. }
  551. #endif
  552. /*
  553. * BN_mod_exp_mont_consttime() stores the precomputed powers in a specific
  554. * layout so that accessing any of these table values shows the same access
  555. * pattern as far as cache lines are concerned. The following functions are
  556. * used to transfer a BIGNUM from/to that table.
  557. */
  558. static int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM *b, int top,
  559. unsigned char *buf, int idx,
  560. int window)
  561. {
  562. int i, j;
  563. int width = 1 << window;
  564. BN_ULONG *table = (BN_ULONG *)buf;
  565. if (top > b->top)
  566. top = b->top; /* this works because 'buf' is explicitly
  567. * zeroed */
  568. for (i = 0, j = idx; i < top; i++, j += width) {
  569. table[j] = b->d[i];
  570. }
  571. return 1;
  572. }
  573. static int MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM *b, int top,
  574. unsigned char *buf, int idx,
  575. int window)
  576. {
  577. int i, j;
  578. int width = 1 << window;
  579. volatile BN_ULONG *table = (volatile BN_ULONG *)buf;
  580. if (bn_wexpand(b, top) == NULL)
  581. return 0;
  582. if (window <= 3) {
  583. for (i = 0; i < top; i++, table += width) {
  584. BN_ULONG acc = 0;
  585. for (j = 0; j < width; j++) {
  586. acc |= table[j] &
  587. ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
  588. }
  589. b->d[i] = acc;
  590. }
  591. } else {
  592. int xstride = 1 << (window - 2);
  593. BN_ULONG y0, y1, y2, y3;
  594. i = idx >> (window - 2); /* equivalent of idx / xstride */
  595. idx &= xstride - 1; /* equivalent of idx % xstride */
  596. y0 = (BN_ULONG)0 - (constant_time_eq_int(i,0)&1);
  597. y1 = (BN_ULONG)0 - (constant_time_eq_int(i,1)&1);
  598. y2 = (BN_ULONG)0 - (constant_time_eq_int(i,2)&1);
  599. y3 = (BN_ULONG)0 - (constant_time_eq_int(i,3)&1);
  600. for (i = 0; i < top; i++, table += width) {
  601. BN_ULONG acc = 0;
  602. for (j = 0; j < xstride; j++) {
  603. acc |= ( (table[j + 0 * xstride] & y0) |
  604. (table[j + 1 * xstride] & y1) |
  605. (table[j + 2 * xstride] & y2) |
  606. (table[j + 3 * xstride] & y3) )
  607. & ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
  608. }
  609. b->d[i] = acc;
  610. }
  611. }
  612. b->top = top;
  613. bn_correct_top(b);
  614. return 1;
  615. }
  616. /*
  617. * Given a pointer value, compute the next address that is a cache line
  618. * multiple.
  619. */
  620. #define MOD_EXP_CTIME_ALIGN(x_) \
  621. ((unsigned char*)(x_) + (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - (((size_t)(x_)) & (MOD_EXP_CTIME_MIN_CACHE_LINE_MASK))))
  622. /*
  623. * This variant of BN_mod_exp_mont() uses fixed windows and the special
  624. * precomputation memory layout to limit data-dependency to a minimum to
  625. * protect secret exponents (cf. the hyper-threading timing attacks pointed
  626. * out by Colin Percival,
  627. * http://www.daemonology.net/hyperthreading-considered-harmful/)
  628. */
  629. int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
  630. const BIGNUM *m, BN_CTX *ctx,
  631. BN_MONT_CTX *in_mont)
  632. {
  633. int i, bits, ret = 0, window, wvalue;
  634. int top;
  635. BN_MONT_CTX *mont = NULL;
  636. int numPowers;
  637. unsigned char *powerbufFree = NULL;
  638. int powerbufLen = 0;
  639. unsigned char *powerbuf = NULL;
  640. BIGNUM tmp, am;
  641. #if defined(SPARC_T4_MONT)
  642. unsigned int t4 = 0;
  643. #endif
  644. bn_check_top(a);
  645. bn_check_top(p);
  646. bn_check_top(m);
  647. if (!BN_is_odd(m)) {
  648. BNerr(BN_F_BN_MOD_EXP_MONT_CONSTTIME, BN_R_CALLED_WITH_EVEN_MODULUS);
  649. return (0);
  650. }
  651. top = m->top;
  652. bits = BN_num_bits(p);
  653. if (bits == 0) {
  654. /* x**0 mod 1 is still zero. */
  655. if (BN_is_one(m)) {
  656. ret = 1;
  657. BN_zero(rr);
  658. } else {
  659. ret = BN_one(rr);
  660. }
  661. return ret;
  662. }
  663. BN_CTX_start(ctx);
  664. /*
  665. * Allocate a montgomery context if it was not supplied by the caller. If
  666. * this is not done, things will break in the montgomery part.
  667. */
  668. if (in_mont != NULL)
  669. mont = in_mont;
  670. else {
  671. if ((mont = BN_MONT_CTX_new()) == NULL)
  672. goto err;
  673. if (!BN_MONT_CTX_set(mont, m, ctx))
  674. goto err;
  675. }
  676. #ifdef RSAZ_ENABLED
  677. /*
  678. * If the size of the operands allow it, perform the optimized
  679. * RSAZ exponentiation. For further information see
  680. * crypto/bn/rsaz_exp.c and accompanying assembly modules.
  681. */
  682. if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024)
  683. && rsaz_avx2_eligible()) {
  684. if (NULL == bn_wexpand(rr, 16))
  685. goto err;
  686. RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d,
  687. mont->n0[0]);
  688. rr->top = 16;
  689. rr->neg = 0;
  690. bn_correct_top(rr);
  691. ret = 1;
  692. goto err;
  693. } else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) {
  694. if (NULL == bn_wexpand(rr, 8))
  695. goto err;
  696. RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d);
  697. rr->top = 8;
  698. rr->neg = 0;
  699. bn_correct_top(rr);
  700. ret = 1;
  701. goto err;
  702. }
  703. #endif
  704. /* Get the window size to use with size of p. */
  705. window = BN_window_bits_for_ctime_exponent_size(bits);
  706. #if defined(SPARC_T4_MONT)
  707. if (window >= 5 && (top & 15) == 0 && top <= 64 &&
  708. (OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) ==
  709. (CFR_MONTMUL | CFR_MONTSQR) && (t4 = OPENSSL_sparcv9cap_P[0]))
  710. window = 5;
  711. else
  712. #endif
  713. #if defined(OPENSSL_BN_ASM_MONT5)
  714. if (window >= 5) {
  715. window = 5; /* ~5% improvement for RSA2048 sign, and even
  716. * for RSA4096 */
  717. /* reserve space for mont->N.d[] copy */
  718. powerbufLen += top * sizeof(mont->N.d[0]);
  719. }
  720. #endif
  721. (void)0;
  722. /*
  723. * Allocate a buffer large enough to hold all of the pre-computed powers
  724. * of am, am itself and tmp.
  725. */
  726. numPowers = 1 << window;
  727. powerbufLen += sizeof(m->d[0]) * (top * numPowers +
  728. ((2 * top) >
  729. numPowers ? (2 * top) : numPowers));
  730. #ifdef alloca
  731. if (powerbufLen < 3072)
  732. powerbufFree =
  733. alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH);
  734. else
  735. #endif
  736. if ((powerbufFree =
  737. (unsigned char *)OPENSSL_malloc(powerbufLen +
  738. MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH))
  739. == NULL)
  740. goto err;
  741. powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree);
  742. memset(powerbuf, 0, powerbufLen);
  743. #ifdef alloca
  744. if (powerbufLen < 3072)
  745. powerbufFree = NULL;
  746. #endif
  747. /* lay down tmp and am right after powers table */
  748. tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers);
  749. am.d = tmp.d + top;
  750. tmp.top = am.top = 0;
  751. tmp.dmax = am.dmax = top;
  752. tmp.neg = am.neg = 0;
  753. tmp.flags = am.flags = BN_FLG_STATIC_DATA;
  754. /* prepare a^0 in Montgomery domain */
  755. #if 1 /* by Shay Gueron's suggestion */
  756. if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
  757. /* 2^(top*BN_BITS2) - m */
  758. tmp.d[0] = (0 - m->d[0]) & BN_MASK2;
  759. for (i = 1; i < top; i++)
  760. tmp.d[i] = (~m->d[i]) & BN_MASK2;
  761. tmp.top = top;
  762. } else
  763. #endif
  764. if (!BN_to_montgomery(&tmp, BN_value_one(), mont, ctx))
  765. goto err;
  766. /* prepare a^1 in Montgomery domain */
  767. if (a->neg || BN_ucmp(a, m) >= 0) {
  768. if (!BN_mod(&am, a, m, ctx))
  769. goto err;
  770. if (!BN_to_montgomery(&am, &am, mont, ctx))
  771. goto err;
  772. } else if (!BN_to_montgomery(&am, a, mont, ctx))
  773. goto err;
  774. #if defined(SPARC_T4_MONT)
  775. if (t4) {
  776. typedef int (*bn_pwr5_mont_f) (BN_ULONG *tp, const BN_ULONG *np,
  777. const BN_ULONG *n0, const void *table,
  778. int power, int bits);
  779. int bn_pwr5_mont_t4_8(BN_ULONG *tp, const BN_ULONG *np,
  780. const BN_ULONG *n0, const void *table,
  781. int power, int bits);
  782. int bn_pwr5_mont_t4_16(BN_ULONG *tp, const BN_ULONG *np,
  783. const BN_ULONG *n0, const void *table,
  784. int power, int bits);
  785. int bn_pwr5_mont_t4_24(BN_ULONG *tp, const BN_ULONG *np,
  786. const BN_ULONG *n0, const void *table,
  787. int power, int bits);
  788. int bn_pwr5_mont_t4_32(BN_ULONG *tp, const BN_ULONG *np,
  789. const BN_ULONG *n0, const void *table,
  790. int power, int bits);
  791. static const bn_pwr5_mont_f pwr5_funcs[4] = {
  792. bn_pwr5_mont_t4_8, bn_pwr5_mont_t4_16,
  793. bn_pwr5_mont_t4_24, bn_pwr5_mont_t4_32
  794. };
  795. bn_pwr5_mont_f pwr5_worker = pwr5_funcs[top / 16 - 1];
  796. typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap,
  797. const void *bp, const BN_ULONG *np,
  798. const BN_ULONG *n0);
  799. int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const void *bp,
  800. const BN_ULONG *np, const BN_ULONG *n0);
  801. int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap,
  802. const void *bp, const BN_ULONG *np,
  803. const BN_ULONG *n0);
  804. int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap,
  805. const void *bp, const BN_ULONG *np,
  806. const BN_ULONG *n0);
  807. int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap,
  808. const void *bp, const BN_ULONG *np,
  809. const BN_ULONG *n0);
  810. static const bn_mul_mont_f mul_funcs[4] = {
  811. bn_mul_mont_t4_8, bn_mul_mont_t4_16,
  812. bn_mul_mont_t4_24, bn_mul_mont_t4_32
  813. };
  814. bn_mul_mont_f mul_worker = mul_funcs[top / 16 - 1];
  815. void bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap,
  816. const void *bp, const BN_ULONG *np,
  817. const BN_ULONG *n0, int num);
  818. void bn_mul_mont_t4(BN_ULONG *rp, const BN_ULONG *ap,
  819. const void *bp, const BN_ULONG *np,
  820. const BN_ULONG *n0, int num);
  821. void bn_mul_mont_gather5_t4(BN_ULONG *rp, const BN_ULONG *ap,
  822. const void *table, const BN_ULONG *np,
  823. const BN_ULONG *n0, int num, int power);
  824. void bn_flip_n_scatter5_t4(const BN_ULONG *inp, size_t num,
  825. void *table, size_t power);
  826. void bn_gather5_t4(BN_ULONG *out, size_t num,
  827. void *table, size_t power);
  828. void bn_flip_t4(BN_ULONG *dst, BN_ULONG *src, size_t num);
  829. BN_ULONG *np = mont->N.d, *n0 = mont->n0;
  830. int stride = 5 * (6 - (top / 16 - 1)); /* multiple of 5, but less
  831. * than 32 */
  832. /*
  833. * BN_to_montgomery can contaminate words above .top [in
  834. * BN_DEBUG[_DEBUG] build]...
  835. */
  836. for (i = am.top; i < top; i++)
  837. am.d[i] = 0;
  838. for (i = tmp.top; i < top; i++)
  839. tmp.d[i] = 0;
  840. bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 0);
  841. bn_flip_n_scatter5_t4(am.d, top, powerbuf, 1);
  842. if (!(*mul_worker) (tmp.d, am.d, am.d, np, n0) &&
  843. !(*mul_worker) (tmp.d, am.d, am.d, np, n0))
  844. bn_mul_mont_vis3(tmp.d, am.d, am.d, np, n0, top);
  845. bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 2);
  846. for (i = 3; i < 32; i++) {
  847. /* Calculate a^i = a^(i-1) * a */
  848. if (!(*mul_worker) (tmp.d, tmp.d, am.d, np, n0) &&
  849. !(*mul_worker) (tmp.d, tmp.d, am.d, np, n0))
  850. bn_mul_mont_vis3(tmp.d, tmp.d, am.d, np, n0, top);
  851. bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, i);
  852. }
  853. /* switch to 64-bit domain */
  854. np = alloca(top * sizeof(BN_ULONG));
  855. top /= 2;
  856. bn_flip_t4(np, mont->N.d, top);
  857. bits--;
  858. for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
  859. wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
  860. bn_gather5_t4(tmp.d, top, powerbuf, wvalue);
  861. /*
  862. * Scan the exponent one window at a time starting from the most
  863. * significant bits.
  864. */
  865. while (bits >= 0) {
  866. if (bits < stride)
  867. stride = bits + 1;
  868. bits -= stride;
  869. wvalue = bn_get_bits(p, bits + 1);
  870. if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
  871. continue;
  872. /* retry once and fall back */
  873. if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
  874. continue;
  875. bits += stride - 5;
  876. wvalue >>= stride - 5;
  877. wvalue &= 31;
  878. bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
  879. bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
  880. bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
  881. bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
  882. bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
  883. bn_mul_mont_gather5_t4(tmp.d, tmp.d, powerbuf, np, n0, top,
  884. wvalue);
  885. }
  886. bn_flip_t4(tmp.d, tmp.d, top);
  887. top *= 2;
  888. /* back to 32-bit domain */
  889. tmp.top = top;
  890. bn_correct_top(&tmp);
  891. OPENSSL_cleanse(np, top * sizeof(BN_ULONG));
  892. } else
  893. #endif
  894. #if defined(OPENSSL_BN_ASM_MONT5)
  895. if (window == 5 && top > 1) {
  896. /*
  897. * This optimization uses ideas from http://eprint.iacr.org/2011/239,
  898. * specifically optimization of cache-timing attack countermeasures
  899. * and pre-computation optimization.
  900. */
  901. /*
  902. * Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as
  903. * 512-bit RSA is hardly relevant, we omit it to spare size...
  904. */
  905. void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap,
  906. const void *table, const BN_ULONG *np,
  907. const BN_ULONG *n0, int num, int power);
  908. void bn_scatter5(const BN_ULONG *inp, size_t num,
  909. void *table, size_t power);
  910. void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power);
  911. void bn_power5(BN_ULONG *rp, const BN_ULONG *ap,
  912. const void *table, const BN_ULONG *np,
  913. const BN_ULONG *n0, int num, int power);
  914. int bn_get_bits5(const BN_ULONG *ap, int off);
  915. int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap,
  916. const BN_ULONG *not_used, const BN_ULONG *np,
  917. const BN_ULONG *n0, int num);
  918. BN_ULONG *n0 = mont->n0, *np;
  919. /*
  920. * BN_to_montgomery can contaminate words above .top [in
  921. * BN_DEBUG[_DEBUG] build]...
  922. */
  923. for (i = am.top; i < top; i++)
  924. am.d[i] = 0;
  925. for (i = tmp.top; i < top; i++)
  926. tmp.d[i] = 0;
  927. /*
  928. * copy mont->N.d[] to improve cache locality
  929. */
  930. for (np = am.d + top, i = 0; i < top; i++)
  931. np[i] = mont->N.d[i];
  932. bn_scatter5(tmp.d, top, powerbuf, 0);
  933. bn_scatter5(am.d, am.top, powerbuf, 1);
  934. bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);
  935. bn_scatter5(tmp.d, top, powerbuf, 2);
  936. # if 0
  937. for (i = 3; i < 32; i++) {
  938. /* Calculate a^i = a^(i-1) * a */
  939. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
  940. bn_scatter5(tmp.d, top, powerbuf, i);
  941. }
  942. # else
  943. /* same as above, but uses squaring for 1/2 of operations */
  944. for (i = 4; i < 32; i *= 2) {
  945. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  946. bn_scatter5(tmp.d, top, powerbuf, i);
  947. }
  948. for (i = 3; i < 8; i += 2) {
  949. int j;
  950. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
  951. bn_scatter5(tmp.d, top, powerbuf, i);
  952. for (j = 2 * i; j < 32; j *= 2) {
  953. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  954. bn_scatter5(tmp.d, top, powerbuf, j);
  955. }
  956. }
  957. for (; i < 16; i += 2) {
  958. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
  959. bn_scatter5(tmp.d, top, powerbuf, i);
  960. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  961. bn_scatter5(tmp.d, top, powerbuf, 2 * i);
  962. }
  963. for (; i < 32; i += 2) {
  964. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
  965. bn_scatter5(tmp.d, top, powerbuf, i);
  966. }
  967. # endif
  968. bits--;
  969. for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
  970. wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
  971. bn_gather5(tmp.d, top, powerbuf, wvalue);
  972. /*
  973. * Scan the exponent one window at a time starting from the most
  974. * significant bits.
  975. */
  976. if (top & 7)
  977. while (bits >= 0) {
  978. for (wvalue = 0, i = 0; i < 5; i++, bits--)
  979. wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
  980. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  981. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  982. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  983. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  984. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  985. bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top,
  986. wvalue);
  987. } else {
  988. while (bits >= 0) {
  989. wvalue = bn_get_bits5(p->d, bits - 4);
  990. bits -= 5;
  991. bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue);
  992. }
  993. }
  994. ret = bn_from_montgomery(tmp.d, tmp.d, NULL, np, n0, top);
  995. tmp.top = top;
  996. bn_correct_top(&tmp);
  997. if (ret) {
  998. if (!BN_copy(rr, &tmp))
  999. ret = 0;
  1000. goto err; /* non-zero ret means it's not error */
  1001. }
  1002. } else
  1003. #endif
  1004. {
  1005. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, window))
  1006. goto err;
  1007. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, window))
  1008. goto err;
  1009. /*
  1010. * If the window size is greater than 1, then calculate
  1011. * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even
  1012. * powers could instead be computed as (a^(i/2))^2 to use the slight
  1013. * performance advantage of sqr over mul).
  1014. */
  1015. if (window > 1) {
  1016. if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx))
  1017. goto err;
  1018. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 2,
  1019. window))
  1020. goto err;
  1021. for (i = 3; i < numPowers; i++) {
  1022. /* Calculate a^i = a^(i-1) * a */
  1023. if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx))
  1024. goto err;
  1025. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, i,
  1026. window))
  1027. goto err;
  1028. }
  1029. }
  1030. bits--;
  1031. for (wvalue = 0, i = bits % window; i >= 0; i--, bits--)
  1032. wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
  1033. if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&tmp, top, powerbuf, wvalue,
  1034. window))
  1035. goto err;
  1036. /*
  1037. * Scan the exponent one window at a time starting from the most
  1038. * significant bits.
  1039. */
  1040. while (bits >= 0) {
  1041. wvalue = 0; /* The 'value' of the window */
  1042. /* Scan the window, squaring the result as we go */
  1043. for (i = 0; i < window; i++, bits--) {
  1044. if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx))
  1045. goto err;
  1046. wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
  1047. }
  1048. /*
  1049. * Fetch the appropriate pre-computed value from the pre-buf
  1050. */
  1051. if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&am, top, powerbuf, wvalue,
  1052. window))
  1053. goto err;
  1054. /* Multiply the result into the intermediate result */
  1055. if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx))
  1056. goto err;
  1057. }
  1058. }
  1059. /* Convert the final result from montgomery to standard format */
  1060. #if defined(SPARC_T4_MONT)
  1061. if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
  1062. am.d[0] = 1; /* borrow am */
  1063. for (i = 1; i < top; i++)
  1064. am.d[i] = 0;
  1065. if (!BN_mod_mul_montgomery(rr, &tmp, &am, mont, ctx))
  1066. goto err;
  1067. } else
  1068. #endif
  1069. if (!BN_from_montgomery(rr, &tmp, mont, ctx))
  1070. goto err;
  1071. ret = 1;
  1072. err:
  1073. if ((in_mont == NULL) && (mont != NULL))
  1074. BN_MONT_CTX_free(mont);
  1075. if (powerbuf != NULL) {
  1076. OPENSSL_cleanse(powerbuf, powerbufLen);
  1077. if (powerbufFree)
  1078. OPENSSL_free(powerbufFree);
  1079. }
  1080. BN_CTX_end(ctx);
  1081. return (ret);
  1082. }
  1083. int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
  1084. const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
  1085. {
  1086. BN_MONT_CTX *mont = NULL;
  1087. int b, bits, ret = 0;
  1088. int r_is_one;
  1089. BN_ULONG w, next_w;
  1090. BIGNUM *d, *r, *t;
  1091. BIGNUM *swap_tmp;
  1092. #define BN_MOD_MUL_WORD(r, w, m) \
  1093. (BN_mul_word(r, (w)) && \
  1094. (/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \
  1095. (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1))))
  1096. /*
  1097. * BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is
  1098. * probably more overhead than always using BN_mod (which uses BN_copy if
  1099. * a similar test returns true).
  1100. */
  1101. /*
  1102. * We can use BN_mod and do not need BN_nnmod because our accumulator is
  1103. * never negative (the result of BN_mod does not depend on the sign of
  1104. * the modulus).
  1105. */
  1106. #define BN_TO_MONTGOMERY_WORD(r, w, mont) \
  1107. (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx))
  1108. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
  1109. /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
  1110. BNerr(BN_F_BN_MOD_EXP_MONT_WORD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  1111. return -1;
  1112. }
  1113. bn_check_top(p);
  1114. bn_check_top(m);
  1115. if (!BN_is_odd(m)) {
  1116. BNerr(BN_F_BN_MOD_EXP_MONT_WORD, BN_R_CALLED_WITH_EVEN_MODULUS);
  1117. return (0);
  1118. }
  1119. if (m->top == 1)
  1120. a %= m->d[0]; /* make sure that 'a' is reduced */
  1121. bits = BN_num_bits(p);
  1122. if (bits == 0) {
  1123. /* x**0 mod 1 is still zero. */
  1124. if (BN_is_one(m)) {
  1125. ret = 1;
  1126. BN_zero(rr);
  1127. } else {
  1128. ret = BN_one(rr);
  1129. }
  1130. return ret;
  1131. }
  1132. if (a == 0) {
  1133. BN_zero(rr);
  1134. ret = 1;
  1135. return ret;
  1136. }
  1137. BN_CTX_start(ctx);
  1138. d = BN_CTX_get(ctx);
  1139. r = BN_CTX_get(ctx);
  1140. t = BN_CTX_get(ctx);
  1141. if (d == NULL || r == NULL || t == NULL)
  1142. goto err;
  1143. if (in_mont != NULL)
  1144. mont = in_mont;
  1145. else {
  1146. if ((mont = BN_MONT_CTX_new()) == NULL)
  1147. goto err;
  1148. if (!BN_MONT_CTX_set(mont, m, ctx))
  1149. goto err;
  1150. }
  1151. r_is_one = 1; /* except for Montgomery factor */
  1152. /* bits-1 >= 0 */
  1153. /* The result is accumulated in the product r*w. */
  1154. w = a; /* bit 'bits-1' of 'p' is always set */
  1155. for (b = bits - 2; b >= 0; b--) {
  1156. /* First, square r*w. */
  1157. next_w = w * w;
  1158. if ((next_w / w) != w) { /* overflow */
  1159. if (r_is_one) {
  1160. if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
  1161. goto err;
  1162. r_is_one = 0;
  1163. } else {
  1164. if (!BN_MOD_MUL_WORD(r, w, m))
  1165. goto err;
  1166. }
  1167. next_w = 1;
  1168. }
  1169. w = next_w;
  1170. if (!r_is_one) {
  1171. if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
  1172. goto err;
  1173. }
  1174. /* Second, multiply r*w by 'a' if exponent bit is set. */
  1175. if (BN_is_bit_set(p, b)) {
  1176. next_w = w * a;
  1177. if ((next_w / a) != w) { /* overflow */
  1178. if (r_is_one) {
  1179. if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
  1180. goto err;
  1181. r_is_one = 0;
  1182. } else {
  1183. if (!BN_MOD_MUL_WORD(r, w, m))
  1184. goto err;
  1185. }
  1186. next_w = a;
  1187. }
  1188. w = next_w;
  1189. }
  1190. }
  1191. /* Finally, set r:=r*w. */
  1192. if (w != 1) {
  1193. if (r_is_one) {
  1194. if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
  1195. goto err;
  1196. r_is_one = 0;
  1197. } else {
  1198. if (!BN_MOD_MUL_WORD(r, w, m))
  1199. goto err;
  1200. }
  1201. }
  1202. if (r_is_one) { /* can happen only if a == 1 */
  1203. if (!BN_one(rr))
  1204. goto err;
  1205. } else {
  1206. if (!BN_from_montgomery(rr, r, mont, ctx))
  1207. goto err;
  1208. }
  1209. ret = 1;
  1210. err:
  1211. if ((in_mont == NULL) && (mont != NULL))
  1212. BN_MONT_CTX_free(mont);
  1213. BN_CTX_end(ctx);
  1214. bn_check_top(rr);
  1215. return (ret);
  1216. }
  1217. /* The old fallback, simple version :-) */
  1218. int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
  1219. const BIGNUM *m, BN_CTX *ctx)
  1220. {
  1221. int i, j, bits, ret = 0, wstart, wend, window, wvalue;
  1222. int start = 1;
  1223. BIGNUM *d;
  1224. /* Table of variables obtained from 'ctx' */
  1225. BIGNUM *val[TABLE_SIZE];
  1226. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
  1227. /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
  1228. BNerr(BN_F_BN_MOD_EXP_SIMPLE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  1229. return -1;
  1230. }
  1231. bits = BN_num_bits(p);
  1232. if (bits == 0) {
  1233. /* x**0 mod 1 is still zero. */
  1234. if (BN_is_one(m)) {
  1235. ret = 1;
  1236. BN_zero(r);
  1237. } else {
  1238. ret = BN_one(r);
  1239. }
  1240. return ret;
  1241. }
  1242. BN_CTX_start(ctx);
  1243. d = BN_CTX_get(ctx);
  1244. val[0] = BN_CTX_get(ctx);
  1245. if (!d || !val[0])
  1246. goto err;
  1247. if (!BN_nnmod(val[0], a, m, ctx))
  1248. goto err; /* 1 */
  1249. if (BN_is_zero(val[0])) {
  1250. BN_zero(r);
  1251. ret = 1;
  1252. goto err;
  1253. }
  1254. window = BN_window_bits_for_exponent_size(bits);
  1255. if (window > 1) {
  1256. if (!BN_mod_mul(d, val[0], val[0], m, ctx))
  1257. goto err; /* 2 */
  1258. j = 1 << (window - 1);
  1259. for (i = 1; i < j; i++) {
  1260. if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
  1261. !BN_mod_mul(val[i], val[i - 1], d, m, ctx))
  1262. goto err;
  1263. }
  1264. }
  1265. start = 1; /* This is used to avoid multiplication etc
  1266. * when there is only the value '1' in the
  1267. * buffer. */
  1268. wvalue = 0; /* The 'value' of the window */
  1269. wstart = bits - 1; /* The top bit of the window */
  1270. wend = 0; /* The bottom bit of the window */
  1271. if (!BN_one(r))
  1272. goto err;
  1273. for (;;) {
  1274. if (BN_is_bit_set(p, wstart) == 0) {
  1275. if (!start)
  1276. if (!BN_mod_mul(r, r, r, m, ctx))
  1277. goto err;
  1278. if (wstart == 0)
  1279. break;
  1280. wstart--;
  1281. continue;
  1282. }
  1283. /*
  1284. * We now have wstart on a 'set' bit, we now need to work out how bit
  1285. * a window to do. To do this we need to scan forward until the last
  1286. * set bit before the end of the window
  1287. */
  1288. j = wstart;
  1289. wvalue = 1;
  1290. wend = 0;
  1291. for (i = 1; i < window; i++) {
  1292. if (wstart - i < 0)
  1293. break;
  1294. if (BN_is_bit_set(p, wstart - i)) {
  1295. wvalue <<= (i - wend);
  1296. wvalue |= 1;
  1297. wend = i;
  1298. }
  1299. }
  1300. /* wend is the size of the current window */
  1301. j = wend + 1;
  1302. /* add the 'bytes above' */
  1303. if (!start)
  1304. for (i = 0; i < j; i++) {
  1305. if (!BN_mod_mul(r, r, r, m, ctx))
  1306. goto err;
  1307. }
  1308. /* wvalue will be an odd number < 2^window */
  1309. if (!BN_mod_mul(r, r, val[wvalue >> 1], m, ctx))
  1310. goto err;
  1311. /* move the 'window' down further */
  1312. wstart -= wend + 1;
  1313. wvalue = 0;
  1314. start = 0;
  1315. if (wstart < 0)
  1316. break;
  1317. }
  1318. ret = 1;
  1319. err:
  1320. BN_CTX_end(ctx);
  1321. bn_check_top(r);
  1322. return (ret);
  1323. }