bn_exp.c 48 KB

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