Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

axtls_bigint.c 38KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513
  1. /*
  2. * Copyright (c) 2007, Cameron Rich
  3. *
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * * Redistributions of source code must retain the above copyright notice,
  10. * this list of conditions and the following disclaimer.
  11. * * Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. * * Neither the name of the axTLS project nor the names of its contributors
  15. * may be used to endorse or promote products derived from this software
  16. * without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  22. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  23. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  24. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  25. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  26. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  27. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  28. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. /**
  31. * @defgroup bigint_api Big Integer API
  32. * @brief The bigint implementation as used by the axTLS project.
  33. *
  34. * The bigint library is for RSA encryption/decryption as well as signing.
  35. * This code tries to minimise use of malloc/free by maintaining a small
  36. * cache. A bigint context may maintain state by being made "permanent".
  37. * It be be later released with a bi_depermanent() and bi_free() call.
  38. *
  39. * It supports the following reduction techniques:
  40. * - Classical
  41. * - Barrett
  42. * - Montgomery
  43. *
  44. * It also implements the following:
  45. * - Karatsuba multiplication
  46. * - Squaring
  47. * - Sliding window exponentiation
  48. * - Chinese Remainder Theorem (implemented in rsa.c).
  49. *
  50. * All the algorithms used are pretty standard, and designed for different
  51. * data bus sizes. Negative numbers are not dealt with at all, so a subtraction
  52. * may need to be tested for negativity.
  53. *
  54. * This library steals some ideas from Jef Poskanzer
  55. * <http://cs.marlboro.edu/term/cs-fall02/algorithms/crypto/RSA/bigint>
  56. * and GMP <http://www.swox.com/gmp>. It gets most of its implementation
  57. * detail from "The Handbook of Applied Cryptography"
  58. * <http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf>
  59. * @{
  60. */
  61. #include <stdlib.h>
  62. #include <limits.h>
  63. #include <string.h>
  64. #include <stdio.h>
  65. #include <time.h>
  66. #include "os_port.h"
  67. #include "bigint.h"
  68. #define V1 v->comps[v->size-1] /**< v1 for division */
  69. #define V2 v->comps[v->size-2] /**< v2 for division */
  70. #define U(j) tmp_u->comps[tmp_u->size-j-1] /**< uj for division */
  71. #define Q(j) quotient->comps[quotient->size-j-1] /**< qj for division */
  72. static bigint *bi_int_multiply(BI_CTX *ctx, bigint *bi, comp i);
  73. static bigint *bi_int_divide(BI_CTX *ctx, bigint *biR, comp denom);
  74. static bigint *alloc(BI_CTX *ctx, int size);
  75. static bigint *trim(bigint *bi);
  76. static void more_comps(bigint *bi, int n);
  77. #if defined(CONFIG_BIGINT_KARATSUBA) || defined(CONFIG_BIGINT_BARRETT) || \
  78. defined(CONFIG_BIGINT_MONTGOMERY)
  79. static bigint *comp_right_shift(bigint *biR, int num_shifts);
  80. static bigint *comp_left_shift(bigint *biR, int num_shifts);
  81. #endif
  82. #ifdef CONFIG_BIGINT_CHECK_ON
  83. static void check(const bigint *bi);
  84. #else
  85. #define check(A) /**< disappears in normal production mode */
  86. #endif
  87. /**
  88. * @brief Start a new bigint context.
  89. * @return A bigint context.
  90. */
  91. BI_CTX *bi_initialize(void)
  92. {
  93. /* calloc() sets everything to zero */
  94. BI_CTX *ctx = (BI_CTX *)calloc(1, sizeof(BI_CTX));
  95. /* the radix */
  96. ctx->bi_radix = alloc(ctx, 2);
  97. ctx->bi_radix->comps[0] = 0;
  98. ctx->bi_radix->comps[1] = 1;
  99. bi_permanent(ctx->bi_radix);
  100. return ctx;
  101. }
  102. /**
  103. * @brief Close the bigint context and free any resources.
  104. *
  105. * Free up any used memory - a check is done if all objects were not
  106. * properly freed.
  107. * @param ctx [in] The bigint session context.
  108. */
  109. void bi_terminate(BI_CTX *ctx)
  110. {
  111. bi_depermanent(ctx->bi_radix);
  112. bi_free(ctx, ctx->bi_radix);
  113. if (ctx->active_count != 0)
  114. {
  115. #ifdef CONFIG_SSL_FULL_MODE
  116. printf("bi_terminate: there were %d un-freed bigints\n",
  117. ctx->active_count);
  118. #endif
  119. abort();
  120. }
  121. bi_clear_cache(ctx);
  122. free(ctx);
  123. }
  124. /**
  125. *@brief Clear the memory cache.
  126. */
  127. void bi_clear_cache(BI_CTX *ctx)
  128. {
  129. bigint *p, *pn;
  130. if (ctx->free_list == NULL)
  131. return;
  132. for (p = ctx->free_list; p != NULL; p = pn)
  133. {
  134. pn = p->next;
  135. free(p->comps);
  136. free(p);
  137. }
  138. ctx->free_count = 0;
  139. ctx->free_list = NULL;
  140. }
  141. /**
  142. * @brief Increment the number of references to this object.
  143. * It does not do a full copy.
  144. * @param bi [in] The bigint to copy.
  145. * @return A reference to the same bigint.
  146. */
  147. bigint *bi_copy(bigint *bi)
  148. {
  149. check(bi);
  150. if (bi->refs != PERMANENT)
  151. bi->refs++;
  152. return bi;
  153. }
  154. /**
  155. * @brief Simply make a bigint object "unfreeable" if bi_free() is called on it.
  156. *
  157. * For this object to be freed, bi_depermanent() must be called.
  158. * @param bi [in] The bigint to be made permanent.
  159. */
  160. void bi_permanent(bigint *bi)
  161. {
  162. check(bi);
  163. if (bi->refs != 1)
  164. {
  165. #ifdef CONFIG_SSL_FULL_MODE
  166. printf("bi_permanent: refs was not 1\n");
  167. #endif
  168. abort();
  169. }
  170. bi->refs = PERMANENT;
  171. }
  172. /**
  173. * @brief Take a permanent object and make it eligible for freedom.
  174. * @param bi [in] The bigint to be made back to temporary.
  175. */
  176. void bi_depermanent(bigint *bi)
  177. {
  178. check(bi);
  179. if (bi->refs != PERMANENT)
  180. {
  181. #ifdef CONFIG_SSL_FULL_MODE
  182. printf("bi_depermanent: bigint was not permanent\n");
  183. #endif
  184. abort();
  185. }
  186. bi->refs = 1;
  187. }
  188. /**
  189. * @brief Free a bigint object so it can be used again.
  190. *
  191. * The memory itself it not actually freed, just tagged as being available
  192. * @param ctx [in] The bigint session context.
  193. * @param bi [in] The bigint to be freed.
  194. */
  195. void bi_free(BI_CTX *ctx, bigint *bi)
  196. {
  197. check(bi);
  198. if (bi->refs == PERMANENT)
  199. {
  200. return;
  201. }
  202. if (--bi->refs > 0)
  203. {
  204. return;
  205. }
  206. bi->next = ctx->free_list;
  207. ctx->free_list = bi;
  208. ctx->free_count++;
  209. if (--ctx->active_count < 0)
  210. {
  211. #ifdef CONFIG_SSL_FULL_MODE
  212. printf("bi_free: active_count went negative "
  213. "- double-freed bigint?\n");
  214. #endif
  215. abort();
  216. }
  217. }
  218. /**
  219. * @brief Convert an (unsigned) integer into a bigint.
  220. * @param ctx [in] The bigint session context.
  221. * @param i [in] The (unsigned) integer to be converted.
  222. *
  223. */
  224. bigint *int_to_bi(BI_CTX *ctx, comp i)
  225. {
  226. bigint *biR = alloc(ctx, 1);
  227. biR->comps[0] = i;
  228. return biR;
  229. }
  230. /**
  231. * @brief Do a full copy of the bigint object.
  232. * @param ctx [in] The bigint session context.
  233. * @param bi [in] The bigint object to be copied.
  234. */
  235. bigint *bi_clone(BI_CTX *ctx, const bigint *bi)
  236. {
  237. bigint *biR = alloc(ctx, bi->size);
  238. check(bi);
  239. memcpy(biR->comps, bi->comps, bi->size*COMP_BYTE_SIZE);
  240. return biR;
  241. }
  242. /**
  243. * @brief Perform an addition operation between two bigints.
  244. * @param ctx [in] The bigint session context.
  245. * @param bia [in] A bigint.
  246. * @param bib [in] Another bigint.
  247. * @return The result of the addition.
  248. */
  249. bigint *bi_add(BI_CTX *ctx, bigint *bia, bigint *bib)
  250. {
  251. int n;
  252. comp carry = 0;
  253. comp *pa, *pb;
  254. check(bia);
  255. check(bib);
  256. n = max(bia->size, bib->size);
  257. more_comps(bia, n+1);
  258. more_comps(bib, n);
  259. pa = bia->comps;
  260. pb = bib->comps;
  261. do
  262. {
  263. comp sl, rl, cy1;
  264. sl = *pa + *pb++;
  265. rl = sl + carry;
  266. cy1 = sl < *pa;
  267. carry = cy1 | (rl < sl);
  268. *pa++ = rl;
  269. } while (--n != 0);
  270. *pa = carry; /* do overflow */
  271. bi_free(ctx, bib);
  272. return trim(bia);
  273. }
  274. /**
  275. * @brief Perform a subtraction operation between two bigints.
  276. * @param ctx [in] The bigint session context.
  277. * @param bia [in] A bigint.
  278. * @param bib [in] Another bigint.
  279. * @param is_negative [out] If defined, indicates that the result was negative.
  280. * is_negative may be null.
  281. * @return The result of the subtraction. The result is always positive.
  282. */
  283. bigint *bi_subtract(BI_CTX *ctx,
  284. bigint *bia, bigint *bib, int *is_negative)
  285. {
  286. int n = bia->size;
  287. comp *pa, *pb, carry = 0;
  288. check(bia);
  289. check(bib);
  290. more_comps(bib, n);
  291. pa = bia->comps;
  292. pb = bib->comps;
  293. do
  294. {
  295. comp sl, rl, cy1;
  296. sl = *pa - *pb++;
  297. rl = sl - carry;
  298. cy1 = sl > *pa;
  299. carry = cy1 | (rl > sl);
  300. *pa++ = rl;
  301. } while (--n != 0);
  302. if (is_negative) /* indicate a negative result */
  303. {
  304. *is_negative = carry;
  305. }
  306. bi_free(ctx, trim(bib)); /* put bib back to the way it was */
  307. return trim(bia);
  308. }
  309. /**
  310. * Perform a multiply between a bigint an an (unsigned) integer
  311. */
  312. static bigint *bi_int_multiply(BI_CTX *ctx, bigint *bia, comp b)
  313. {
  314. int j = 0, n = bia->size;
  315. bigint *biR = alloc(ctx, n + 1);
  316. comp carry = 0;
  317. comp *r = biR->comps;
  318. comp *a = bia->comps;
  319. check(bia);
  320. /* clear things to start with */
  321. memset(r, 0, ((n+1)*COMP_BYTE_SIZE));
  322. do
  323. {
  324. long_comp tmp = *r + (long_comp)a[j]*b + carry;
  325. *r++ = (comp)tmp; /* downsize */
  326. carry = (comp)(tmp >> COMP_BIT_SIZE);
  327. } while (++j < n);
  328. *r = carry;
  329. bi_free(ctx, bia);
  330. return trim(biR);
  331. }
  332. /**
  333. * @brief Does both division and modulo calculations.
  334. *
  335. * Used extensively when doing classical reduction.
  336. * @param ctx [in] The bigint session context.
  337. * @param u [in] A bigint which is the numerator.
  338. * @param v [in] Either the denominator or the modulus depending on the mode.
  339. * @param is_mod [n] Determines if this is a normal division (0) or a reduction
  340. * (1).
  341. * @return The result of the division/reduction.
  342. */
  343. bigint *bi_divide(BI_CTX *ctx, bigint *u, bigint *v, int is_mod)
  344. {
  345. int n = v->size, m = u->size-n;
  346. int j = 0, orig_u_size = u->size;
  347. uint8_t mod_offset = ctx->mod_offset;
  348. comp d;
  349. bigint *quotient, *tmp_u;
  350. comp q_dash;
  351. check(u);
  352. check(v);
  353. /* if doing reduction and we are < mod, then return mod */
  354. if (is_mod && bi_compare(v, u) > 0)
  355. {
  356. bi_free(ctx, v);
  357. return u;
  358. }
  359. quotient = alloc(ctx, m+1);
  360. tmp_u = alloc(ctx, n+1);
  361. v = trim(v); /* make sure we have no leading 0's */
  362. d = (comp)((long_comp)COMP_RADIX/(V1+1));
  363. /* clear things to start with */
  364. memset(quotient->comps, 0, ((quotient->size)*COMP_BYTE_SIZE));
  365. /* normalise */
  366. if (d > 1)
  367. {
  368. u = bi_int_multiply(ctx, u, d);
  369. if (is_mod)
  370. {
  371. v = ctx->bi_normalised_mod[mod_offset];
  372. }
  373. else
  374. {
  375. v = bi_int_multiply(ctx, v, d);
  376. }
  377. }
  378. if (orig_u_size == u->size) /* new digit position u0 */
  379. {
  380. more_comps(u, orig_u_size + 1);
  381. }
  382. do
  383. {
  384. /* get a temporary short version of u */
  385. memcpy(tmp_u->comps, &u->comps[u->size-n-1-j], (n+1)*COMP_BYTE_SIZE);
  386. /* calculate q' */
  387. if (U(0) == V1)
  388. {
  389. q_dash = COMP_RADIX-1;
  390. }
  391. else
  392. {
  393. q_dash = (comp)(((long_comp)U(0)*COMP_RADIX + U(1))/V1);
  394. if (v->size > 1 && V2)
  395. {
  396. /* we are implementing the following:
  397. if (V2*q_dash > (((U(0)*COMP_RADIX + U(1) -
  398. q_dash*V1)*COMP_RADIX) + U(2))) ... */
  399. comp inner = (comp)((long_comp)COMP_RADIX*U(0) + U(1) -
  400. (long_comp)q_dash*V1);
  401. if ((long_comp)V2*q_dash > (long_comp)inner*COMP_RADIX + U(2))
  402. {
  403. q_dash--;
  404. }
  405. }
  406. }
  407. /* multiply and subtract */
  408. if (q_dash)
  409. {
  410. int is_negative;
  411. tmp_u = bi_subtract(ctx, tmp_u,
  412. bi_int_multiply(ctx, bi_copy(v), q_dash), &is_negative);
  413. more_comps(tmp_u, n+1);
  414. Q(j) = q_dash;
  415. /* add back */
  416. if (is_negative)
  417. {
  418. Q(j)--;
  419. tmp_u = bi_add(ctx, tmp_u, bi_copy(v));
  420. /* lop off the carry */
  421. tmp_u->size--;
  422. v->size--;
  423. }
  424. }
  425. else
  426. {
  427. Q(j) = 0;
  428. }
  429. /* copy back to u */
  430. memcpy(&u->comps[u->size-n-1-j], tmp_u->comps, (n+1)*COMP_BYTE_SIZE);
  431. } while (++j <= m);
  432. bi_free(ctx, tmp_u);
  433. bi_free(ctx, v);
  434. if (is_mod) /* get the remainder */
  435. {
  436. bi_free(ctx, quotient);
  437. return bi_int_divide(ctx, trim(u), d);
  438. }
  439. else /* get the quotient */
  440. {
  441. bi_free(ctx, u);
  442. return trim(quotient);
  443. }
  444. }
  445. /*
  446. * Perform an integer divide on a bigint.
  447. */
  448. // mcb30 - mark ctx with __unused to avoid a compilation error
  449. static bigint *bi_int_divide(BI_CTX *ctx __unused, bigint *biR, comp denom)
  450. {
  451. int i = biR->size - 1;
  452. long_comp r = 0;
  453. check(biR);
  454. do
  455. {
  456. r = (r<<COMP_BIT_SIZE) + biR->comps[i];
  457. biR->comps[i] = (comp)(r / denom);
  458. r %= denom;
  459. } while (--i >= 0);
  460. return trim(biR);
  461. }
  462. #ifdef CONFIG_BIGINT_MONTGOMERY
  463. /**
  464. * There is a need for the value of integer N' such that B^-1(B-1)-N^-1N'=1,
  465. * where B^-1(B-1) mod N=1. Actually, only the least significant part of
  466. * N' is needed, hence the definition N0'=N' mod b. We reproduce below the
  467. * simple algorithm from an article by Dusse and Kaliski to efficiently
  468. * find N0' from N0 and b */
  469. static comp modular_inverse(bigint *bim)
  470. {
  471. int i;
  472. comp t = 1;
  473. comp two_2_i_minus_1 = 2; /* 2^(i-1) */
  474. long_comp two_2_i = 4; /* 2^i */
  475. comp N = bim->comps[0];
  476. for (i = 2; i <= COMP_BIT_SIZE; i++)
  477. {
  478. if ((long_comp)N*t%two_2_i >= two_2_i_minus_1)
  479. {
  480. t += two_2_i_minus_1;
  481. }
  482. two_2_i_minus_1 <<= 1;
  483. two_2_i <<= 1;
  484. }
  485. return (comp)(COMP_RADIX-t);
  486. }
  487. #endif
  488. #if defined(CONFIG_BIGINT_KARATSUBA) || defined(CONFIG_BIGINT_BARRETT) || \
  489. defined(CONFIG_BIGINT_MONTGOMERY)
  490. /**
  491. * Take each component and shift down (in terms of components)
  492. */
  493. static bigint *comp_right_shift(bigint *biR, int num_shifts)
  494. {
  495. int i = biR->size-num_shifts;
  496. comp *x = biR->comps;
  497. comp *y = &biR->comps[num_shifts];
  498. check(biR);
  499. if (i <= 0) /* have we completely right shifted? */
  500. {
  501. biR->comps[0] = 0; /* return 0 */
  502. biR->size = 1;
  503. return biR;
  504. }
  505. do
  506. {
  507. *x++ = *y++;
  508. } while (--i > 0);
  509. biR->size -= num_shifts;
  510. return biR;
  511. }
  512. /**
  513. * Take each component and shift it up (in terms of components)
  514. */
  515. static bigint *comp_left_shift(bigint *biR, int num_shifts)
  516. {
  517. int i = biR->size-1;
  518. comp *x, *y;
  519. check(biR);
  520. if (num_shifts <= 0)
  521. {
  522. return biR;
  523. }
  524. more_comps(biR, biR->size + num_shifts);
  525. x = &biR->comps[i+num_shifts];
  526. y = &biR->comps[i];
  527. do
  528. {
  529. *x-- = *y--;
  530. } while (i--);
  531. memset(biR->comps, 0, num_shifts*COMP_BYTE_SIZE); /* zero LS comps */
  532. return biR;
  533. }
  534. #endif
  535. /**
  536. * @brief Allow a binary sequence to be imported as a bigint.
  537. * @param ctx [in] The bigint session context.
  538. * @param data [in] The data to be converted.
  539. * @param size [in] The number of bytes of data.
  540. * @return A bigint representing this data.
  541. */
  542. bigint *bi_import(BI_CTX *ctx, const uint8_t *data, int size)
  543. {
  544. bigint *biR = alloc(ctx, (size+COMP_BYTE_SIZE-1)/COMP_BYTE_SIZE);
  545. int i, j = 0, offset = 0;
  546. memset(biR->comps, 0, biR->size*COMP_BYTE_SIZE);
  547. for (i = size-1; i >= 0; i--)
  548. {
  549. biR->comps[offset] += data[i] << (j*8);
  550. if (++j == COMP_BYTE_SIZE)
  551. {
  552. j = 0;
  553. offset ++;
  554. }
  555. }
  556. return trim(biR);
  557. }
  558. #ifdef CONFIG_SSL_FULL_MODE
  559. /**
  560. * @brief The testharness uses this code to import text hex-streams and
  561. * convert them into bigints.
  562. * @param ctx [in] The bigint session context.
  563. * @param data [in] A string consisting of hex characters. The characters must
  564. * be in upper case.
  565. * @return A bigint representing this data.
  566. */
  567. bigint *bi_str_import(BI_CTX *ctx, const char *data)
  568. {
  569. int size = strlen(data);
  570. bigint *biR = alloc(ctx, (size+COMP_NUM_NIBBLES-1)/COMP_NUM_NIBBLES);
  571. int i, j = 0, offset = 0;
  572. memset(biR->comps, 0, biR->size*COMP_BYTE_SIZE);
  573. for (i = size-1; i >= 0; i--)
  574. {
  575. int num = (data[i] <= '9') ? (data[i] - '0') : (data[i] - 'A' + 10);
  576. biR->comps[offset] += num << (j*4);
  577. if (++j == COMP_NUM_NIBBLES)
  578. {
  579. j = 0;
  580. offset ++;
  581. }
  582. }
  583. return biR;
  584. }
  585. void bi_print(const char *label, bigint *x)
  586. {
  587. int i, j;
  588. if (x == NULL)
  589. {
  590. printf("%s: (null)\n", label);
  591. return;
  592. }
  593. printf("%s: (size %d)\n", label, x->size);
  594. for (i = x->size-1; i >= 0; i--)
  595. {
  596. for (j = COMP_NUM_NIBBLES-1; j >= 0; j--)
  597. {
  598. comp mask = 0x0f << (j*4);
  599. comp num = (x->comps[i] & mask) >> (j*4);
  600. putc((num <= 9) ? (num + '0') : (num + 'A' - 10), stdout);
  601. }
  602. }
  603. printf("\n");
  604. }
  605. #endif
  606. /**
  607. * @brief Take a bigint and convert it into a byte sequence.
  608. *
  609. * This is useful after a decrypt operation.
  610. * @param ctx [in] The bigint session context.
  611. * @param x [in] The bigint to be converted.
  612. * @param data [out] The converted data as a byte stream.
  613. * @param size [in] The maximum size of the byte stream. Unused bytes will be
  614. * zeroed.
  615. */
  616. void bi_export(BI_CTX *ctx, bigint *x, uint8_t *data, int size)
  617. {
  618. int i, j, k = size-1;
  619. check(x);
  620. memset(data, 0, size); /* ensure all leading 0's are cleared */
  621. for (i = 0; i < x->size; i++)
  622. {
  623. for (j = 0; j < COMP_BYTE_SIZE; j++)
  624. {
  625. comp mask = 0xff << (j*8);
  626. int num = (x->comps[i] & mask) >> (j*8);
  627. data[k--] = num;
  628. if (k < 0)
  629. {
  630. goto buf_done;
  631. }
  632. }
  633. }
  634. buf_done:
  635. bi_free(ctx, x);
  636. }
  637. /**
  638. * @brief Pre-calculate some of the expensive steps in reduction.
  639. *
  640. * This function should only be called once (normally when a session starts).
  641. * When the session is over, bi_free_mod() should be called. bi_mod_power()
  642. * relies on this function being called.
  643. * @param ctx [in] The bigint session context.
  644. * @param bim [in] The bigint modulus that will be used.
  645. * @param mod_offset [in] There are three moduluii that can be stored - the
  646. * standard modulus, and its two primes p and q. This offset refers to which
  647. * modulus we are referring to.
  648. * @see bi_free_mod(), bi_mod_power().
  649. */
  650. void bi_set_mod(BI_CTX *ctx, bigint *bim, int mod_offset)
  651. {
  652. int k = bim->size;
  653. comp d = (comp)((long_comp)COMP_RADIX/(bim->comps[k-1]+1));
  654. #ifdef CONFIG_BIGINT_MONTGOMERY
  655. bigint *R, *R2;
  656. #endif
  657. ctx->bi_mod[mod_offset] = bim;
  658. bi_permanent(ctx->bi_mod[mod_offset]);
  659. ctx->bi_normalised_mod[mod_offset] = bi_int_multiply(ctx, bim, d);
  660. bi_permanent(ctx->bi_normalised_mod[mod_offset]);
  661. #if defined(CONFIG_BIGINT_MONTGOMERY)
  662. /* set montgomery variables */
  663. R = comp_left_shift(bi_clone(ctx, ctx->bi_radix), k-1); /* R */
  664. R2 = comp_left_shift(bi_clone(ctx, ctx->bi_radix), k*2-1); /* R^2 */
  665. ctx->bi_RR_mod_m[mod_offset] = bi_mod(ctx, R2); /* R^2 mod m */
  666. ctx->bi_R_mod_m[mod_offset] = bi_mod(ctx, R); /* R mod m */
  667. bi_permanent(ctx->bi_RR_mod_m[mod_offset]);
  668. bi_permanent(ctx->bi_R_mod_m[mod_offset]);
  669. ctx->N0_dash[mod_offset] = modular_inverse(ctx->bi_mod[mod_offset]);
  670. #elif defined (CONFIG_BIGINT_BARRETT)
  671. ctx->bi_mu[mod_offset] =
  672. bi_divide(ctx, comp_left_shift(
  673. bi_clone(ctx, ctx->bi_radix), k*2-1), ctx->bi_mod[mod_offset], 0);
  674. bi_permanent(ctx->bi_mu[mod_offset]);
  675. #endif
  676. }
  677. /**
  678. * @brief Used when cleaning various bigints at the end of a session.
  679. * @param ctx [in] The bigint session context.
  680. * @param mod_offset [in] The offset to use.
  681. * @see bi_set_mod().
  682. */
  683. void bi_free_mod(BI_CTX *ctx, int mod_offset)
  684. {
  685. bi_depermanent(ctx->bi_mod[mod_offset]);
  686. bi_free(ctx, ctx->bi_mod[mod_offset]);
  687. #if defined (CONFIG_BIGINT_MONTGOMERY)
  688. bi_depermanent(ctx->bi_RR_mod_m[mod_offset]);
  689. bi_depermanent(ctx->bi_R_mod_m[mod_offset]);
  690. bi_free(ctx, ctx->bi_RR_mod_m[mod_offset]);
  691. bi_free(ctx, ctx->bi_R_mod_m[mod_offset]);
  692. #elif defined(CONFIG_BIGINT_BARRETT)
  693. bi_depermanent(ctx->bi_mu[mod_offset]);
  694. bi_free(ctx, ctx->bi_mu[mod_offset]);
  695. #endif
  696. bi_depermanent(ctx->bi_normalised_mod[mod_offset]);
  697. bi_free(ctx, ctx->bi_normalised_mod[mod_offset]);
  698. }
  699. /**
  700. * Perform a standard multiplication between two bigints.
  701. *
  702. * Barrett reduction has no need for some parts of the product, so ignore bits
  703. * of the multiply. This routine gives Barrett its big performance
  704. * improvements over Classical/Montgomery reduction methods.
  705. */
  706. static bigint *regular_multiply(BI_CTX *ctx, bigint *bia, bigint *bib,
  707. int inner_partial, int outer_partial)
  708. {
  709. int i = 0, j;
  710. int n = bia->size;
  711. int t = bib->size;
  712. bigint *biR = alloc(ctx, n + t);
  713. comp *sr = biR->comps;
  714. comp *sa = bia->comps;
  715. comp *sb = bib->comps;
  716. check(bia);
  717. check(bib);
  718. /* clear things to start with */
  719. memset(biR->comps, 0, ((n+t)*COMP_BYTE_SIZE));
  720. do
  721. {
  722. long_comp tmp;
  723. comp carry = 0;
  724. int r_index = i;
  725. j = 0;
  726. if (outer_partial && outer_partial-i > 0 && outer_partial < n)
  727. {
  728. r_index = outer_partial-1;
  729. j = outer_partial-i-1;
  730. }
  731. do
  732. {
  733. if (inner_partial && r_index >= inner_partial)
  734. {
  735. break;
  736. }
  737. tmp = sr[r_index] + ((long_comp)sa[j])*sb[i] + carry;
  738. sr[r_index++] = (comp)tmp; /* downsize */
  739. carry = tmp >> COMP_BIT_SIZE;
  740. } while (++j < n);
  741. sr[r_index] = carry;
  742. } while (++i < t);
  743. bi_free(ctx, bia);
  744. bi_free(ctx, bib);
  745. return trim(biR);
  746. }
  747. #ifdef CONFIG_BIGINT_KARATSUBA
  748. /*
  749. * Karatsuba improves on regular multiplication due to only 3 multiplications
  750. * being done instead of 4. The additional additions/subtractions are O(N)
  751. * rather than O(N^2) and so for big numbers it saves on a few operations
  752. */
  753. static bigint *karatsuba(BI_CTX *ctx, bigint *bia, bigint *bib, int is_square)
  754. {
  755. bigint *x0, *x1;
  756. bigint *p0, *p1, *p2;
  757. int m;
  758. if (is_square)
  759. {
  760. m = (bia->size + 1)/2;
  761. }
  762. else
  763. {
  764. m = (max(bia->size, bib->size) + 1)/2;
  765. }
  766. x0 = bi_clone(ctx, bia);
  767. x0->size = m;
  768. x1 = bi_clone(ctx, bia);
  769. comp_right_shift(x1, m);
  770. bi_free(ctx, bia);
  771. /* work out the 3 partial products */
  772. if (is_square)
  773. {
  774. p0 = bi_square(ctx, bi_copy(x0));
  775. p2 = bi_square(ctx, bi_copy(x1));
  776. p1 = bi_square(ctx, bi_add(ctx, x0, x1));
  777. }
  778. else /* normal multiply */
  779. {
  780. bigint *y0, *y1;
  781. y0 = bi_clone(ctx, bib);
  782. y0->size = m;
  783. y1 = bi_clone(ctx, bib);
  784. comp_right_shift(y1, m);
  785. bi_free(ctx, bib);
  786. p0 = bi_multiply(ctx, bi_copy(x0), bi_copy(y0));
  787. p2 = bi_multiply(ctx, bi_copy(x1), bi_copy(y1));
  788. p1 = bi_multiply(ctx, bi_add(ctx, x0, x1), bi_add(ctx, y0, y1));
  789. }
  790. p1 = bi_subtract(ctx,
  791. bi_subtract(ctx, p1, bi_copy(p2), NULL), bi_copy(p0), NULL);
  792. comp_left_shift(p1, m);
  793. comp_left_shift(p2, 2*m);
  794. return bi_add(ctx, p1, bi_add(ctx, p0, p2));
  795. }
  796. #endif
  797. /**
  798. * @brief Perform a multiplication operation between two bigints.
  799. * @param ctx [in] The bigint session context.
  800. * @param bia [in] A bigint.
  801. * @param bib [in] Another bigint.
  802. * @return The result of the multiplication.
  803. */
  804. bigint *bi_multiply(BI_CTX *ctx, bigint *bia, bigint *bib)
  805. {
  806. check(bia);
  807. check(bib);
  808. #ifdef CONFIG_BIGINT_KARATSUBA
  809. if (min(bia->size, bib->size) < MUL_KARATSUBA_THRESH)
  810. {
  811. return regular_multiply(ctx, bia, bib, 0, 0);
  812. }
  813. return karatsuba(ctx, bia, bib, 0);
  814. #else
  815. return regular_multiply(ctx, bia, bib, 0, 0);
  816. #endif
  817. }
  818. #ifdef CONFIG_BIGINT_SQUARE
  819. /*
  820. * Perform the actual square operion. It takes into account overflow.
  821. */
  822. static bigint *regular_square(BI_CTX *ctx, bigint *bi)
  823. {
  824. int t = bi->size;
  825. int i = 0, j;
  826. bigint *biR = alloc(ctx, t*2+1);
  827. comp *w = biR->comps;
  828. comp *x = bi->comps;
  829. long_comp carry;
  830. memset(w, 0, biR->size*COMP_BYTE_SIZE);
  831. do
  832. {
  833. long_comp tmp = w[2*i] + (long_comp)x[i]*x[i];
  834. w[2*i] = (comp)tmp;
  835. carry = tmp >> COMP_BIT_SIZE;
  836. for (j = i+1; j < t; j++)
  837. {
  838. uint8_t c = 0;
  839. long_comp xx = (long_comp)x[i]*x[j];
  840. if ((COMP_MAX-xx) < xx)
  841. c = 1;
  842. tmp = (xx<<1);
  843. if ((COMP_MAX-tmp) < w[i+j])
  844. c = 1;
  845. tmp += w[i+j];
  846. if ((COMP_MAX-tmp) < carry)
  847. c = 1;
  848. tmp += carry;
  849. w[i+j] = (comp)tmp;
  850. carry = tmp >> COMP_BIT_SIZE;
  851. if (c)
  852. carry += COMP_RADIX;
  853. }
  854. tmp = w[i+t] + carry;
  855. w[i+t] = (comp)tmp;
  856. w[i+t+1] = tmp >> COMP_BIT_SIZE;
  857. } while (++i < t);
  858. bi_free(ctx, bi);
  859. return trim(biR);
  860. }
  861. /**
  862. * @brief Perform a square operation on a bigint.
  863. * @param ctx [in] The bigint session context.
  864. * @param bia [in] A bigint.
  865. * @return The result of the multiplication.
  866. */
  867. bigint *bi_square(BI_CTX *ctx, bigint *bia)
  868. {
  869. check(bia);
  870. #ifdef CONFIG_BIGINT_KARATSUBA
  871. if (bia->size < SQU_KARATSUBA_THRESH)
  872. {
  873. return regular_square(ctx, bia);
  874. }
  875. return karatsuba(ctx, bia, NULL, 1);
  876. #else
  877. return regular_square(ctx, bia);
  878. #endif
  879. }
  880. #endif
  881. /**
  882. * @brief Compare two bigints.
  883. * @param bia [in] A bigint.
  884. * @param bib [in] Another bigint.
  885. * @return -1 if smaller, 1 if larger and 0 if equal.
  886. */
  887. int bi_compare(bigint *bia, bigint *bib)
  888. {
  889. int r, i;
  890. check(bia);
  891. check(bib);
  892. if (bia->size > bib->size)
  893. r = 1;
  894. else if (bia->size < bib->size)
  895. r = -1;
  896. else
  897. {
  898. comp *a = bia->comps;
  899. comp *b = bib->comps;
  900. /* Same number of components. Compare starting from the high end
  901. * and working down. */
  902. r = 0;
  903. i = bia->size - 1;
  904. do
  905. {
  906. if (a[i] > b[i])
  907. {
  908. r = 1;
  909. break;
  910. }
  911. else if (a[i] < b[i])
  912. {
  913. r = -1;
  914. break;
  915. }
  916. } while (--i >= 0);
  917. }
  918. return r;
  919. }
  920. /*
  921. * Allocate and zero more components. Does not consume bi.
  922. */
  923. static void more_comps(bigint *bi, int n)
  924. {
  925. if (n > bi->max_comps)
  926. {
  927. bi->max_comps = max(bi->max_comps * 2, n);
  928. bi->comps = (comp*)realloc(bi->comps, bi->max_comps * COMP_BYTE_SIZE);
  929. }
  930. if (n > bi->size)
  931. {
  932. memset(&bi->comps[bi->size], 0, (n-bi->size)*COMP_BYTE_SIZE);
  933. }
  934. bi->size = n;
  935. }
  936. /*
  937. * Make a new empty bigint. It may just use an old one if one is available.
  938. * Otherwise get one off the heap.
  939. */
  940. static bigint *alloc(BI_CTX *ctx, int size)
  941. {
  942. bigint *biR;
  943. /* Can we recycle an old bigint? */
  944. if (ctx->free_list != NULL)
  945. {
  946. biR = ctx->free_list;
  947. ctx->free_list = biR->next;
  948. ctx->free_count--;
  949. if (biR->refs != 0)
  950. {
  951. #ifdef CONFIG_SSL_FULL_MODE
  952. printf("alloc: refs was not 0\n");
  953. #endif
  954. abort(); /* create a stack trace from a core dump */
  955. }
  956. more_comps(biR, size);
  957. }
  958. else
  959. {
  960. /* No free bigints available - create a new one. */
  961. biR = (bigint *)malloc(sizeof(bigint));
  962. biR->comps = (comp*)malloc(size * COMP_BYTE_SIZE);
  963. biR->max_comps = size; /* give some space to spare */
  964. }
  965. biR->size = size;
  966. biR->refs = 1;
  967. biR->next = NULL;
  968. ctx->active_count++;
  969. return biR;
  970. }
  971. /*
  972. * Work out the highest '1' bit in an exponent. Used when doing sliding-window
  973. * exponentiation.
  974. */
  975. static int find_max_exp_index(bigint *biexp)
  976. {
  977. int i = COMP_BIT_SIZE-1;
  978. comp shift = COMP_RADIX/2;
  979. comp test = biexp->comps[biexp->size-1]; /* assume no leading zeroes */
  980. check(biexp);
  981. do
  982. {
  983. if (test & shift)
  984. {
  985. return i+(biexp->size-1)*COMP_BIT_SIZE;
  986. }
  987. shift >>= 1;
  988. } while (i-- != 0);
  989. return -1; /* error - must have been a leading 0 */
  990. }
  991. /*
  992. * Is a particular bit is an exponent 1 or 0? Used when doing sliding-window
  993. * exponentiation.
  994. */
  995. static int exp_bit_is_one(bigint *biexp, int offset)
  996. {
  997. comp test = biexp->comps[offset / COMP_BIT_SIZE];
  998. int num_shifts = offset % COMP_BIT_SIZE;
  999. comp shift = 1;
  1000. int i;
  1001. check(biexp);
  1002. for (i = 0; i < num_shifts; i++)
  1003. {
  1004. shift <<= 1;
  1005. }
  1006. return (test & shift) != 0;
  1007. }
  1008. #ifdef CONFIG_BIGINT_CHECK_ON
  1009. /*
  1010. * Perform a sanity check on bi.
  1011. */
  1012. static void check(const bigint *bi)
  1013. {
  1014. if (bi->refs <= 0)
  1015. {
  1016. printf("check: zero or negative refs in bigint\n");
  1017. abort();
  1018. }
  1019. if (bi->next != NULL)
  1020. {
  1021. printf("check: attempt to use a bigint from "
  1022. "the free list\n");
  1023. abort();
  1024. }
  1025. }
  1026. #endif
  1027. /*
  1028. * Delete any leading 0's (and allow for 0).
  1029. */
  1030. static bigint *trim(bigint *bi)
  1031. {
  1032. check(bi);
  1033. while (bi->comps[bi->size-1] == 0 && bi->size > 1)
  1034. {
  1035. bi->size--;
  1036. }
  1037. return bi;
  1038. }
  1039. #if defined(CONFIG_BIGINT_MONTGOMERY)
  1040. /**
  1041. * @brief Perform a single montgomery reduction.
  1042. * @param ctx [in] The bigint session context.
  1043. * @param bixy [in] A bigint.
  1044. * @return The result of the montgomery reduction.
  1045. */
  1046. bigint *bi_mont(BI_CTX *ctx, bigint *bixy)
  1047. {
  1048. int i = 0, n;
  1049. uint8_t mod_offset = ctx->mod_offset;
  1050. bigint *bim = ctx->bi_mod[mod_offset];
  1051. comp mod_inv = ctx->N0_dash[mod_offset];
  1052. check(bixy);
  1053. if (ctx->use_classical) /* just use classical instead */
  1054. {
  1055. return bi_mod(ctx, bixy);
  1056. }
  1057. n = bim->size;
  1058. do
  1059. {
  1060. bixy = bi_add(ctx, bixy, comp_left_shift(
  1061. bi_int_multiply(ctx, bim, bixy->comps[i]*mod_inv), i));
  1062. } while (++i < n);
  1063. comp_right_shift(bixy, n);
  1064. if (bi_compare(bixy, bim) >= 0)
  1065. {
  1066. bixy = bi_subtract(ctx, bixy, bim, NULL);
  1067. }
  1068. return bixy;
  1069. }
  1070. #elif defined(CONFIG_BIGINT_BARRETT)
  1071. /*
  1072. * Stomp on the most significant components to give the illusion of a "mod base
  1073. * radix" operation
  1074. */
  1075. static bigint *comp_mod(bigint *bi, int mod)
  1076. {
  1077. check(bi);
  1078. if (bi->size > mod)
  1079. {
  1080. bi->size = mod;
  1081. }
  1082. return bi;
  1083. }
  1084. /**
  1085. * @brief Perform a single Barrett reduction.
  1086. * @param ctx [in] The bigint session context.
  1087. * @param bi [in] A bigint.
  1088. * @return The result of the Barrett reduction.
  1089. */
  1090. bigint *bi_barrett(BI_CTX *ctx, bigint *bi)
  1091. {
  1092. bigint *q1, *q2, *q3, *r1, *r2, *r;
  1093. uint8_t mod_offset = ctx->mod_offset;
  1094. bigint *bim = ctx->bi_mod[mod_offset];
  1095. int k = bim->size;
  1096. check(bi);
  1097. check(bim);
  1098. /* use Classical method instead - Barrett cannot help here */
  1099. if (bi->size > k*2)
  1100. {
  1101. return bi_mod(ctx, bi);
  1102. }
  1103. q1 = comp_right_shift(bi_clone(ctx, bi), k-1);
  1104. /* do outer partial multiply */
  1105. q2 = regular_multiply(ctx, q1, ctx->bi_mu[mod_offset], 0, k-1);
  1106. q3 = comp_right_shift(q2, k+1);
  1107. r1 = comp_mod(bi, k+1);
  1108. /* do inner partial multiply */
  1109. r2 = comp_mod(regular_multiply(ctx, q3, bim, k+1, 0), k+1);
  1110. r = bi_subtract(ctx, r1, r2, NULL);
  1111. /* if (r >= m) r = r - m; */
  1112. if (bi_compare(r, bim) >= 0)
  1113. {
  1114. r = bi_subtract(ctx, r, bim, NULL);
  1115. }
  1116. return r;
  1117. }
  1118. #endif /* CONFIG_BIGINT_BARRETT */
  1119. #ifdef CONFIG_BIGINT_SLIDING_WINDOW
  1120. /*
  1121. * Work out g1, g3, g5, g7... etc for the sliding-window algorithm
  1122. */
  1123. static void precompute_slide_window(BI_CTX *ctx, int window, bigint *g1)
  1124. {
  1125. int k = 1, i;
  1126. bigint *g2;
  1127. for (i = 0; i < window-1; i++) /* compute 2^(window-1) */
  1128. {
  1129. k <<= 1;
  1130. }
  1131. ctx->g = (bigint **)malloc(k*sizeof(bigint *));
  1132. ctx->g[0] = bi_clone(ctx, g1);
  1133. bi_permanent(ctx->g[0]);
  1134. g2 = bi_residue(ctx, bi_square(ctx, ctx->g[0])); /* g^2 */
  1135. for (i = 1; i < k; i++)
  1136. {
  1137. ctx->g[i] = bi_residue(ctx, bi_multiply(ctx, ctx->g[i-1], bi_copy(g2)));
  1138. bi_permanent(ctx->g[i]);
  1139. }
  1140. bi_free(ctx, g2);
  1141. ctx->window = k;
  1142. }
  1143. #endif
  1144. /**
  1145. * @brief Perform a modular exponentiation.
  1146. *
  1147. * This function requires bi_set_mod() to have been called previously. This is
  1148. * one of the optimisations used for performance.
  1149. * @param ctx [in] The bigint session context.
  1150. * @param bi [in] The bigint on which to perform the mod power operation.
  1151. * @param biexp [in] The bigint exponent.
  1152. * @return The result of the mod exponentiation operation
  1153. * @see bi_set_mod().
  1154. */
  1155. bigint *bi_mod_power(BI_CTX *ctx, bigint *bi, bigint *biexp)
  1156. {
  1157. int i = find_max_exp_index(biexp), j, window_size = 1;
  1158. bigint *biR = int_to_bi(ctx, 1);
  1159. #if defined(CONFIG_BIGINT_MONTGOMERY)
  1160. uint8_t mod_offset = ctx->mod_offset;
  1161. if (!ctx->use_classical)
  1162. {
  1163. /* preconvert */
  1164. bi = bi_mont(ctx,
  1165. bi_multiply(ctx, bi, ctx->bi_RR_mod_m[mod_offset])); /* x' */
  1166. bi_free(ctx, biR);
  1167. biR = ctx->bi_R_mod_m[mod_offset]; /* A */
  1168. }
  1169. #endif
  1170. check(bi);
  1171. check(biexp);
  1172. #ifdef CONFIG_BIGINT_SLIDING_WINDOW
  1173. for (j = i; j > 32; j /= 5) /* work out an optimum size */
  1174. window_size++;
  1175. /* work out the slide constants */
  1176. precompute_slide_window(ctx, window_size, bi);
  1177. #else /* just one constant */
  1178. ctx->g = (bigint **)malloc(sizeof(bigint *));
  1179. ctx->g[0] = bi_clone(ctx, bi);
  1180. ctx->window = 1;
  1181. bi_permanent(ctx->g[0]);
  1182. #endif
  1183. /* if sliding-window is off, then only one bit will be done at a time and
  1184. * will reduce to standard left-to-right exponentiation */
  1185. do
  1186. {
  1187. if (exp_bit_is_one(biexp, i))
  1188. {
  1189. int l = i-window_size+1;
  1190. int part_exp = 0;
  1191. if (l < 0) /* LSB of exponent will always be 1 */
  1192. l = 0;
  1193. else
  1194. {
  1195. while (exp_bit_is_one(biexp, l) == 0)
  1196. l++; /* go back up */
  1197. }
  1198. /* build up the section of the exponent */
  1199. for (j = i; j >= l; j--)
  1200. {
  1201. biR = bi_residue(ctx, bi_square(ctx, biR));
  1202. if (exp_bit_is_one(biexp, j))
  1203. part_exp++;
  1204. if (j != l)
  1205. part_exp <<= 1;
  1206. }
  1207. part_exp = (part_exp-1)/2; /* adjust for array */
  1208. biR = bi_residue(ctx, bi_multiply(ctx, biR, ctx->g[part_exp]));
  1209. i = l-1;
  1210. }
  1211. else /* square it */
  1212. {
  1213. biR = bi_residue(ctx, bi_square(ctx, biR));
  1214. i--;
  1215. }
  1216. } while (i >= 0);
  1217. /* cleanup */
  1218. for (i = 0; i < ctx->window; i++)
  1219. {
  1220. bi_depermanent(ctx->g[i]);
  1221. bi_free(ctx, ctx->g[i]);
  1222. }
  1223. free(ctx->g);
  1224. bi_free(ctx, bi);
  1225. bi_free(ctx, biexp);
  1226. #if defined CONFIG_BIGINT_MONTGOMERY
  1227. return ctx->use_classical ? biR : bi_mont(ctx, biR); /* convert back */
  1228. #else /* CONFIG_BIGINT_CLASSICAL or CONFIG_BIGINT_BARRETT */
  1229. return biR;
  1230. #endif
  1231. }
  1232. #ifdef CONFIG_SSL_CERT_VERIFICATION
  1233. /**
  1234. * @brief Perform a modular exponentiation using a temporary modulus.
  1235. *
  1236. * We need this function to check the signatures of certificates. The modulus
  1237. * of this function is temporary as it's just used for authentication.
  1238. * @param ctx [in] The bigint session context.
  1239. * @param bi [in] The bigint to perform the exp/mod.
  1240. * @param bim [in] The temporary modulus.
  1241. * @param biexp [in] The bigint exponent.
  1242. * @return The result of the mod exponentiation operation
  1243. * @see bi_set_mod().
  1244. */
  1245. bigint *bi_mod_power2(BI_CTX *ctx, bigint *bi, bigint *bim, bigint *biexp)
  1246. {
  1247. bigint *biR, *tmp_biR;
  1248. /* Set up a temporary bigint context and transfer what we need between
  1249. * them. We need to do this since we want to keep the original modulus
  1250. * which is already in this context. This operation is only called when
  1251. * doing peer verification, and so is not expensive :-) */
  1252. BI_CTX *tmp_ctx = bi_initialize();
  1253. bi_set_mod(tmp_ctx, bi_clone(tmp_ctx, bim), BIGINT_M_OFFSET);
  1254. tmp_biR = bi_mod_power(tmp_ctx,
  1255. bi_clone(tmp_ctx, bi),
  1256. bi_clone(tmp_ctx, biexp));
  1257. biR = bi_clone(ctx, tmp_biR);
  1258. bi_free(tmp_ctx, tmp_biR);
  1259. bi_free_mod(tmp_ctx, BIGINT_M_OFFSET);
  1260. bi_terminate(tmp_ctx);
  1261. bi_free(ctx, bi);
  1262. bi_free(ctx, bim);
  1263. bi_free(ctx, biexp);
  1264. return biR;
  1265. }
  1266. #endif
  1267. #ifdef CONFIG_BIGINT_CRT
  1268. /**
  1269. * @brief Use the Chinese Remainder Theorem to quickly perform RSA decrypts.
  1270. *
  1271. * @param ctx [in] The bigint session context.
  1272. * @param bi [in] The bigint to perform the exp/mod.
  1273. * @param dP [in] CRT's dP bigint
  1274. * @param dQ [in] CRT's dQ bigint
  1275. * @param p [in] CRT's p bigint
  1276. * @param q [in] CRT's q bigint
  1277. * @param qInv [in] CRT's qInv bigint
  1278. * @return The result of the CRT operation
  1279. */
  1280. bigint *bi_crt(BI_CTX *ctx, bigint *bi,
  1281. bigint *dP, bigint *dQ,
  1282. bigint *p, bigint *q, bigint *qInv)
  1283. {
  1284. bigint *m1, *m2, *h;
  1285. /* Montgomery has a condition the 0 < x, y < m and these products violate
  1286. * that condition. So disable Montgomery when using CRT */
  1287. #if defined(CONFIG_BIGINT_MONTGOMERY)
  1288. ctx->use_classical = 1;
  1289. #endif
  1290. ctx->mod_offset = BIGINT_P_OFFSET;
  1291. m1 = bi_mod_power(ctx, bi_copy(bi), dP);
  1292. ctx->mod_offset = BIGINT_Q_OFFSET;
  1293. m2 = bi_mod_power(ctx, bi, dQ);
  1294. h = bi_subtract(ctx, bi_add(ctx, m1, p), bi_copy(m2), NULL);
  1295. h = bi_multiply(ctx, h, qInv);
  1296. ctx->mod_offset = BIGINT_P_OFFSET;
  1297. h = bi_residue(ctx, h);
  1298. #if defined(CONFIG_BIGINT_MONTGOMERY)
  1299. ctx->use_classical = 0; /* reset for any further operation */
  1300. #endif
  1301. return bi_add(ctx, m2, bi_multiply(ctx, q, h));
  1302. }
  1303. #endif
  1304. /** @} */