1
0

bigint.c 39 KB

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