bigint.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  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. static bigint *bi_int_divide(BI_CTX *ctx, bigint *biR, comp denom)
  449. {
  450. int i = biR->size - 1;
  451. long_comp r = 0;
  452. check(biR);
  453. do
  454. {
  455. r = (r<<COMP_BIT_SIZE) + biR->comps[i];
  456. biR->comps[i] = (comp)(r / denom);
  457. r %= denom;
  458. } while (--i >= 0);
  459. return trim(biR);
  460. }
  461. #ifdef CONFIG_BIGINT_MONTGOMERY
  462. /**
  463. * There is a need for the value of integer N' such that B^-1(B-1)-N^-1N'=1,
  464. * where B^-1(B-1) mod N=1. Actually, only the least significant part of
  465. * N' is needed, hence the definition N0'=N' mod b. We reproduce below the
  466. * simple algorithm from an article by Dusse and Kaliski to efficiently
  467. * find N0' from N0 and b */
  468. static comp modular_inverse(bigint *bim)
  469. {
  470. int i;
  471. comp t = 1;
  472. comp two_2_i_minus_1 = 2; /* 2^(i-1) */
  473. long_comp two_2_i = 4; /* 2^i */
  474. comp N = bim->comps[0];
  475. for (i = 2; i <= COMP_BIT_SIZE; i++)
  476. {
  477. if ((long_comp)N*t%two_2_i >= two_2_i_minus_1)
  478. {
  479. t += two_2_i_minus_1;
  480. }
  481. two_2_i_minus_1 <<= 1;
  482. two_2_i <<= 1;
  483. }
  484. return (comp)(COMP_RADIX-t);
  485. }
  486. #endif
  487. #if defined(CONFIG_BIGINT_KARATSUBA) || defined(CONFIG_BIGINT_BARRETT) || \
  488. defined(CONFIG_BIGINT_MONTGOMERY)
  489. /**
  490. * Take each component and shift down (in terms of components)
  491. */
  492. static bigint *comp_right_shift(bigint *biR, int num_shifts)
  493. {
  494. int i = biR->size-num_shifts;
  495. comp *x = biR->comps;
  496. comp *y = &biR->comps[num_shifts];
  497. check(biR);
  498. if (i <= 0) /* have we completely right shifted? */
  499. {
  500. biR->comps[0] = 0; /* return 0 */
  501. biR->size = 1;
  502. return biR;
  503. }
  504. do
  505. {
  506. *x++ = *y++;
  507. } while (--i > 0);
  508. biR->size -= num_shifts;
  509. return biR;
  510. }
  511. /**
  512. * Take each component and shift it up (in terms of components)
  513. */
  514. static bigint *comp_left_shift(bigint *biR, int num_shifts)
  515. {
  516. int i = biR->size-1;
  517. comp *x, *y;
  518. check(biR);
  519. if (num_shifts <= 0)
  520. {
  521. return biR;
  522. }
  523. more_comps(biR, biR->size + num_shifts);
  524. x = &biR->comps[i+num_shifts];
  525. y = &biR->comps[i];
  526. do
  527. {
  528. *x-- = *y--;
  529. } while (i--);
  530. memset(biR->comps, 0, num_shifts*COMP_BYTE_SIZE); /* zero LS comps */
  531. return biR;
  532. }
  533. #endif
  534. /**
  535. * @brief Allow a binary sequence to be imported as a bigint.
  536. * @param ctx [in] The bigint session context.
  537. * @param data [in] The data to be converted.
  538. * @param size [in] The number of bytes of data.
  539. * @return A bigint representing this data.
  540. */
  541. bigint *bi_import(BI_CTX *ctx, const uint8_t *data, int size)
  542. {
  543. bigint *biR = alloc(ctx, (size+COMP_BYTE_SIZE-1)/COMP_BYTE_SIZE);
  544. int i, j = 0, offset = 0;
  545. memset(biR->comps, 0, biR->size*COMP_BYTE_SIZE);
  546. for (i = size-1; i >= 0; i--)
  547. {
  548. biR->comps[offset] += data[i] << (j*8);
  549. if (++j == COMP_BYTE_SIZE)
  550. {
  551. j = 0;
  552. offset ++;
  553. }
  554. }
  555. return trim(biR);
  556. }
  557. #ifdef CONFIG_SSL_FULL_MODE
  558. /**
  559. * @brief The testharness uses this code to import text hex-streams and
  560. * convert them into bigints.
  561. * @param ctx [in] The bigint session context.
  562. * @param data [in] A string consisting of hex characters. The characters must
  563. * be in upper case.
  564. * @return A bigint representing this data.
  565. */
  566. bigint *bi_str_import(BI_CTX *ctx, const char *data)
  567. {
  568. int size = strlen(data);
  569. bigint *biR = alloc(ctx, (size+COMP_NUM_NIBBLES-1)/COMP_NUM_NIBBLES);
  570. int i, j = 0, offset = 0;
  571. memset(biR->comps, 0, biR->size*COMP_BYTE_SIZE);
  572. for (i = size-1; i >= 0; i--)
  573. {
  574. int num = (data[i] <= '9') ? (data[i] - '0') : (data[i] - 'A' + 10);
  575. biR->comps[offset] += num << (j*4);
  576. if (++j == COMP_NUM_NIBBLES)
  577. {
  578. j = 0;
  579. offset ++;
  580. }
  581. }
  582. return biR;
  583. }
  584. void bi_print(const char *label, bigint *x)
  585. {
  586. int i, j;
  587. if (x == NULL)
  588. {
  589. printf("%s: (null)\n", label);
  590. return;
  591. }
  592. printf("%s: (size %d)\n", label, x->size);
  593. for (i = x->size-1; i >= 0; i--)
  594. {
  595. for (j = COMP_NUM_NIBBLES-1; j >= 0; j--)
  596. {
  597. comp mask = 0x0f << (j*4);
  598. comp num = (x->comps[i] & mask) >> (j*4);
  599. putc((num <= 9) ? (num + '0') : (num + 'A' - 10), stdout);
  600. }
  601. }
  602. printf("\n");
  603. }
  604. #endif
  605. /**
  606. * @brief Take a bigint and convert it into a byte sequence.
  607. *
  608. * This is useful after a decrypt operation.
  609. * @param ctx [in] The bigint session context.
  610. * @param x [in] The bigint to be converted.
  611. * @param data [out] The converted data as a byte stream.
  612. * @param size [in] The maximum size of the byte stream. Unused bytes will be
  613. * zeroed.
  614. */
  615. void bi_export(BI_CTX *ctx, bigint *x, uint8_t *data, int size)
  616. {
  617. int i, j, k = size-1;
  618. check(x);
  619. memset(data, 0, size); /* ensure all leading 0's are cleared */
  620. for (i = 0; i < x->size; i++)
  621. {
  622. for (j = 0; j < COMP_BYTE_SIZE; j++)
  623. {
  624. comp mask = 0xff << (j*8);
  625. int num = (x->comps[i] & mask) >> (j*8);
  626. data[k--] = num;
  627. if (k < 0)
  628. {
  629. goto buf_done;
  630. }
  631. }
  632. }
  633. buf_done:
  634. bi_free(ctx, x);
  635. }
  636. /**
  637. * @brief Pre-calculate some of the expensive steps in reduction.
  638. *
  639. * This function should only be called once (normally when a session starts).
  640. * When the session is over, bi_free_mod() should be called. bi_mod_power()
  641. * relies on this function being called.
  642. * @param ctx [in] The bigint session context.
  643. * @param bim [in] The bigint modulus that will be used.
  644. * @param mod_offset [in] There are three moduluii that can be stored - the
  645. * standard modulus, and its two primes p and q. This offset refers to which
  646. * modulus we are referring to.
  647. * @see bi_free_mod(), bi_mod_power().
  648. */
  649. void bi_set_mod(BI_CTX *ctx, bigint *bim, int mod_offset)
  650. {
  651. int k = bim->size;
  652. comp d = (comp)((long_comp)COMP_RADIX/(bim->comps[k-1]+1));
  653. #ifdef CONFIG_BIGINT_MONTGOMERY
  654. bigint *R, *R2;
  655. #endif
  656. ctx->bi_mod[mod_offset] = bim;
  657. bi_permanent(ctx->bi_mod[mod_offset]);
  658. ctx->bi_normalised_mod[mod_offset] = bi_int_multiply(ctx, bim, d);
  659. bi_permanent(ctx->bi_normalised_mod[mod_offset]);
  660. #if defined(CONFIG_BIGINT_MONTGOMERY)
  661. /* set montgomery variables */
  662. R = comp_left_shift(bi_clone(ctx, ctx->bi_radix), k-1); /* R */
  663. R2 = comp_left_shift(bi_clone(ctx, ctx->bi_radix), k*2-1); /* R^2 */
  664. ctx->bi_RR_mod_m[mod_offset] = bi_mod(ctx, R2); /* R^2 mod m */
  665. ctx->bi_R_mod_m[mod_offset] = bi_mod(ctx, R); /* R mod m */
  666. bi_permanent(ctx->bi_RR_mod_m[mod_offset]);
  667. bi_permanent(ctx->bi_R_mod_m[mod_offset]);
  668. ctx->N0_dash[mod_offset] = modular_inverse(ctx->bi_mod[mod_offset]);
  669. #elif defined (CONFIG_BIGINT_BARRETT)
  670. ctx->bi_mu[mod_offset] =
  671. bi_divide(ctx, comp_left_shift(
  672. bi_clone(ctx, ctx->bi_radix), k*2-1), ctx->bi_mod[mod_offset], 0);
  673. bi_permanent(ctx->bi_mu[mod_offset]);
  674. #endif
  675. }
  676. /**
  677. * @brief Used when cleaning various bigints at the end of a session.
  678. * @param ctx [in] The bigint session context.
  679. * @param mod_offset [in] The offset to use.
  680. * @see bi_set_mod().
  681. */
  682. void bi_free_mod(BI_CTX *ctx, int mod_offset)
  683. {
  684. bi_depermanent(ctx->bi_mod[mod_offset]);
  685. bi_free(ctx, ctx->bi_mod[mod_offset]);
  686. #if defined (CONFIG_BIGINT_MONTGOMERY)
  687. bi_depermanent(ctx->bi_RR_mod_m[mod_offset]);
  688. bi_depermanent(ctx->bi_R_mod_m[mod_offset]);
  689. bi_free(ctx, ctx->bi_RR_mod_m[mod_offset]);
  690. bi_free(ctx, ctx->bi_R_mod_m[mod_offset]);
  691. #elif defined(CONFIG_BIGINT_BARRETT)
  692. bi_depermanent(ctx->bi_mu[mod_offset]);
  693. bi_free(ctx, ctx->bi_mu[mod_offset]);
  694. #endif
  695. bi_depermanent(ctx->bi_normalised_mod[mod_offset]);
  696. bi_free(ctx, ctx->bi_normalised_mod[mod_offset]);
  697. }
  698. /**
  699. * Perform a standard multiplication between two bigints.
  700. *
  701. * Barrett reduction has no need for some parts of the product, so ignore bits
  702. * of the multiply. This routine gives Barrett its big performance
  703. * improvements over Classical/Montgomery reduction methods.
  704. */
  705. static bigint *regular_multiply(BI_CTX *ctx, bigint *bia, bigint *bib,
  706. int inner_partial, int outer_partial)
  707. {
  708. int i = 0, j;
  709. int n = bia->size;
  710. int t = bib->size;
  711. bigint *biR = alloc(ctx, n + t);
  712. comp *sr = biR->comps;
  713. comp *sa = bia->comps;
  714. comp *sb = bib->comps;
  715. check(bia);
  716. check(bib);
  717. /* clear things to start with */
  718. memset(biR->comps, 0, ((n+t)*COMP_BYTE_SIZE));
  719. do
  720. {
  721. long_comp tmp;
  722. comp carry = 0;
  723. int r_index = i;
  724. j = 0;
  725. if (outer_partial && outer_partial-i > 0 && outer_partial < n)
  726. {
  727. r_index = outer_partial-1;
  728. j = outer_partial-i-1;
  729. }
  730. do
  731. {
  732. if (inner_partial && r_index >= inner_partial)
  733. {
  734. break;
  735. }
  736. tmp = sr[r_index] + ((long_comp)sa[j])*sb[i] + carry;
  737. sr[r_index++] = (comp)tmp; /* downsize */
  738. carry = tmp >> COMP_BIT_SIZE;
  739. } while (++j < n);
  740. sr[r_index] = carry;
  741. } while (++i < t);
  742. bi_free(ctx, bia);
  743. bi_free(ctx, bib);
  744. return trim(biR);
  745. }
  746. #ifdef CONFIG_BIGINT_KARATSUBA
  747. /*
  748. * Karatsuba improves on regular multiplication due to only 3 multiplications
  749. * being done instead of 4. The additional additions/subtractions are O(N)
  750. * rather than O(N^2) and so for big numbers it saves on a few operations
  751. */
  752. static bigint *karatsuba(BI_CTX *ctx, bigint *bia, bigint *bib, int is_square)
  753. {
  754. bigint *x0, *x1;
  755. bigint *p0, *p1, *p2;
  756. int m;
  757. if (is_square)
  758. {
  759. m = (bia->size + 1)/2;
  760. }
  761. else
  762. {
  763. m = (max(bia->size, bib->size) + 1)/2;
  764. }
  765. x0 = bi_clone(ctx, bia);
  766. x0->size = m;
  767. x1 = bi_clone(ctx, bia);
  768. comp_right_shift(x1, m);
  769. bi_free(ctx, bia);
  770. /* work out the 3 partial products */
  771. if (is_square)
  772. {
  773. p0 = bi_square(ctx, bi_copy(x0));
  774. p2 = bi_square(ctx, bi_copy(x1));
  775. p1 = bi_square(ctx, bi_add(ctx, x0, x1));
  776. }
  777. else /* normal multiply */
  778. {
  779. bigint *y0, *y1;
  780. y0 = bi_clone(ctx, bib);
  781. y0->size = m;
  782. y1 = bi_clone(ctx, bib);
  783. comp_right_shift(y1, m);
  784. bi_free(ctx, bib);
  785. p0 = bi_multiply(ctx, bi_copy(x0), bi_copy(y0));
  786. p2 = bi_multiply(ctx, bi_copy(x1), bi_copy(y1));
  787. p1 = bi_multiply(ctx, bi_add(ctx, x0, x1), bi_add(ctx, y0, y1));
  788. }
  789. p1 = bi_subtract(ctx,
  790. bi_subtract(ctx, p1, bi_copy(p2), NULL), bi_copy(p0), NULL);
  791. comp_left_shift(p1, m);
  792. comp_left_shift(p2, 2*m);
  793. return bi_add(ctx, p1, bi_add(ctx, p0, p2));
  794. }
  795. #endif
  796. /**
  797. * @brief Perform a multiplication operation between two bigints.
  798. * @param ctx [in] The bigint session context.
  799. * @param bia [in] A bigint.
  800. * @param bib [in] Another bigint.
  801. * @return The result of the multiplication.
  802. */
  803. bigint *bi_multiply(BI_CTX *ctx, bigint *bia, bigint *bib)
  804. {
  805. check(bia);
  806. check(bib);
  807. #ifdef CONFIG_BIGINT_KARATSUBA
  808. if (min(bia->size, bib->size) < MUL_KARATSUBA_THRESH)
  809. {
  810. return regular_multiply(ctx, bia, bib, 0, 0);
  811. }
  812. return karatsuba(ctx, bia, bib, 0);
  813. #else
  814. return regular_multiply(ctx, bia, bib, 0, 0);
  815. #endif
  816. }
  817. #ifdef CONFIG_BIGINT_SQUARE
  818. /*
  819. * Perform the actual square operion. It takes into account overflow.
  820. */
  821. static bigint *regular_square(BI_CTX *ctx, bigint *bi)
  822. {
  823. int t = bi->size;
  824. int i = 0, j;
  825. bigint *biR = alloc(ctx, t*2+1);
  826. comp *w = biR->comps;
  827. comp *x = bi->comps;
  828. long_comp carry;
  829. memset(w, 0, biR->size*COMP_BYTE_SIZE);
  830. do
  831. {
  832. long_comp tmp = w[2*i] + (long_comp)x[i]*x[i];
  833. w[2*i] = (comp)tmp;
  834. carry = tmp >> COMP_BIT_SIZE;
  835. for (j = i+1; j < t; j++)
  836. {
  837. uint8_t c = 0;
  838. long_comp xx = (long_comp)x[i]*x[j];
  839. if ((COMP_MAX-xx) < xx)
  840. c = 1;
  841. tmp = (xx<<1);
  842. if ((COMP_MAX-tmp) < w[i+j])
  843. c = 1;
  844. tmp += w[i+j];
  845. if ((COMP_MAX-tmp) < carry)
  846. c = 1;
  847. tmp += carry;
  848. w[i+j] = (comp)tmp;
  849. carry = tmp >> COMP_BIT_SIZE;
  850. if (c)
  851. carry += COMP_RADIX;
  852. }
  853. tmp = w[i+t] + carry;
  854. w[i+t] = (comp)tmp;
  855. w[i+t+1] = tmp >> COMP_BIT_SIZE;
  856. } while (++i < t);
  857. bi_free(ctx, bi);
  858. return trim(biR);
  859. }
  860. /**
  861. * @brief Perform a square operation on a bigint.
  862. * @param ctx [in] The bigint session context.
  863. * @param bia [in] A bigint.
  864. * @return The result of the multiplication.
  865. */
  866. bigint *bi_square(BI_CTX *ctx, bigint *bia)
  867. {
  868. check(bia);
  869. #ifdef CONFIG_BIGINT_KARATSUBA
  870. if (bia->size < SQU_KARATSUBA_THRESH)
  871. {
  872. return regular_square(ctx, bia);
  873. }
  874. return karatsuba(ctx, bia, NULL, 1);
  875. #else
  876. return regular_square(ctx, bia);
  877. #endif
  878. }
  879. #endif
  880. /**
  881. * @brief Compare two bigints.
  882. * @param bia [in] A bigint.
  883. * @param bib [in] Another bigint.
  884. * @return -1 if smaller, 1 if larger and 0 if equal.
  885. */
  886. int bi_compare(bigint *bia, bigint *bib)
  887. {
  888. int r, i;
  889. check(bia);
  890. check(bib);
  891. if (bia->size > bib->size)
  892. r = 1;
  893. else if (bia->size < bib->size)
  894. r = -1;
  895. else
  896. {
  897. comp *a = bia->comps;
  898. comp *b = bib->comps;
  899. /* Same number of components. Compare starting from the high end
  900. * and working down. */
  901. r = 0;
  902. i = bia->size - 1;
  903. do
  904. {
  905. if (a[i] > b[i])
  906. {
  907. r = 1;
  908. break;
  909. }
  910. else if (a[i] < b[i])
  911. {
  912. r = -1;
  913. break;
  914. }
  915. } while (--i >= 0);
  916. }
  917. return r;
  918. }
  919. /*
  920. * Allocate and zero more components. Does not consume bi.
  921. */
  922. static void more_comps(bigint *bi, int n)
  923. {
  924. if (n > bi->max_comps)
  925. {
  926. bi->max_comps = max(bi->max_comps * 2, n);
  927. bi->comps = (comp*)realloc(bi->comps, bi->max_comps * COMP_BYTE_SIZE);
  928. }
  929. if (n > bi->size)
  930. {
  931. memset(&bi->comps[bi->size], 0, (n-bi->size)*COMP_BYTE_SIZE);
  932. }
  933. bi->size = n;
  934. }
  935. /*
  936. * Make a new empty bigint. It may just use an old one if one is available.
  937. * Otherwise get one off the heap.
  938. */
  939. static bigint *alloc(BI_CTX *ctx, int size)
  940. {
  941. bigint *biR;
  942. /* Can we recycle an old bigint? */
  943. if (ctx->free_list != NULL)
  944. {
  945. biR = ctx->free_list;
  946. ctx->free_list = biR->next;
  947. ctx->free_count--;
  948. if (biR->refs != 0)
  949. {
  950. #ifdef CONFIG_SSL_FULL_MODE
  951. printf("alloc: refs was not 0\n");
  952. #endif
  953. abort(); /* create a stack trace from a core dump */
  954. }
  955. more_comps(biR, size);
  956. }
  957. else
  958. {
  959. /* No free bigints available - create a new one. */
  960. biR = (bigint *)malloc(sizeof(bigint));
  961. biR->comps = (comp*)malloc(size * COMP_BYTE_SIZE);
  962. biR->max_comps = size; /* give some space to spare */
  963. }
  964. biR->size = size;
  965. biR->refs = 1;
  966. biR->next = NULL;
  967. ctx->active_count++;
  968. return biR;
  969. }
  970. /*
  971. * Work out the highest '1' bit in an exponent. Used when doing sliding-window
  972. * exponentiation.
  973. */
  974. static int find_max_exp_index(bigint *biexp)
  975. {
  976. int i = COMP_BIT_SIZE-1;
  977. comp shift = COMP_RADIX/2;
  978. comp test = biexp->comps[biexp->size-1]; /* assume no leading zeroes */
  979. check(biexp);
  980. do
  981. {
  982. if (test & shift)
  983. {
  984. return i+(biexp->size-1)*COMP_BIT_SIZE;
  985. }
  986. shift >>= 1;
  987. } while (i-- != 0);
  988. return -1; /* error - must have been a leading 0 */
  989. }
  990. /*
  991. * Is a particular bit is an exponent 1 or 0? Used when doing sliding-window
  992. * exponentiation.
  993. */
  994. static int exp_bit_is_one(bigint *biexp, int offset)
  995. {
  996. comp test = biexp->comps[offset / COMP_BIT_SIZE];
  997. int num_shifts = offset % COMP_BIT_SIZE;
  998. comp shift = 1;
  999. int i;
  1000. check(biexp);
  1001. for (i = 0; i < num_shifts; i++)
  1002. {
  1003. shift <<= 1;
  1004. }
  1005. return (test & shift) != 0;
  1006. }
  1007. #ifdef CONFIG_BIGINT_CHECK_ON
  1008. /*
  1009. * Perform a sanity check on bi.
  1010. */
  1011. static void check(const bigint *bi)
  1012. {
  1013. if (bi->refs <= 0)
  1014. {
  1015. printf("check: zero or negative refs in bigint\n");
  1016. abort();
  1017. }
  1018. if (bi->next != NULL)
  1019. {
  1020. printf("check: attempt to use a bigint from "
  1021. "the free list\n");
  1022. abort();
  1023. }
  1024. }
  1025. #endif
  1026. /*
  1027. * Delete any leading 0's (and allow for 0).
  1028. */
  1029. static bigint *trim(bigint *bi)
  1030. {
  1031. check(bi);
  1032. while (bi->comps[bi->size-1] == 0 && bi->size > 1)
  1033. {
  1034. bi->size--;
  1035. }
  1036. return bi;
  1037. }
  1038. #if defined(CONFIG_BIGINT_MONTGOMERY)
  1039. /**
  1040. * @brief Perform a single montgomery reduction.
  1041. * @param ctx [in] The bigint session context.
  1042. * @param bixy [in] A bigint.
  1043. * @return The result of the montgomery reduction.
  1044. */
  1045. bigint *bi_mont(BI_CTX *ctx, bigint *bixy)
  1046. {
  1047. int i = 0, n;
  1048. uint8_t mod_offset = ctx->mod_offset;
  1049. bigint *bim = ctx->bi_mod[mod_offset];
  1050. comp mod_inv = ctx->N0_dash[mod_offset];
  1051. check(bixy);
  1052. if (ctx->use_classical) /* just use classical instead */
  1053. {
  1054. return bi_mod(ctx, bixy);
  1055. }
  1056. n = bim->size;
  1057. do
  1058. {
  1059. bixy = bi_add(ctx, bixy, comp_left_shift(
  1060. bi_int_multiply(ctx, bim, bixy->comps[i]*mod_inv), i));
  1061. } while (++i < n);
  1062. comp_right_shift(bixy, n);
  1063. if (bi_compare(bixy, bim) >= 0)
  1064. {
  1065. bixy = bi_subtract(ctx, bixy, bim, NULL);
  1066. }
  1067. return bixy;
  1068. }
  1069. #elif defined(CONFIG_BIGINT_BARRETT)
  1070. /*
  1071. * Stomp on the most significant components to give the illusion of a "mod base
  1072. * radix" operation
  1073. */
  1074. static bigint *comp_mod(bigint *bi, int mod)
  1075. {
  1076. check(bi);
  1077. if (bi->size > mod)
  1078. {
  1079. bi->size = mod;
  1080. }
  1081. return bi;
  1082. }
  1083. /**
  1084. * @brief Perform a single Barrett reduction.
  1085. * @param ctx [in] The bigint session context.
  1086. * @param bi [in] A bigint.
  1087. * @return The result of the Barrett reduction.
  1088. */
  1089. bigint *bi_barrett(BI_CTX *ctx, bigint *bi)
  1090. {
  1091. bigint *q1, *q2, *q3, *r1, *r2, *r;
  1092. uint8_t mod_offset = ctx->mod_offset;
  1093. bigint *bim = ctx->bi_mod[mod_offset];
  1094. int k = bim->size;
  1095. check(bi);
  1096. check(bim);
  1097. /* use Classical method instead - Barrett cannot help here */
  1098. if (bi->size > k*2)
  1099. {
  1100. return bi_mod(ctx, bi);
  1101. }
  1102. q1 = comp_right_shift(bi_clone(ctx, bi), k-1);
  1103. /* do outer partial multiply */
  1104. q2 = regular_multiply(ctx, q1, ctx->bi_mu[mod_offset], 0, k-1);
  1105. q3 = comp_right_shift(q2, k+1);
  1106. r1 = comp_mod(bi, k+1);
  1107. /* do inner partial multiply */
  1108. r2 = comp_mod(regular_multiply(ctx, q3, bim, k+1, 0), k+1);
  1109. r = bi_subtract(ctx, r1, r2, NULL);
  1110. /* if (r >= m) r = r - m; */
  1111. if (bi_compare(r, bim) >= 0)
  1112. {
  1113. r = bi_subtract(ctx, r, bim, NULL);
  1114. }
  1115. return r;
  1116. }
  1117. #endif /* CONFIG_BIGINT_BARRETT */
  1118. #ifdef CONFIG_BIGINT_SLIDING_WINDOW
  1119. /*
  1120. * Work out g1, g3, g5, g7... etc for the sliding-window algorithm
  1121. */
  1122. static void precompute_slide_window(BI_CTX *ctx, int window, bigint *g1)
  1123. {
  1124. int k = 1, i;
  1125. bigint *g2;
  1126. for (i = 0; i < window-1; i++) /* compute 2^(window-1) */
  1127. {
  1128. k <<= 1;
  1129. }
  1130. ctx->g = (bigint **)malloc(k*sizeof(bigint *));
  1131. ctx->g[0] = bi_clone(ctx, g1);
  1132. bi_permanent(ctx->g[0]);
  1133. g2 = bi_residue(ctx, bi_square(ctx, ctx->g[0])); /* g^2 */
  1134. for (i = 1; i < k; i++)
  1135. {
  1136. ctx->g[i] = bi_residue(ctx, bi_multiply(ctx, ctx->g[i-1], bi_copy(g2)));
  1137. bi_permanent(ctx->g[i]);
  1138. }
  1139. bi_free(ctx, g2);
  1140. ctx->window = k;
  1141. }
  1142. #endif
  1143. /**
  1144. * @brief Perform a modular exponentiation.
  1145. *
  1146. * This function requires bi_set_mod() to have been called previously. This is
  1147. * one of the optimisations used for performance.
  1148. * @param ctx [in] The bigint session context.
  1149. * @param bi [in] The bigint on which to perform the mod power operation.
  1150. * @param biexp [in] The bigint exponent.
  1151. * @return The result of the mod exponentiation operation
  1152. * @see bi_set_mod().
  1153. */
  1154. bigint *bi_mod_power(BI_CTX *ctx, bigint *bi, bigint *biexp)
  1155. {
  1156. int i = find_max_exp_index(biexp), j, window_size = 1;
  1157. bigint *biR = int_to_bi(ctx, 1);
  1158. #if defined(CONFIG_BIGINT_MONTGOMERY)
  1159. uint8_t mod_offset = ctx->mod_offset;
  1160. if (!ctx->use_classical)
  1161. {
  1162. /* preconvert */
  1163. bi = bi_mont(ctx,
  1164. bi_multiply(ctx, bi, ctx->bi_RR_mod_m[mod_offset])); /* x' */
  1165. bi_free(ctx, biR);
  1166. biR = ctx->bi_R_mod_m[mod_offset]; /* A */
  1167. }
  1168. #endif
  1169. check(bi);
  1170. check(biexp);
  1171. #ifdef CONFIG_BIGINT_SLIDING_WINDOW
  1172. for (j = i; j > 32; j /= 5) /* work out an optimum size */
  1173. window_size++;
  1174. /* work out the slide constants */
  1175. precompute_slide_window(ctx, window_size, bi);
  1176. #else /* just one constant */
  1177. ctx->g = (bigint **)malloc(sizeof(bigint *));
  1178. ctx->g[0] = bi_clone(ctx, bi);
  1179. ctx->window = 1;
  1180. bi_permanent(ctx->g[0]);
  1181. #endif
  1182. /* if sliding-window is off, then only one bit will be done at a time and
  1183. * will reduce to standard left-to-right exponentiation */
  1184. do
  1185. {
  1186. if (exp_bit_is_one(biexp, i))
  1187. {
  1188. int l = i-window_size+1;
  1189. int part_exp = 0;
  1190. if (l < 0) /* LSB of exponent will always be 1 */
  1191. l = 0;
  1192. else
  1193. {
  1194. while (exp_bit_is_one(biexp, l) == 0)
  1195. l++; /* go back up */
  1196. }
  1197. /* build up the section of the exponent */
  1198. for (j = i; j >= l; j--)
  1199. {
  1200. biR = bi_residue(ctx, bi_square(ctx, biR));
  1201. if (exp_bit_is_one(biexp, j))
  1202. part_exp++;
  1203. if (j != l)
  1204. part_exp <<= 1;
  1205. }
  1206. part_exp = (part_exp-1)/2; /* adjust for array */
  1207. biR = bi_residue(ctx, bi_multiply(ctx, biR, ctx->g[part_exp]));
  1208. i = l-1;
  1209. }
  1210. else /* square it */
  1211. {
  1212. biR = bi_residue(ctx, bi_square(ctx, biR));
  1213. i--;
  1214. }
  1215. } while (i >= 0);
  1216. /* cleanup */
  1217. for (i = 0; i < ctx->window; i++)
  1218. {
  1219. bi_depermanent(ctx->g[i]);
  1220. bi_free(ctx, ctx->g[i]);
  1221. }
  1222. free(ctx->g);
  1223. bi_free(ctx, bi);
  1224. bi_free(ctx, biexp);
  1225. #if defined CONFIG_BIGINT_MONTGOMERY
  1226. return ctx->use_classical ? biR : bi_mont(ctx, biR); /* convert back */
  1227. #else /* CONFIG_BIGINT_CLASSICAL or CONFIG_BIGINT_BARRETT */
  1228. return biR;
  1229. #endif
  1230. }
  1231. #ifdef CONFIG_SSL_CERT_VERIFICATION
  1232. /**
  1233. * @brief Perform a modular exponentiation using a temporary modulus.
  1234. *
  1235. * We need this function to check the signatures of certificates. The modulus
  1236. * of this function is temporary as it's just used for authentication.
  1237. * @param ctx [in] The bigint session context.
  1238. * @param bi [in] The bigint to perform the exp/mod.
  1239. * @param bim [in] The temporary modulus.
  1240. * @param biexp [in] The bigint exponent.
  1241. * @return The result of the mod exponentiation operation
  1242. * @see bi_set_mod().
  1243. */
  1244. bigint *bi_mod_power2(BI_CTX *ctx, bigint *bi, bigint *bim, bigint *biexp)
  1245. {
  1246. bigint *biR, *tmp_biR;
  1247. /* Set up a temporary bigint context and transfer what we need between
  1248. * them. We need to do this since we want to keep the original modulus
  1249. * which is already in this context. This operation is only called when
  1250. * doing peer verification, and so is not expensive :-) */
  1251. BI_CTX *tmp_ctx = bi_initialize();
  1252. bi_set_mod(tmp_ctx, bi_clone(tmp_ctx, bim), BIGINT_M_OFFSET);
  1253. tmp_biR = bi_mod_power(tmp_ctx,
  1254. bi_clone(tmp_ctx, bi),
  1255. bi_clone(tmp_ctx, biexp));
  1256. biR = bi_clone(ctx, tmp_biR);
  1257. bi_free(tmp_ctx, tmp_biR);
  1258. bi_free_mod(tmp_ctx, BIGINT_M_OFFSET);
  1259. bi_terminate(tmp_ctx);
  1260. bi_free(ctx, bi);
  1261. bi_free(ctx, bim);
  1262. bi_free(ctx, biexp);
  1263. return biR;
  1264. }
  1265. #endif
  1266. #ifdef CONFIG_BIGINT_CRT
  1267. /**
  1268. * @brief Use the Chinese Remainder Theorem to quickly perform RSA decrypts.
  1269. *
  1270. * @param ctx [in] The bigint session context.
  1271. * @param bi [in] The bigint to perform the exp/mod.
  1272. * @param dP [in] CRT's dP bigint
  1273. * @param dQ [in] CRT's dQ bigint
  1274. * @param p [in] CRT's p bigint
  1275. * @param q [in] CRT's q bigint
  1276. * @param qInv [in] CRT's qInv bigint
  1277. * @return The result of the CRT operation
  1278. */
  1279. bigint *bi_crt(BI_CTX *ctx, bigint *bi,
  1280. bigint *dP, bigint *dQ,
  1281. bigint *p, bigint *q, bigint *qInv)
  1282. {
  1283. bigint *m1, *m2, *h;
  1284. /* Montgomery has a condition the 0 < x, y < m and these products violate
  1285. * that condition. So disable Montgomery when using CRT */
  1286. #if defined(CONFIG_BIGINT_MONTGOMERY)
  1287. ctx->use_classical = 1;
  1288. #endif
  1289. ctx->mod_offset = BIGINT_P_OFFSET;
  1290. m1 = bi_mod_power(ctx, bi_copy(bi), dP);
  1291. ctx->mod_offset = BIGINT_Q_OFFSET;
  1292. m2 = bi_mod_power(ctx, bi, dQ);
  1293. h = bi_subtract(ctx, bi_add(ctx, m1, p), bi_copy(m2), NULL);
  1294. h = bi_multiply(ctx, h, qInv);
  1295. ctx->mod_offset = BIGINT_P_OFFSET;
  1296. h = bi_residue(ctx, h);
  1297. #if defined(CONFIG_BIGINT_MONTGOMERY)
  1298. ctx->use_classical = 0; /* reset for any further operation */
  1299. #endif
  1300. return bi_add(ctx, m2, bi_multiply(ctx, q, h));
  1301. }
  1302. #endif
  1303. /** @} */