You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bigint.c 36KB

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