bignum.c 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487
  1. /*
  2. * Multi-precision integer library
  3. *
  4. * Copyright The Mbed TLS Contributors
  5. * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  6. */
  7. /*
  8. * The following sources were referenced in the design of this Multi-precision
  9. * Integer library:
  10. *
  11. * [1] Handbook of Applied Cryptography - 1997
  12. * Menezes, van Oorschot and Vanstone
  13. *
  14. * [2] Multi-Precision Math
  15. * Tom St Denis
  16. * https://github.com/libtom/libtommath/blob/develop/tommath.pdf
  17. *
  18. * [3] GNU Multi-Precision Arithmetic Library
  19. * https://gmplib.org/manual/index.html
  20. *
  21. */
  22. #include "common.h"
  23. #if defined(MBEDTLS_BIGNUM_C)
  24. #include "mbedtls/bignum.h"
  25. #include "bignum_core.h"
  26. #include "bignum_internal.h"
  27. #include "bn_mul.h"
  28. #include "mbedtls/platform_util.h"
  29. #include "mbedtls/error.h"
  30. #include "constant_time_internal.h"
  31. #include <limits.h>
  32. #include <string.h>
  33. #include "mbedtls/platform.h"
  34. /*
  35. * Conditionally select an MPI sign in constant time.
  36. * (MPI sign is the field s in mbedtls_mpi. It is unsigned short and only 1 and -1 are valid
  37. * values.)
  38. */
  39. static inline signed short mbedtls_ct_mpi_sign_if(mbedtls_ct_condition_t cond,
  40. signed short sign1, signed short sign2)
  41. {
  42. return (signed short) mbedtls_ct_uint_if(cond, sign1 + 1, sign2 + 1) - 1;
  43. }
  44. /*
  45. * Compare signed values in constant time
  46. */
  47. int mbedtls_mpi_lt_mpi_ct(const mbedtls_mpi *X,
  48. const mbedtls_mpi *Y,
  49. unsigned *ret)
  50. {
  51. mbedtls_ct_condition_t different_sign, X_is_negative, Y_is_negative, result;
  52. if (X->n != Y->n) {
  53. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  54. }
  55. /*
  56. * Set N_is_negative to MBEDTLS_CT_FALSE if N >= 0, MBEDTLS_CT_TRUE if N < 0.
  57. * We know that N->s == 1 if N >= 0 and N->s == -1 if N < 0.
  58. */
  59. X_is_negative = mbedtls_ct_bool((X->s & 2) >> 1);
  60. Y_is_negative = mbedtls_ct_bool((Y->s & 2) >> 1);
  61. /*
  62. * If the signs are different, then the positive operand is the bigger.
  63. * That is if X is negative (X_is_negative == 1), then X < Y is true and it
  64. * is false if X is positive (X_is_negative == 0).
  65. */
  66. different_sign = mbedtls_ct_bool_ne(X_is_negative, Y_is_negative); // true if different sign
  67. result = mbedtls_ct_bool_and(different_sign, X_is_negative);
  68. /*
  69. * Assuming signs are the same, compare X and Y. We switch the comparison
  70. * order if they are negative so that we get the right result, regardles of
  71. * sign.
  72. */
  73. /* This array is used to conditionally swap the pointers in const time */
  74. void * const p[2] = { X->p, Y->p };
  75. size_t i = mbedtls_ct_size_if_else_0(X_is_negative, 1);
  76. mbedtls_ct_condition_t lt = mbedtls_mpi_core_lt_ct(p[i], p[i ^ 1], X->n);
  77. /*
  78. * Store in result iff the signs are the same (i.e., iff different_sign == false). If
  79. * the signs differ, result has already been set, so we don't change it.
  80. */
  81. result = mbedtls_ct_bool_or(result,
  82. mbedtls_ct_bool_and(mbedtls_ct_bool_not(different_sign), lt));
  83. *ret = mbedtls_ct_uint_if_else_0(result, 1);
  84. return 0;
  85. }
  86. /*
  87. * Conditionally assign X = Y, without leaking information
  88. * about whether the assignment was made or not.
  89. * (Leaking information about the respective sizes of X and Y is ok however.)
  90. */
  91. #if defined(_MSC_VER) && defined(MBEDTLS_PLATFORM_IS_WINDOWS_ON_ARM64) && \
  92. (_MSC_FULL_VER < 193131103)
  93. /*
  94. * MSVC miscompiles this function if it's inlined prior to Visual Studio 2022 version 17.1. See:
  95. * https://developercommunity.visualstudio.com/t/c-compiler-miscompiles-part-of-mbedtls-library-on/1646989
  96. */
  97. __declspec(noinline)
  98. #endif
  99. int mbedtls_mpi_safe_cond_assign(mbedtls_mpi *X,
  100. const mbedtls_mpi *Y,
  101. unsigned char assign)
  102. {
  103. int ret = 0;
  104. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, Y->n));
  105. {
  106. mbedtls_ct_condition_t do_assign = mbedtls_ct_bool(assign);
  107. X->s = mbedtls_ct_mpi_sign_if(do_assign, Y->s, X->s);
  108. mbedtls_mpi_core_cond_assign(X->p, Y->p, Y->n, do_assign);
  109. mbedtls_ct_condition_t do_not_assign = mbedtls_ct_bool_not(do_assign);
  110. for (size_t i = Y->n; i < X->n; i++) {
  111. X->p[i] = mbedtls_ct_mpi_uint_if_else_0(do_not_assign, X->p[i]);
  112. }
  113. }
  114. cleanup:
  115. return ret;
  116. }
  117. /*
  118. * Conditionally swap X and Y, without leaking information
  119. * about whether the swap was made or not.
  120. * Here it is not ok to simply swap the pointers, which would lead to
  121. * different memory access patterns when X and Y are used afterwards.
  122. */
  123. int mbedtls_mpi_safe_cond_swap(mbedtls_mpi *X,
  124. mbedtls_mpi *Y,
  125. unsigned char swap)
  126. {
  127. int ret = 0;
  128. int s;
  129. if (X == Y) {
  130. return 0;
  131. }
  132. mbedtls_ct_condition_t do_swap = mbedtls_ct_bool(swap);
  133. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, Y->n));
  134. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(Y, X->n));
  135. s = X->s;
  136. X->s = mbedtls_ct_mpi_sign_if(do_swap, Y->s, X->s);
  137. Y->s = mbedtls_ct_mpi_sign_if(do_swap, s, Y->s);
  138. mbedtls_mpi_core_cond_swap(X->p, Y->p, X->n, do_swap);
  139. cleanup:
  140. return ret;
  141. }
  142. /* Implementation that should never be optimized out by the compiler */
  143. #define mbedtls_mpi_zeroize_and_free(v, n) mbedtls_zeroize_and_free(v, ciL * (n))
  144. /*
  145. * Initialize one MPI
  146. */
  147. void mbedtls_mpi_init(mbedtls_mpi *X)
  148. {
  149. X->s = 1;
  150. X->n = 0;
  151. X->p = NULL;
  152. }
  153. /*
  154. * Unallocate one MPI
  155. */
  156. void mbedtls_mpi_free(mbedtls_mpi *X)
  157. {
  158. if (X == NULL) {
  159. return;
  160. }
  161. if (X->p != NULL) {
  162. mbedtls_mpi_zeroize_and_free(X->p, X->n);
  163. }
  164. X->s = 1;
  165. X->n = 0;
  166. X->p = NULL;
  167. }
  168. /*
  169. * Enlarge to the specified number of limbs
  170. */
  171. int mbedtls_mpi_grow(mbedtls_mpi *X, size_t nblimbs)
  172. {
  173. mbedtls_mpi_uint *p;
  174. if (nblimbs > MBEDTLS_MPI_MAX_LIMBS) {
  175. return MBEDTLS_ERR_MPI_ALLOC_FAILED;
  176. }
  177. if (X->n < nblimbs) {
  178. if ((p = (mbedtls_mpi_uint *) mbedtls_calloc(nblimbs, ciL)) == NULL) {
  179. return MBEDTLS_ERR_MPI_ALLOC_FAILED;
  180. }
  181. if (X->p != NULL) {
  182. memcpy(p, X->p, X->n * ciL);
  183. mbedtls_mpi_zeroize_and_free(X->p, X->n);
  184. }
  185. /* nblimbs fits in n because we ensure that MBEDTLS_MPI_MAX_LIMBS
  186. * fits, and we've checked that nblimbs <= MBEDTLS_MPI_MAX_LIMBS. */
  187. X->n = (unsigned short) nblimbs;
  188. X->p = p;
  189. }
  190. return 0;
  191. }
  192. /*
  193. * Resize down as much as possible,
  194. * while keeping at least the specified number of limbs
  195. */
  196. int mbedtls_mpi_shrink(mbedtls_mpi *X, size_t nblimbs)
  197. {
  198. mbedtls_mpi_uint *p;
  199. size_t i;
  200. if (nblimbs > MBEDTLS_MPI_MAX_LIMBS) {
  201. return MBEDTLS_ERR_MPI_ALLOC_FAILED;
  202. }
  203. /* Actually resize up if there are currently fewer than nblimbs limbs. */
  204. if (X->n <= nblimbs) {
  205. return mbedtls_mpi_grow(X, nblimbs);
  206. }
  207. /* After this point, then X->n > nblimbs and in particular X->n > 0. */
  208. for (i = X->n - 1; i > 0; i--) {
  209. if (X->p[i] != 0) {
  210. break;
  211. }
  212. }
  213. i++;
  214. if (i < nblimbs) {
  215. i = nblimbs;
  216. }
  217. if ((p = (mbedtls_mpi_uint *) mbedtls_calloc(i, ciL)) == NULL) {
  218. return MBEDTLS_ERR_MPI_ALLOC_FAILED;
  219. }
  220. if (X->p != NULL) {
  221. memcpy(p, X->p, i * ciL);
  222. mbedtls_mpi_zeroize_and_free(X->p, X->n);
  223. }
  224. /* i fits in n because we ensure that MBEDTLS_MPI_MAX_LIMBS
  225. * fits, and we've checked that i <= nblimbs <= MBEDTLS_MPI_MAX_LIMBS. */
  226. X->n = (unsigned short) i;
  227. X->p = p;
  228. return 0;
  229. }
  230. /* Resize X to have exactly n limbs and set it to 0. */
  231. static int mbedtls_mpi_resize_clear(mbedtls_mpi *X, size_t limbs)
  232. {
  233. if (limbs == 0) {
  234. mbedtls_mpi_free(X);
  235. return 0;
  236. } else if (X->n == limbs) {
  237. memset(X->p, 0, limbs * ciL);
  238. X->s = 1;
  239. return 0;
  240. } else {
  241. mbedtls_mpi_free(X);
  242. return mbedtls_mpi_grow(X, limbs);
  243. }
  244. }
  245. /*
  246. * Copy the contents of Y into X.
  247. *
  248. * This function is not constant-time. Leading zeros in Y may be removed.
  249. *
  250. * Ensure that X does not shrink. This is not guaranteed by the public API,
  251. * but some code in the bignum module might still rely on this property.
  252. */
  253. int mbedtls_mpi_copy(mbedtls_mpi *X, const mbedtls_mpi *Y)
  254. {
  255. int ret = 0;
  256. size_t i;
  257. if (X == Y) {
  258. return 0;
  259. }
  260. if (Y->n == 0) {
  261. if (X->n != 0) {
  262. X->s = 1;
  263. memset(X->p, 0, X->n * ciL);
  264. }
  265. return 0;
  266. }
  267. for (i = Y->n - 1; i > 0; i--) {
  268. if (Y->p[i] != 0) {
  269. break;
  270. }
  271. }
  272. i++;
  273. X->s = Y->s;
  274. if (X->n < i) {
  275. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, i));
  276. } else {
  277. memset(X->p + i, 0, (X->n - i) * ciL);
  278. }
  279. memcpy(X->p, Y->p, i * ciL);
  280. cleanup:
  281. return ret;
  282. }
  283. /*
  284. * Swap the contents of X and Y
  285. */
  286. void mbedtls_mpi_swap(mbedtls_mpi *X, mbedtls_mpi *Y)
  287. {
  288. mbedtls_mpi T;
  289. memcpy(&T, X, sizeof(mbedtls_mpi));
  290. memcpy(X, Y, sizeof(mbedtls_mpi));
  291. memcpy(Y, &T, sizeof(mbedtls_mpi));
  292. }
  293. static inline mbedtls_mpi_uint mpi_sint_abs(mbedtls_mpi_sint z)
  294. {
  295. if (z >= 0) {
  296. return z;
  297. }
  298. /* Take care to handle the most negative value (-2^(biL-1)) correctly.
  299. * A naive -z would have undefined behavior.
  300. * Write this in a way that makes popular compilers happy (GCC, Clang,
  301. * MSVC). */
  302. return (mbedtls_mpi_uint) 0 - (mbedtls_mpi_uint) z;
  303. }
  304. /* Convert x to a sign, i.e. to 1, if x is positive, or -1, if x is negative.
  305. * This looks awkward but generates smaller code than (x < 0 ? -1 : 1) */
  306. #define TO_SIGN(x) ((mbedtls_mpi_sint) (((mbedtls_mpi_uint) x) >> (biL - 1)) * -2 + 1)
  307. /*
  308. * Set value from integer
  309. */
  310. int mbedtls_mpi_lset(mbedtls_mpi *X, mbedtls_mpi_sint z)
  311. {
  312. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  313. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, 1));
  314. memset(X->p, 0, X->n * ciL);
  315. X->p[0] = mpi_sint_abs(z);
  316. X->s = TO_SIGN(z);
  317. cleanup:
  318. return ret;
  319. }
  320. /*
  321. * Get a specific bit
  322. */
  323. int mbedtls_mpi_get_bit(const mbedtls_mpi *X, size_t pos)
  324. {
  325. if (X->n * biL <= pos) {
  326. return 0;
  327. }
  328. return (X->p[pos / biL] >> (pos % biL)) & 0x01;
  329. }
  330. /*
  331. * Set a bit to a specific value of 0 or 1
  332. */
  333. int mbedtls_mpi_set_bit(mbedtls_mpi *X, size_t pos, unsigned char val)
  334. {
  335. int ret = 0;
  336. size_t off = pos / biL;
  337. size_t idx = pos % biL;
  338. if (val != 0 && val != 1) {
  339. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  340. }
  341. if (X->n * biL <= pos) {
  342. if (val == 0) {
  343. return 0;
  344. }
  345. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, off + 1));
  346. }
  347. X->p[off] &= ~((mbedtls_mpi_uint) 0x01 << idx);
  348. X->p[off] |= (mbedtls_mpi_uint) val << idx;
  349. cleanup:
  350. return ret;
  351. }
  352. /*
  353. * Return the number of less significant zero-bits
  354. */
  355. size_t mbedtls_mpi_lsb(const mbedtls_mpi *X)
  356. {
  357. size_t i;
  358. #if defined(__has_builtin)
  359. #if (MBEDTLS_MPI_UINT_MAX == UINT_MAX) && __has_builtin(__builtin_ctz)
  360. #define mbedtls_mpi_uint_ctz __builtin_ctz
  361. #elif (MBEDTLS_MPI_UINT_MAX == ULONG_MAX) && __has_builtin(__builtin_ctzl)
  362. #define mbedtls_mpi_uint_ctz __builtin_ctzl
  363. #elif (MBEDTLS_MPI_UINT_MAX == ULLONG_MAX) && __has_builtin(__builtin_ctzll)
  364. #define mbedtls_mpi_uint_ctz __builtin_ctzll
  365. #endif
  366. #endif
  367. #if defined(mbedtls_mpi_uint_ctz)
  368. for (i = 0; i < X->n; i++) {
  369. if (X->p[i] != 0) {
  370. return i * biL + mbedtls_mpi_uint_ctz(X->p[i]);
  371. }
  372. }
  373. #else
  374. size_t count = 0;
  375. for (i = 0; i < X->n; i++) {
  376. for (size_t j = 0; j < biL; j++, count++) {
  377. if (((X->p[i] >> j) & 1) != 0) {
  378. return count;
  379. }
  380. }
  381. }
  382. #endif
  383. return 0;
  384. }
  385. /*
  386. * Return the number of bits
  387. */
  388. size_t mbedtls_mpi_bitlen(const mbedtls_mpi *X)
  389. {
  390. return mbedtls_mpi_core_bitlen(X->p, X->n);
  391. }
  392. /*
  393. * Return the total size in bytes
  394. */
  395. size_t mbedtls_mpi_size(const mbedtls_mpi *X)
  396. {
  397. return (mbedtls_mpi_bitlen(X) + 7) >> 3;
  398. }
  399. /*
  400. * Convert an ASCII character to digit value
  401. */
  402. static int mpi_get_digit(mbedtls_mpi_uint *d, int radix, char c)
  403. {
  404. *d = 255;
  405. if (c >= 0x30 && c <= 0x39) {
  406. *d = c - 0x30;
  407. }
  408. if (c >= 0x41 && c <= 0x46) {
  409. *d = c - 0x37;
  410. }
  411. if (c >= 0x61 && c <= 0x66) {
  412. *d = c - 0x57;
  413. }
  414. if (*d >= (mbedtls_mpi_uint) radix) {
  415. return MBEDTLS_ERR_MPI_INVALID_CHARACTER;
  416. }
  417. return 0;
  418. }
  419. /*
  420. * Import from an ASCII string
  421. */
  422. int mbedtls_mpi_read_string(mbedtls_mpi *X, int radix, const char *s)
  423. {
  424. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  425. size_t i, j, slen, n;
  426. int sign = 1;
  427. mbedtls_mpi_uint d;
  428. mbedtls_mpi T;
  429. if (radix < 2 || radix > 16) {
  430. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  431. }
  432. mbedtls_mpi_init(&T);
  433. if (s[0] == 0) {
  434. mbedtls_mpi_free(X);
  435. return 0;
  436. }
  437. if (s[0] == '-') {
  438. ++s;
  439. sign = -1;
  440. }
  441. slen = strlen(s);
  442. if (radix == 16) {
  443. if (slen > SIZE_MAX >> 2) {
  444. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  445. }
  446. n = BITS_TO_LIMBS(slen << 2);
  447. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, n));
  448. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(X, 0));
  449. for (i = slen, j = 0; i > 0; i--, j++) {
  450. MBEDTLS_MPI_CHK(mpi_get_digit(&d, radix, s[i - 1]));
  451. X->p[j / (2 * ciL)] |= d << ((j % (2 * ciL)) << 2);
  452. }
  453. } else {
  454. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(X, 0));
  455. for (i = 0; i < slen; i++) {
  456. MBEDTLS_MPI_CHK(mpi_get_digit(&d, radix, s[i]));
  457. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_int(&T, X, radix));
  458. MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(X, &T, d));
  459. }
  460. }
  461. if (sign < 0 && mbedtls_mpi_bitlen(X) != 0) {
  462. X->s = -1;
  463. }
  464. cleanup:
  465. mbedtls_mpi_free(&T);
  466. return ret;
  467. }
  468. /*
  469. * Helper to write the digits high-order first.
  470. */
  471. static int mpi_write_hlp(mbedtls_mpi *X, int radix,
  472. char **p, const size_t buflen)
  473. {
  474. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  475. mbedtls_mpi_uint r;
  476. size_t length = 0;
  477. char *p_end = *p + buflen;
  478. do {
  479. if (length >= buflen) {
  480. return MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL;
  481. }
  482. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_int(&r, X, radix));
  483. MBEDTLS_MPI_CHK(mbedtls_mpi_div_int(X, NULL, X, radix));
  484. /*
  485. * Write the residue in the current position, as an ASCII character.
  486. */
  487. if (r < 0xA) {
  488. *(--p_end) = (char) ('0' + r);
  489. } else {
  490. *(--p_end) = (char) ('A' + (r - 0xA));
  491. }
  492. length++;
  493. } while (mbedtls_mpi_cmp_int(X, 0) != 0);
  494. memmove(*p, p_end, length);
  495. *p += length;
  496. cleanup:
  497. return ret;
  498. }
  499. /*
  500. * Export into an ASCII string
  501. */
  502. int mbedtls_mpi_write_string(const mbedtls_mpi *X, int radix,
  503. char *buf, size_t buflen, size_t *olen)
  504. {
  505. int ret = 0;
  506. size_t n;
  507. char *p;
  508. mbedtls_mpi T;
  509. if (radix < 2 || radix > 16) {
  510. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  511. }
  512. n = mbedtls_mpi_bitlen(X); /* Number of bits necessary to present `n`. */
  513. if (radix >= 4) {
  514. n >>= 1; /* Number of 4-adic digits necessary to present
  515. * `n`. If radix > 4, this might be a strict
  516. * overapproximation of the number of
  517. * radix-adic digits needed to present `n`. */
  518. }
  519. if (radix >= 16) {
  520. n >>= 1; /* Number of hexadecimal digits necessary to
  521. * present `n`. */
  522. }
  523. n += 1; /* Terminating null byte */
  524. n += 1; /* Compensate for the divisions above, which round down `n`
  525. * in case it's not even. */
  526. n += 1; /* Potential '-'-sign. */
  527. n += (n & 1); /* Make n even to have enough space for hexadecimal writing,
  528. * which always uses an even number of hex-digits. */
  529. if (buflen < n) {
  530. *olen = n;
  531. return MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL;
  532. }
  533. p = buf;
  534. mbedtls_mpi_init(&T);
  535. if (X->s == -1) {
  536. *p++ = '-';
  537. buflen--;
  538. }
  539. if (radix == 16) {
  540. int c;
  541. size_t i, j, k;
  542. for (i = X->n, k = 0; i > 0; i--) {
  543. for (j = ciL; j > 0; j--) {
  544. c = (X->p[i - 1] >> ((j - 1) << 3)) & 0xFF;
  545. if (c == 0 && k == 0 && (i + j) != 2) {
  546. continue;
  547. }
  548. *(p++) = "0123456789ABCDEF" [c / 16];
  549. *(p++) = "0123456789ABCDEF" [c % 16];
  550. k = 1;
  551. }
  552. }
  553. } else {
  554. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&T, X));
  555. if (T.s == -1) {
  556. T.s = 1;
  557. }
  558. MBEDTLS_MPI_CHK(mpi_write_hlp(&T, radix, &p, buflen));
  559. }
  560. *p++ = '\0';
  561. *olen = (size_t) (p - buf);
  562. cleanup:
  563. mbedtls_mpi_free(&T);
  564. return ret;
  565. }
  566. #if defined(MBEDTLS_FS_IO)
  567. /*
  568. * Read X from an opened file
  569. */
  570. int mbedtls_mpi_read_file(mbedtls_mpi *X, int radix, FILE *fin)
  571. {
  572. mbedtls_mpi_uint d;
  573. size_t slen;
  574. char *p;
  575. /*
  576. * Buffer should have space for (short) label and decimal formatted MPI,
  577. * newline characters and '\0'
  578. */
  579. char s[MBEDTLS_MPI_RW_BUFFER_SIZE];
  580. if (radix < 2 || radix > 16) {
  581. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  582. }
  583. memset(s, 0, sizeof(s));
  584. if (fgets(s, sizeof(s) - 1, fin) == NULL) {
  585. return MBEDTLS_ERR_MPI_FILE_IO_ERROR;
  586. }
  587. slen = strlen(s);
  588. if (slen == sizeof(s) - 2) {
  589. return MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL;
  590. }
  591. if (slen > 0 && s[slen - 1] == '\n') {
  592. slen--; s[slen] = '\0';
  593. }
  594. if (slen > 0 && s[slen - 1] == '\r') {
  595. slen--; s[slen] = '\0';
  596. }
  597. p = s + slen;
  598. while (p-- > s) {
  599. if (mpi_get_digit(&d, radix, *p) != 0) {
  600. break;
  601. }
  602. }
  603. return mbedtls_mpi_read_string(X, radix, p + 1);
  604. }
  605. /*
  606. * Write X into an opened file (or stdout if fout == NULL)
  607. */
  608. int mbedtls_mpi_write_file(const char *p, const mbedtls_mpi *X, int radix, FILE *fout)
  609. {
  610. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  611. size_t n, slen, plen;
  612. /*
  613. * Buffer should have space for (short) label and decimal formatted MPI,
  614. * newline characters and '\0'
  615. */
  616. char s[MBEDTLS_MPI_RW_BUFFER_SIZE];
  617. if (radix < 2 || radix > 16) {
  618. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  619. }
  620. memset(s, 0, sizeof(s));
  621. MBEDTLS_MPI_CHK(mbedtls_mpi_write_string(X, radix, s, sizeof(s) - 2, &n));
  622. if (p == NULL) {
  623. p = "";
  624. }
  625. plen = strlen(p);
  626. slen = strlen(s);
  627. s[slen++] = '\r';
  628. s[slen++] = '\n';
  629. if (fout != NULL) {
  630. if (fwrite(p, 1, plen, fout) != plen ||
  631. fwrite(s, 1, slen, fout) != slen) {
  632. return MBEDTLS_ERR_MPI_FILE_IO_ERROR;
  633. }
  634. } else {
  635. mbedtls_printf("%s%s", p, s);
  636. }
  637. cleanup:
  638. return ret;
  639. }
  640. #endif /* MBEDTLS_FS_IO */
  641. /*
  642. * Import X from unsigned binary data, little endian
  643. *
  644. * This function is guaranteed to return an MPI with exactly the necessary
  645. * number of limbs (in particular, it does not skip 0s in the input).
  646. */
  647. int mbedtls_mpi_read_binary_le(mbedtls_mpi *X,
  648. const unsigned char *buf, size_t buflen)
  649. {
  650. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  651. const size_t limbs = CHARS_TO_LIMBS(buflen);
  652. /* Ensure that target MPI has exactly the necessary number of limbs */
  653. MBEDTLS_MPI_CHK(mbedtls_mpi_resize_clear(X, limbs));
  654. MBEDTLS_MPI_CHK(mbedtls_mpi_core_read_le(X->p, X->n, buf, buflen));
  655. cleanup:
  656. /*
  657. * This function is also used to import keys. However, wiping the buffers
  658. * upon failure is not necessary because failure only can happen before any
  659. * input is copied.
  660. */
  661. return ret;
  662. }
  663. /*
  664. * Import X from unsigned binary data, big endian
  665. *
  666. * This function is guaranteed to return an MPI with exactly the necessary
  667. * number of limbs (in particular, it does not skip 0s in the input).
  668. */
  669. int mbedtls_mpi_read_binary(mbedtls_mpi *X, const unsigned char *buf, size_t buflen)
  670. {
  671. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  672. const size_t limbs = CHARS_TO_LIMBS(buflen);
  673. /* Ensure that target MPI has exactly the necessary number of limbs */
  674. MBEDTLS_MPI_CHK(mbedtls_mpi_resize_clear(X, limbs));
  675. MBEDTLS_MPI_CHK(mbedtls_mpi_core_read_be(X->p, X->n, buf, buflen));
  676. cleanup:
  677. /*
  678. * This function is also used to import keys. However, wiping the buffers
  679. * upon failure is not necessary because failure only can happen before any
  680. * input is copied.
  681. */
  682. return ret;
  683. }
  684. /*
  685. * Export X into unsigned binary data, little endian
  686. */
  687. int mbedtls_mpi_write_binary_le(const mbedtls_mpi *X,
  688. unsigned char *buf, size_t buflen)
  689. {
  690. return mbedtls_mpi_core_write_le(X->p, X->n, buf, buflen);
  691. }
  692. /*
  693. * Export X into unsigned binary data, big endian
  694. */
  695. int mbedtls_mpi_write_binary(const mbedtls_mpi *X,
  696. unsigned char *buf, size_t buflen)
  697. {
  698. return mbedtls_mpi_core_write_be(X->p, X->n, buf, buflen);
  699. }
  700. /*
  701. * Left-shift: X <<= count
  702. */
  703. int mbedtls_mpi_shift_l(mbedtls_mpi *X, size_t count)
  704. {
  705. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  706. size_t i;
  707. i = mbedtls_mpi_bitlen(X) + count;
  708. if (X->n * biL < i) {
  709. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, BITS_TO_LIMBS(i)));
  710. }
  711. ret = 0;
  712. mbedtls_mpi_core_shift_l(X->p, X->n, count);
  713. cleanup:
  714. return ret;
  715. }
  716. /*
  717. * Right-shift: X >>= count
  718. */
  719. int mbedtls_mpi_shift_r(mbedtls_mpi *X, size_t count)
  720. {
  721. if (X->n != 0) {
  722. mbedtls_mpi_core_shift_r(X->p, X->n, count);
  723. }
  724. return 0;
  725. }
  726. /*
  727. * Compare unsigned values
  728. */
  729. int mbedtls_mpi_cmp_abs(const mbedtls_mpi *X, const mbedtls_mpi *Y)
  730. {
  731. size_t i, j;
  732. for (i = X->n; i > 0; i--) {
  733. if (X->p[i - 1] != 0) {
  734. break;
  735. }
  736. }
  737. for (j = Y->n; j > 0; j--) {
  738. if (Y->p[j - 1] != 0) {
  739. break;
  740. }
  741. }
  742. /* If i == j == 0, i.e. abs(X) == abs(Y),
  743. * we end up returning 0 at the end of the function. */
  744. if (i > j) {
  745. return 1;
  746. }
  747. if (j > i) {
  748. return -1;
  749. }
  750. for (; i > 0; i--) {
  751. if (X->p[i - 1] > Y->p[i - 1]) {
  752. return 1;
  753. }
  754. if (X->p[i - 1] < Y->p[i - 1]) {
  755. return -1;
  756. }
  757. }
  758. return 0;
  759. }
  760. /*
  761. * Compare signed values
  762. */
  763. int mbedtls_mpi_cmp_mpi(const mbedtls_mpi *X, const mbedtls_mpi *Y)
  764. {
  765. size_t i, j;
  766. for (i = X->n; i > 0; i--) {
  767. if (X->p[i - 1] != 0) {
  768. break;
  769. }
  770. }
  771. for (j = Y->n; j > 0; j--) {
  772. if (Y->p[j - 1] != 0) {
  773. break;
  774. }
  775. }
  776. if (i == 0 && j == 0) {
  777. return 0;
  778. }
  779. if (i > j) {
  780. return X->s;
  781. }
  782. if (j > i) {
  783. return -Y->s;
  784. }
  785. if (X->s > 0 && Y->s < 0) {
  786. return 1;
  787. }
  788. if (Y->s > 0 && X->s < 0) {
  789. return -1;
  790. }
  791. for (; i > 0; i--) {
  792. if (X->p[i - 1] > Y->p[i - 1]) {
  793. return X->s;
  794. }
  795. if (X->p[i - 1] < Y->p[i - 1]) {
  796. return -X->s;
  797. }
  798. }
  799. return 0;
  800. }
  801. /*
  802. * Compare signed values
  803. */
  804. int mbedtls_mpi_cmp_int(const mbedtls_mpi *X, mbedtls_mpi_sint z)
  805. {
  806. mbedtls_mpi Y;
  807. mbedtls_mpi_uint p[1];
  808. *p = mpi_sint_abs(z);
  809. Y.s = TO_SIGN(z);
  810. Y.n = 1;
  811. Y.p = p;
  812. return mbedtls_mpi_cmp_mpi(X, &Y);
  813. }
  814. /*
  815. * Unsigned addition: X = |A| + |B| (HAC 14.7)
  816. */
  817. int mbedtls_mpi_add_abs(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B)
  818. {
  819. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  820. size_t j;
  821. mbedtls_mpi_uint *p;
  822. mbedtls_mpi_uint c;
  823. if (X == B) {
  824. const mbedtls_mpi *T = A; A = X; B = T;
  825. }
  826. if (X != A) {
  827. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(X, A));
  828. }
  829. /*
  830. * X must always be positive as a result of unsigned additions.
  831. */
  832. X->s = 1;
  833. for (j = B->n; j > 0; j--) {
  834. if (B->p[j - 1] != 0) {
  835. break;
  836. }
  837. }
  838. /* Exit early to avoid undefined behavior on NULL+0 when X->n == 0
  839. * and B is 0 (of any size). */
  840. if (j == 0) {
  841. return 0;
  842. }
  843. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, j));
  844. /* j is the number of non-zero limbs of B. Add those to X. */
  845. p = X->p;
  846. c = mbedtls_mpi_core_add(p, p, B->p, j);
  847. p += j;
  848. /* Now propagate any carry */
  849. while (c != 0) {
  850. if (j >= X->n) {
  851. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, j + 1));
  852. p = X->p + j;
  853. }
  854. *p += c; c = (*p < c); j++; p++;
  855. }
  856. cleanup:
  857. return ret;
  858. }
  859. /*
  860. * Unsigned subtraction: X = |A| - |B| (HAC 14.9, 14.10)
  861. */
  862. int mbedtls_mpi_sub_abs(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B)
  863. {
  864. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  865. size_t n;
  866. mbedtls_mpi_uint carry;
  867. for (n = B->n; n > 0; n--) {
  868. if (B->p[n - 1] != 0) {
  869. break;
  870. }
  871. }
  872. if (n > A->n) {
  873. /* B >= (2^ciL)^n > A */
  874. ret = MBEDTLS_ERR_MPI_NEGATIVE_VALUE;
  875. goto cleanup;
  876. }
  877. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, A->n));
  878. /* Set the high limbs of X to match A. Don't touch the lower limbs
  879. * because X might be aliased to B, and we must not overwrite the
  880. * significant digits of B. */
  881. if (A->n > n && A != X) {
  882. memcpy(X->p + n, A->p + n, (A->n - n) * ciL);
  883. }
  884. if (X->n > A->n) {
  885. memset(X->p + A->n, 0, (X->n - A->n) * ciL);
  886. }
  887. carry = mbedtls_mpi_core_sub(X->p, A->p, B->p, n);
  888. if (carry != 0) {
  889. /* Propagate the carry through the rest of X. */
  890. carry = mbedtls_mpi_core_sub_int(X->p + n, X->p + n, carry, X->n - n);
  891. /* If we have further carry/borrow, the result is negative. */
  892. if (carry != 0) {
  893. ret = MBEDTLS_ERR_MPI_NEGATIVE_VALUE;
  894. goto cleanup;
  895. }
  896. }
  897. /* X should always be positive as a result of unsigned subtractions. */
  898. X->s = 1;
  899. cleanup:
  900. return ret;
  901. }
  902. /* Common function for signed addition and subtraction.
  903. * Calculate A + B * flip_B where flip_B is 1 or -1.
  904. */
  905. static int add_sub_mpi(mbedtls_mpi *X,
  906. const mbedtls_mpi *A, const mbedtls_mpi *B,
  907. int flip_B)
  908. {
  909. int ret, s;
  910. s = A->s;
  911. if (A->s * B->s * flip_B < 0) {
  912. int cmp = mbedtls_mpi_cmp_abs(A, B);
  913. if (cmp >= 0) {
  914. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs(X, A, B));
  915. /* If |A| = |B|, the result is 0 and we must set the sign bit
  916. * to +1 regardless of which of A or B was negative. Otherwise,
  917. * since |A| > |B|, the sign is the sign of A. */
  918. X->s = cmp == 0 ? 1 : s;
  919. } else {
  920. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs(X, B, A));
  921. /* Since |A| < |B|, the sign is the opposite of A. */
  922. X->s = -s;
  923. }
  924. } else {
  925. MBEDTLS_MPI_CHK(mbedtls_mpi_add_abs(X, A, B));
  926. X->s = s;
  927. }
  928. cleanup:
  929. return ret;
  930. }
  931. /*
  932. * Signed addition: X = A + B
  933. */
  934. int mbedtls_mpi_add_mpi(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B)
  935. {
  936. return add_sub_mpi(X, A, B, 1);
  937. }
  938. /*
  939. * Signed subtraction: X = A - B
  940. */
  941. int mbedtls_mpi_sub_mpi(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B)
  942. {
  943. return add_sub_mpi(X, A, B, -1);
  944. }
  945. /*
  946. * Signed addition: X = A + b
  947. */
  948. int mbedtls_mpi_add_int(mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_sint b)
  949. {
  950. mbedtls_mpi B;
  951. mbedtls_mpi_uint p[1];
  952. p[0] = mpi_sint_abs(b);
  953. B.s = TO_SIGN(b);
  954. B.n = 1;
  955. B.p = p;
  956. return mbedtls_mpi_add_mpi(X, A, &B);
  957. }
  958. /*
  959. * Signed subtraction: X = A - b
  960. */
  961. int mbedtls_mpi_sub_int(mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_sint b)
  962. {
  963. mbedtls_mpi B;
  964. mbedtls_mpi_uint p[1];
  965. p[0] = mpi_sint_abs(b);
  966. B.s = TO_SIGN(b);
  967. B.n = 1;
  968. B.p = p;
  969. return mbedtls_mpi_sub_mpi(X, A, &B);
  970. }
  971. /*
  972. * Baseline multiplication: X = A * B (HAC 14.12)
  973. */
  974. int mbedtls_mpi_mul_mpi(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B)
  975. {
  976. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  977. size_t i, j;
  978. mbedtls_mpi TA, TB;
  979. int result_is_zero = 0;
  980. mbedtls_mpi_init(&TA);
  981. mbedtls_mpi_init(&TB);
  982. if (X == A) {
  983. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TA, A)); A = &TA;
  984. }
  985. if (X == B) {
  986. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TB, B)); B = &TB;
  987. }
  988. for (i = A->n; i > 0; i--) {
  989. if (A->p[i - 1] != 0) {
  990. break;
  991. }
  992. }
  993. if (i == 0) {
  994. result_is_zero = 1;
  995. }
  996. for (j = B->n; j > 0; j--) {
  997. if (B->p[j - 1] != 0) {
  998. break;
  999. }
  1000. }
  1001. if (j == 0) {
  1002. result_is_zero = 1;
  1003. }
  1004. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, i + j));
  1005. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(X, 0));
  1006. mbedtls_mpi_core_mul(X->p, A->p, i, B->p, j);
  1007. /* If the result is 0, we don't shortcut the operation, which reduces
  1008. * but does not eliminate side channels leaking the zero-ness. We do
  1009. * need to take care to set the sign bit properly since the library does
  1010. * not fully support an MPI object with a value of 0 and s == -1. */
  1011. if (result_is_zero) {
  1012. X->s = 1;
  1013. } else {
  1014. X->s = A->s * B->s;
  1015. }
  1016. cleanup:
  1017. mbedtls_mpi_free(&TB); mbedtls_mpi_free(&TA);
  1018. return ret;
  1019. }
  1020. /*
  1021. * Baseline multiplication: X = A * b
  1022. */
  1023. int mbedtls_mpi_mul_int(mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_uint b)
  1024. {
  1025. size_t n = A->n;
  1026. while (n > 0 && A->p[n - 1] == 0) {
  1027. --n;
  1028. }
  1029. /* The general method below doesn't work if b==0. */
  1030. if (b == 0 || n == 0) {
  1031. return mbedtls_mpi_lset(X, 0);
  1032. }
  1033. /* Calculate A*b as A + A*(b-1) to take advantage of mbedtls_mpi_core_mla */
  1034. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1035. /* In general, A * b requires 1 limb more than b. If
  1036. * A->p[n - 1] * b / b == A->p[n - 1], then A * b fits in the same
  1037. * number of limbs as A and the call to grow() is not required since
  1038. * copy() will take care of the growth if needed. However, experimentally,
  1039. * making the call to grow() unconditional causes slightly fewer
  1040. * calls to calloc() in ECP code, presumably because it reuses the
  1041. * same mpi for a while and this way the mpi is more likely to directly
  1042. * grow to its final size.
  1043. *
  1044. * Note that calculating A*b as 0 + A*b doesn't work as-is because
  1045. * A,X can be the same. */
  1046. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, n + 1));
  1047. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(X, A));
  1048. mbedtls_mpi_core_mla(X->p, X->n, A->p, n, b - 1);
  1049. cleanup:
  1050. return ret;
  1051. }
  1052. /*
  1053. * Unsigned integer divide - double mbedtls_mpi_uint dividend, u1/u0, and
  1054. * mbedtls_mpi_uint divisor, d
  1055. */
  1056. static mbedtls_mpi_uint mbedtls_int_div_int(mbedtls_mpi_uint u1,
  1057. mbedtls_mpi_uint u0,
  1058. mbedtls_mpi_uint d,
  1059. mbedtls_mpi_uint *r)
  1060. {
  1061. #if defined(MBEDTLS_HAVE_UDBL)
  1062. mbedtls_t_udbl dividend, quotient;
  1063. #else
  1064. const mbedtls_mpi_uint radix = (mbedtls_mpi_uint) 1 << biH;
  1065. const mbedtls_mpi_uint uint_halfword_mask = ((mbedtls_mpi_uint) 1 << biH) - 1;
  1066. mbedtls_mpi_uint d0, d1, q0, q1, rAX, r0, quotient;
  1067. mbedtls_mpi_uint u0_msw, u0_lsw;
  1068. size_t s;
  1069. #endif
  1070. /*
  1071. * Check for overflow
  1072. */
  1073. if (0 == d || u1 >= d) {
  1074. if (r != NULL) {
  1075. *r = ~(mbedtls_mpi_uint) 0u;
  1076. }
  1077. return ~(mbedtls_mpi_uint) 0u;
  1078. }
  1079. #if defined(MBEDTLS_HAVE_UDBL)
  1080. dividend = (mbedtls_t_udbl) u1 << biL;
  1081. dividend |= (mbedtls_t_udbl) u0;
  1082. quotient = dividend / d;
  1083. if (quotient > ((mbedtls_t_udbl) 1 << biL) - 1) {
  1084. quotient = ((mbedtls_t_udbl) 1 << biL) - 1;
  1085. }
  1086. if (r != NULL) {
  1087. *r = (mbedtls_mpi_uint) (dividend - (quotient * d));
  1088. }
  1089. return (mbedtls_mpi_uint) quotient;
  1090. #else
  1091. /*
  1092. * Algorithm D, Section 4.3.1 - The Art of Computer Programming
  1093. * Vol. 2 - Seminumerical Algorithms, Knuth
  1094. */
  1095. /*
  1096. * Normalize the divisor, d, and dividend, u0, u1
  1097. */
  1098. s = mbedtls_mpi_core_clz(d);
  1099. d = d << s;
  1100. u1 = u1 << s;
  1101. u1 |= (u0 >> (biL - s)) & (-(mbedtls_mpi_sint) s >> (biL - 1));
  1102. u0 = u0 << s;
  1103. d1 = d >> biH;
  1104. d0 = d & uint_halfword_mask;
  1105. u0_msw = u0 >> biH;
  1106. u0_lsw = u0 & uint_halfword_mask;
  1107. /*
  1108. * Find the first quotient and remainder
  1109. */
  1110. q1 = u1 / d1;
  1111. r0 = u1 - d1 * q1;
  1112. while (q1 >= radix || (q1 * d0 > radix * r0 + u0_msw)) {
  1113. q1 -= 1;
  1114. r0 += d1;
  1115. if (r0 >= radix) {
  1116. break;
  1117. }
  1118. }
  1119. rAX = (u1 * radix) + (u0_msw - q1 * d);
  1120. q0 = rAX / d1;
  1121. r0 = rAX - q0 * d1;
  1122. while (q0 >= radix || (q0 * d0 > radix * r0 + u0_lsw)) {
  1123. q0 -= 1;
  1124. r0 += d1;
  1125. if (r0 >= radix) {
  1126. break;
  1127. }
  1128. }
  1129. if (r != NULL) {
  1130. *r = (rAX * radix + u0_lsw - q0 * d) >> s;
  1131. }
  1132. quotient = q1 * radix + q0;
  1133. return quotient;
  1134. #endif
  1135. }
  1136. /*
  1137. * Division by mbedtls_mpi: A = Q * B + R (HAC 14.20)
  1138. */
  1139. int mbedtls_mpi_div_mpi(mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A,
  1140. const mbedtls_mpi *B)
  1141. {
  1142. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1143. size_t i, n, t, k;
  1144. mbedtls_mpi X, Y, Z, T1, T2;
  1145. mbedtls_mpi_uint TP2[3];
  1146. if (mbedtls_mpi_cmp_int(B, 0) == 0) {
  1147. return MBEDTLS_ERR_MPI_DIVISION_BY_ZERO;
  1148. }
  1149. mbedtls_mpi_init(&X); mbedtls_mpi_init(&Y); mbedtls_mpi_init(&Z);
  1150. mbedtls_mpi_init(&T1);
  1151. /*
  1152. * Avoid dynamic memory allocations for constant-size T2.
  1153. *
  1154. * T2 is used for comparison only and the 3 limbs are assigned explicitly,
  1155. * so nobody increase the size of the MPI and we're safe to use an on-stack
  1156. * buffer.
  1157. */
  1158. T2.s = 1;
  1159. T2.n = sizeof(TP2) / sizeof(*TP2);
  1160. T2.p = TP2;
  1161. if (mbedtls_mpi_cmp_abs(A, B) < 0) {
  1162. if (Q != NULL) {
  1163. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(Q, 0));
  1164. }
  1165. if (R != NULL) {
  1166. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(R, A));
  1167. }
  1168. return 0;
  1169. }
  1170. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&X, A));
  1171. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&Y, B));
  1172. X.s = Y.s = 1;
  1173. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&Z, A->n + 2));
  1174. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&Z, 0));
  1175. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&T1, A->n + 2));
  1176. k = mbedtls_mpi_bitlen(&Y) % biL;
  1177. if (k < biL - 1) {
  1178. k = biL - 1 - k;
  1179. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&X, k));
  1180. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&Y, k));
  1181. } else {
  1182. k = 0;
  1183. }
  1184. n = X.n - 1;
  1185. t = Y.n - 1;
  1186. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&Y, biL * (n - t)));
  1187. while (mbedtls_mpi_cmp_mpi(&X, &Y) >= 0) {
  1188. Z.p[n - t]++;
  1189. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&X, &X, &Y));
  1190. }
  1191. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&Y, biL * (n - t)));
  1192. for (i = n; i > t; i--) {
  1193. if (X.p[i] >= Y.p[t]) {
  1194. Z.p[i - t - 1] = ~(mbedtls_mpi_uint) 0u;
  1195. } else {
  1196. Z.p[i - t - 1] = mbedtls_int_div_int(X.p[i], X.p[i - 1],
  1197. Y.p[t], NULL);
  1198. }
  1199. T2.p[0] = (i < 2) ? 0 : X.p[i - 2];
  1200. T2.p[1] = (i < 1) ? 0 : X.p[i - 1];
  1201. T2.p[2] = X.p[i];
  1202. Z.p[i - t - 1]++;
  1203. do {
  1204. Z.p[i - t - 1]--;
  1205. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&T1, 0));
  1206. T1.p[0] = (t < 1) ? 0 : Y.p[t - 1];
  1207. T1.p[1] = Y.p[t];
  1208. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_int(&T1, &T1, Z.p[i - t - 1]));
  1209. } while (mbedtls_mpi_cmp_mpi(&T1, &T2) > 0);
  1210. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_int(&T1, &Y, Z.p[i - t - 1]));
  1211. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&T1, biL * (i - t - 1)));
  1212. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&X, &X, &T1));
  1213. if (mbedtls_mpi_cmp_int(&X, 0) < 0) {
  1214. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&T1, &Y));
  1215. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&T1, biL * (i - t - 1)));
  1216. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&X, &X, &T1));
  1217. Z.p[i - t - 1]--;
  1218. }
  1219. }
  1220. if (Q != NULL) {
  1221. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(Q, &Z));
  1222. Q->s = A->s * B->s;
  1223. }
  1224. if (R != NULL) {
  1225. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&X, k));
  1226. X.s = A->s;
  1227. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(R, &X));
  1228. if (mbedtls_mpi_cmp_int(R, 0) == 0) {
  1229. R->s = 1;
  1230. }
  1231. }
  1232. cleanup:
  1233. mbedtls_mpi_free(&X); mbedtls_mpi_free(&Y); mbedtls_mpi_free(&Z);
  1234. mbedtls_mpi_free(&T1);
  1235. mbedtls_platform_zeroize(TP2, sizeof(TP2));
  1236. return ret;
  1237. }
  1238. /*
  1239. * Division by int: A = Q * b + R
  1240. */
  1241. int mbedtls_mpi_div_int(mbedtls_mpi *Q, mbedtls_mpi *R,
  1242. const mbedtls_mpi *A,
  1243. mbedtls_mpi_sint b)
  1244. {
  1245. mbedtls_mpi B;
  1246. mbedtls_mpi_uint p[1];
  1247. p[0] = mpi_sint_abs(b);
  1248. B.s = TO_SIGN(b);
  1249. B.n = 1;
  1250. B.p = p;
  1251. return mbedtls_mpi_div_mpi(Q, R, A, &B);
  1252. }
  1253. /*
  1254. * Modulo: R = A mod B
  1255. */
  1256. int mbedtls_mpi_mod_mpi(mbedtls_mpi *R, const mbedtls_mpi *A, const mbedtls_mpi *B)
  1257. {
  1258. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1259. if (mbedtls_mpi_cmp_int(B, 0) < 0) {
  1260. return MBEDTLS_ERR_MPI_NEGATIVE_VALUE;
  1261. }
  1262. MBEDTLS_MPI_CHK(mbedtls_mpi_div_mpi(NULL, R, A, B));
  1263. while (mbedtls_mpi_cmp_int(R, 0) < 0) {
  1264. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(R, R, B));
  1265. }
  1266. while (mbedtls_mpi_cmp_mpi(R, B) >= 0) {
  1267. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(R, R, B));
  1268. }
  1269. cleanup:
  1270. return ret;
  1271. }
  1272. /*
  1273. * Modulo: r = A mod b
  1274. */
  1275. int mbedtls_mpi_mod_int(mbedtls_mpi_uint *r, const mbedtls_mpi *A, mbedtls_mpi_sint b)
  1276. {
  1277. size_t i;
  1278. mbedtls_mpi_uint x, y, z;
  1279. if (b == 0) {
  1280. return MBEDTLS_ERR_MPI_DIVISION_BY_ZERO;
  1281. }
  1282. if (b < 0) {
  1283. return MBEDTLS_ERR_MPI_NEGATIVE_VALUE;
  1284. }
  1285. /*
  1286. * handle trivial cases
  1287. */
  1288. if (b == 1 || A->n == 0) {
  1289. *r = 0;
  1290. return 0;
  1291. }
  1292. if (b == 2) {
  1293. *r = A->p[0] & 1;
  1294. return 0;
  1295. }
  1296. /*
  1297. * general case
  1298. */
  1299. for (i = A->n, y = 0; i > 0; i--) {
  1300. x = A->p[i - 1];
  1301. y = (y << biH) | (x >> biH);
  1302. z = y / b;
  1303. y -= z * b;
  1304. x <<= biH;
  1305. y = (y << biH) | (x >> biH);
  1306. z = y / b;
  1307. y -= z * b;
  1308. }
  1309. /*
  1310. * If A is negative, then the current y represents a negative value.
  1311. * Flipping it to the positive side.
  1312. */
  1313. if (A->s < 0 && y != 0) {
  1314. y = b - y;
  1315. }
  1316. *r = y;
  1317. return 0;
  1318. }
  1319. /*
  1320. * Warning! If the parameter E_public has MBEDTLS_MPI_IS_PUBLIC as its value,
  1321. * this function is not constant time with respect to the exponent (parameter E).
  1322. */
  1323. static int mbedtls_mpi_exp_mod_optionally_safe(mbedtls_mpi *X, const mbedtls_mpi *A,
  1324. const mbedtls_mpi *E, int E_public,
  1325. const mbedtls_mpi *N, mbedtls_mpi *prec_RR)
  1326. {
  1327. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1328. if (mbedtls_mpi_cmp_int(N, 0) <= 0 || (N->p[0] & 1) == 0) {
  1329. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  1330. }
  1331. if (mbedtls_mpi_cmp_int(E, 0) < 0) {
  1332. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  1333. }
  1334. if (mbedtls_mpi_bitlen(E) > MBEDTLS_MPI_MAX_BITS ||
  1335. mbedtls_mpi_bitlen(N) > MBEDTLS_MPI_MAX_BITS) {
  1336. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  1337. }
  1338. /*
  1339. * Ensure that the exponent that we are passing to the core is not NULL.
  1340. */
  1341. if (E->n == 0) {
  1342. ret = mbedtls_mpi_lset(X, 1);
  1343. return ret;
  1344. }
  1345. /*
  1346. * Allocate working memory for mbedtls_mpi_core_exp_mod()
  1347. */
  1348. size_t T_limbs = mbedtls_mpi_core_exp_mod_working_limbs(N->n, E->n);
  1349. mbedtls_mpi_uint *T = (mbedtls_mpi_uint *) mbedtls_calloc(T_limbs, sizeof(mbedtls_mpi_uint));
  1350. if (T == NULL) {
  1351. return MBEDTLS_ERR_MPI_ALLOC_FAILED;
  1352. }
  1353. mbedtls_mpi RR;
  1354. mbedtls_mpi_init(&RR);
  1355. /*
  1356. * If 1st call, pre-compute R^2 mod N
  1357. */
  1358. if (prec_RR == NULL || prec_RR->p == NULL) {
  1359. MBEDTLS_MPI_CHK(mbedtls_mpi_core_get_mont_r2_unsafe(&RR, N));
  1360. if (prec_RR != NULL) {
  1361. *prec_RR = RR;
  1362. }
  1363. } else {
  1364. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(prec_RR, N->n));
  1365. RR = *prec_RR;
  1366. }
  1367. /*
  1368. * To preserve constness we need to make a copy of A. Using X for this to
  1369. * save memory.
  1370. */
  1371. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(X, A));
  1372. /*
  1373. * Compensate for negative A (and correct at the end).
  1374. */
  1375. X->s = 1;
  1376. /*
  1377. * Make sure that X is in a form that is safe for consumption by
  1378. * the core functions.
  1379. *
  1380. * - The core functions will not touch the limbs of X above N->n. The
  1381. * result will be correct if those limbs are 0, which the mod call
  1382. * ensures.
  1383. * - Also, X must have at least as many limbs as N for the calls to the
  1384. * core functions.
  1385. */
  1386. if (mbedtls_mpi_cmp_mpi(X, N) >= 0) {
  1387. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(X, X, N));
  1388. }
  1389. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, N->n));
  1390. /*
  1391. * Convert to and from Montgomery around mbedtls_mpi_core_exp_mod().
  1392. */
  1393. {
  1394. mbedtls_mpi_uint mm = mbedtls_mpi_core_montmul_init(N->p);
  1395. mbedtls_mpi_core_to_mont_rep(X->p, X->p, N->p, N->n, mm, RR.p, T);
  1396. if (E_public == MBEDTLS_MPI_IS_PUBLIC) {
  1397. mbedtls_mpi_core_exp_mod_unsafe(X->p, X->p, N->p, N->n, E->p, E->n, RR.p, T);
  1398. } else {
  1399. mbedtls_mpi_core_exp_mod(X->p, X->p, N->p, N->n, E->p, E->n, RR.p, T);
  1400. }
  1401. mbedtls_mpi_core_from_mont_rep(X->p, X->p, N->p, N->n, mm, T);
  1402. }
  1403. /*
  1404. * Correct for negative A.
  1405. */
  1406. if (A->s == -1 && (E->p[0] & 1) != 0) {
  1407. mbedtls_ct_condition_t is_x_non_zero = mbedtls_mpi_core_check_zero_ct(X->p, X->n);
  1408. X->s = mbedtls_ct_mpi_sign_if(is_x_non_zero, -1, 1);
  1409. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(X, N, X));
  1410. }
  1411. cleanup:
  1412. mbedtls_mpi_zeroize_and_free(T, T_limbs);
  1413. if (prec_RR == NULL || prec_RR->p == NULL) {
  1414. mbedtls_mpi_free(&RR);
  1415. }
  1416. return ret;
  1417. }
  1418. int mbedtls_mpi_exp_mod(mbedtls_mpi *X, const mbedtls_mpi *A,
  1419. const mbedtls_mpi *E, const mbedtls_mpi *N,
  1420. mbedtls_mpi *prec_RR)
  1421. {
  1422. return mbedtls_mpi_exp_mod_optionally_safe(X, A, E, MBEDTLS_MPI_IS_SECRET, N, prec_RR);
  1423. }
  1424. int mbedtls_mpi_exp_mod_unsafe(mbedtls_mpi *X, const mbedtls_mpi *A,
  1425. const mbedtls_mpi *E, const mbedtls_mpi *N,
  1426. mbedtls_mpi *prec_RR)
  1427. {
  1428. return mbedtls_mpi_exp_mod_optionally_safe(X, A, E, MBEDTLS_MPI_IS_PUBLIC, N, prec_RR);
  1429. }
  1430. /*
  1431. * Greatest common divisor: G = gcd(A, B) (HAC 14.54)
  1432. */
  1433. int mbedtls_mpi_gcd(mbedtls_mpi *G, const mbedtls_mpi *A, const mbedtls_mpi *B)
  1434. {
  1435. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1436. size_t lz, lzt;
  1437. mbedtls_mpi TA, TB;
  1438. mbedtls_mpi_init(&TA); mbedtls_mpi_init(&TB);
  1439. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TA, A));
  1440. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TB, B));
  1441. lz = mbedtls_mpi_lsb(&TA);
  1442. lzt = mbedtls_mpi_lsb(&TB);
  1443. /* The loop below gives the correct result when A==0 but not when B==0.
  1444. * So have a special case for B==0. Leverage the fact that we just
  1445. * calculated the lsb and lsb(B)==0 iff B is odd or 0 to make the test
  1446. * slightly more efficient than cmp_int(). */
  1447. if (lzt == 0 && mbedtls_mpi_get_bit(&TB, 0) == 0) {
  1448. ret = mbedtls_mpi_copy(G, A);
  1449. goto cleanup;
  1450. }
  1451. if (lzt < lz) {
  1452. lz = lzt;
  1453. }
  1454. TA.s = TB.s = 1;
  1455. /* We mostly follow the procedure described in HAC 14.54, but with some
  1456. * minor differences:
  1457. * - Sequences of multiplications or divisions by 2 are grouped into a
  1458. * single shift operation.
  1459. * - The procedure in HAC assumes that 0 < TB <= TA.
  1460. * - The condition TB <= TA is not actually necessary for correctness.
  1461. * TA and TB have symmetric roles except for the loop termination
  1462. * condition, and the shifts at the beginning of the loop body
  1463. * remove any significance from the ordering of TA vs TB before
  1464. * the shifts.
  1465. * - If TA = 0, the loop goes through 0 iterations and the result is
  1466. * correctly TB.
  1467. * - The case TB = 0 was short-circuited above.
  1468. *
  1469. * For the correctness proof below, decompose the original values of
  1470. * A and B as
  1471. * A = sa * 2^a * A' with A'=0 or A' odd, and sa = +-1
  1472. * B = sb * 2^b * B' with B'=0 or B' odd, and sb = +-1
  1473. * Then gcd(A, B) = 2^{min(a,b)} * gcd(A',B'),
  1474. * and gcd(A',B') is odd or 0.
  1475. *
  1476. * At the beginning, we have TA = |A| and TB = |B| so gcd(A,B) = gcd(TA,TB).
  1477. * The code maintains the following invariant:
  1478. * gcd(A,B) = 2^k * gcd(TA,TB) for some k (I)
  1479. */
  1480. /* Proof that the loop terminates:
  1481. * At each iteration, either the right-shift by 1 is made on a nonzero
  1482. * value and the nonnegative integer bitlen(TA) + bitlen(TB) decreases
  1483. * by at least 1, or the right-shift by 1 is made on zero and then
  1484. * TA becomes 0 which ends the loop (TB cannot be 0 if it is right-shifted
  1485. * since in that case TB is calculated from TB-TA with the condition TB>TA).
  1486. */
  1487. while (mbedtls_mpi_cmp_int(&TA, 0) != 0) {
  1488. /* Divisions by 2 preserve the invariant (I). */
  1489. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TA, mbedtls_mpi_lsb(&TA)));
  1490. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TB, mbedtls_mpi_lsb(&TB)));
  1491. /* Set either TA or TB to |TA-TB|/2. Since TA and TB are both odd,
  1492. * TA-TB is even so the division by 2 has an integer result.
  1493. * Invariant (I) is preserved since any odd divisor of both TA and TB
  1494. * also divides |TA-TB|/2, and any odd divisor of both TA and |TA-TB|/2
  1495. * also divides TB, and any odd divisor of both TB and |TA-TB|/2 also
  1496. * divides TA.
  1497. */
  1498. if (mbedtls_mpi_cmp_mpi(&TA, &TB) >= 0) {
  1499. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs(&TA, &TA, &TB));
  1500. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TA, 1));
  1501. } else {
  1502. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs(&TB, &TB, &TA));
  1503. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TB, 1));
  1504. }
  1505. /* Note that one of TA or TB is still odd. */
  1506. }
  1507. /* By invariant (I), gcd(A,B) = 2^k * gcd(TA,TB) for some k.
  1508. * At the loop exit, TA = 0, so gcd(TA,TB) = TB.
  1509. * - If there was at least one loop iteration, then one of TA or TB is odd,
  1510. * and TA = 0, so TB is odd and gcd(TA,TB) = gcd(A',B'). In this case,
  1511. * lz = min(a,b) so gcd(A,B) = 2^lz * TB.
  1512. * - If there was no loop iteration, then A was 0, and gcd(A,B) = B.
  1513. * In this case, lz = 0 and B = TB so gcd(A,B) = B = 2^lz * TB as well.
  1514. */
  1515. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&TB, lz));
  1516. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(G, &TB));
  1517. cleanup:
  1518. mbedtls_mpi_free(&TA); mbedtls_mpi_free(&TB);
  1519. return ret;
  1520. }
  1521. /*
  1522. * Fill X with size bytes of random.
  1523. * The bytes returned from the RNG are used in a specific order which
  1524. * is suitable for deterministic ECDSA (see the specification of
  1525. * mbedtls_mpi_random() and the implementation in mbedtls_mpi_fill_random()).
  1526. */
  1527. int mbedtls_mpi_fill_random(mbedtls_mpi *X, size_t size,
  1528. int (*f_rng)(void *, unsigned char *, size_t),
  1529. void *p_rng)
  1530. {
  1531. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1532. const size_t limbs = CHARS_TO_LIMBS(size);
  1533. /* Ensure that target MPI has exactly the necessary number of limbs */
  1534. MBEDTLS_MPI_CHK(mbedtls_mpi_resize_clear(X, limbs));
  1535. if (size == 0) {
  1536. return 0;
  1537. }
  1538. ret = mbedtls_mpi_core_fill_random(X->p, X->n, size, f_rng, p_rng);
  1539. cleanup:
  1540. return ret;
  1541. }
  1542. int mbedtls_mpi_random(mbedtls_mpi *X,
  1543. mbedtls_mpi_sint min,
  1544. const mbedtls_mpi *N,
  1545. int (*f_rng)(void *, unsigned char *, size_t),
  1546. void *p_rng)
  1547. {
  1548. if (min < 0) {
  1549. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  1550. }
  1551. if (mbedtls_mpi_cmp_int(N, min) <= 0) {
  1552. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  1553. }
  1554. /* Ensure that target MPI has exactly the same number of limbs
  1555. * as the upper bound, even if the upper bound has leading zeros.
  1556. * This is necessary for mbedtls_mpi_core_random. */
  1557. int ret = mbedtls_mpi_resize_clear(X, N->n);
  1558. if (ret != 0) {
  1559. return ret;
  1560. }
  1561. return mbedtls_mpi_core_random(X->p, min, N->p, X->n, f_rng, p_rng);
  1562. }
  1563. /*
  1564. * Modular inverse: X = A^-1 mod N (HAC 14.61 / 14.64)
  1565. */
  1566. int mbedtls_mpi_inv_mod(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *N)
  1567. {
  1568. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1569. mbedtls_mpi G, TA, TU, U1, U2, TB, TV, V1, V2;
  1570. if (mbedtls_mpi_cmp_int(N, 1) <= 0) {
  1571. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  1572. }
  1573. mbedtls_mpi_init(&TA); mbedtls_mpi_init(&TU); mbedtls_mpi_init(&U1); mbedtls_mpi_init(&U2);
  1574. mbedtls_mpi_init(&G); mbedtls_mpi_init(&TB); mbedtls_mpi_init(&TV);
  1575. mbedtls_mpi_init(&V1); mbedtls_mpi_init(&V2);
  1576. MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, A, N));
  1577. if (mbedtls_mpi_cmp_int(&G, 1) != 0) {
  1578. ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
  1579. goto cleanup;
  1580. }
  1581. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&TA, A, N));
  1582. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TU, &TA));
  1583. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TB, N));
  1584. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TV, N));
  1585. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&U1, 1));
  1586. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&U2, 0));
  1587. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&V1, 0));
  1588. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&V2, 1));
  1589. do {
  1590. while ((TU.p[0] & 1) == 0) {
  1591. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TU, 1));
  1592. if ((U1.p[0] & 1) != 0 || (U2.p[0] & 1) != 0) {
  1593. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&U1, &U1, &TB));
  1594. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&U2, &U2, &TA));
  1595. }
  1596. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&U1, 1));
  1597. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&U2, 1));
  1598. }
  1599. while ((TV.p[0] & 1) == 0) {
  1600. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TV, 1));
  1601. if ((V1.p[0] & 1) != 0 || (V2.p[0] & 1) != 0) {
  1602. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&V1, &V1, &TB));
  1603. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&V2, &V2, &TA));
  1604. }
  1605. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&V1, 1));
  1606. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&V2, 1));
  1607. }
  1608. if (mbedtls_mpi_cmp_mpi(&TU, &TV) >= 0) {
  1609. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&TU, &TU, &TV));
  1610. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&U1, &U1, &V1));
  1611. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&U2, &U2, &V2));
  1612. } else {
  1613. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&TV, &TV, &TU));
  1614. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&V1, &V1, &U1));
  1615. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&V2, &V2, &U2));
  1616. }
  1617. } while (mbedtls_mpi_cmp_int(&TU, 0) != 0);
  1618. while (mbedtls_mpi_cmp_int(&V1, 0) < 0) {
  1619. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&V1, &V1, N));
  1620. }
  1621. while (mbedtls_mpi_cmp_mpi(&V1, N) >= 0) {
  1622. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&V1, &V1, N));
  1623. }
  1624. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(X, &V1));
  1625. cleanup:
  1626. mbedtls_mpi_free(&TA); mbedtls_mpi_free(&TU); mbedtls_mpi_free(&U1); mbedtls_mpi_free(&U2);
  1627. mbedtls_mpi_free(&G); mbedtls_mpi_free(&TB); mbedtls_mpi_free(&TV);
  1628. mbedtls_mpi_free(&V1); mbedtls_mpi_free(&V2);
  1629. return ret;
  1630. }
  1631. #if defined(MBEDTLS_GENPRIME)
  1632. /* Gaps between primes, starting at 3. https://oeis.org/A001223 */
  1633. static const unsigned char small_prime_gaps[] = {
  1634. 2, 2, 4, 2, 4, 2, 4, 6,
  1635. 2, 6, 4, 2, 4, 6, 6, 2,
  1636. 6, 4, 2, 6, 4, 6, 8, 4,
  1637. 2, 4, 2, 4, 14, 4, 6, 2,
  1638. 10, 2, 6, 6, 4, 6, 6, 2,
  1639. 10, 2, 4, 2, 12, 12, 4, 2,
  1640. 4, 6, 2, 10, 6, 6, 6, 2,
  1641. 6, 4, 2, 10, 14, 4, 2, 4,
  1642. 14, 6, 10, 2, 4, 6, 8, 6,
  1643. 6, 4, 6, 8, 4, 8, 10, 2,
  1644. 10, 2, 6, 4, 6, 8, 4, 2,
  1645. 4, 12, 8, 4, 8, 4, 6, 12,
  1646. 2, 18, 6, 10, 6, 6, 2, 6,
  1647. 10, 6, 6, 2, 6, 6, 4, 2,
  1648. 12, 10, 2, 4, 6, 6, 2, 12,
  1649. 4, 6, 8, 10, 8, 10, 8, 6,
  1650. 6, 4, 8, 6, 4, 8, 4, 14,
  1651. 10, 12, 2, 10, 2, 4, 2, 10,
  1652. 14, 4, 2, 4, 14, 4, 2, 4,
  1653. 20, 4, 8, 10, 8, 4, 6, 6,
  1654. 14, 4, 6, 6, 8, 6, /*reaches 997*/
  1655. 0 /* the last entry is effectively unused */
  1656. };
  1657. /*
  1658. * Small divisors test (X must be positive)
  1659. *
  1660. * Return values:
  1661. * 0: no small factor (possible prime, more tests needed)
  1662. * 1: certain prime
  1663. * MBEDTLS_ERR_MPI_NOT_ACCEPTABLE: certain non-prime
  1664. * other negative: error
  1665. */
  1666. static int mpi_check_small_factors(const mbedtls_mpi *X)
  1667. {
  1668. int ret = 0;
  1669. size_t i;
  1670. mbedtls_mpi_uint r;
  1671. unsigned p = 3; /* The first odd prime */
  1672. if ((X->p[0] & 1) == 0) {
  1673. return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
  1674. }
  1675. for (i = 0; i < sizeof(small_prime_gaps); p += small_prime_gaps[i], i++) {
  1676. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_int(&r, X, p));
  1677. if (r == 0) {
  1678. if (mbedtls_mpi_cmp_int(X, p) == 0) {
  1679. return 1;
  1680. } else {
  1681. return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
  1682. }
  1683. }
  1684. }
  1685. cleanup:
  1686. return ret;
  1687. }
  1688. /*
  1689. * Miller-Rabin pseudo-primality test (HAC 4.24)
  1690. */
  1691. static int mpi_miller_rabin(const mbedtls_mpi *X, size_t rounds,
  1692. int (*f_rng)(void *, unsigned char *, size_t),
  1693. void *p_rng)
  1694. {
  1695. int ret, count;
  1696. size_t i, j, k, s;
  1697. mbedtls_mpi W, R, T, A, RR;
  1698. mbedtls_mpi_init(&W); mbedtls_mpi_init(&R);
  1699. mbedtls_mpi_init(&T); mbedtls_mpi_init(&A);
  1700. mbedtls_mpi_init(&RR);
  1701. /*
  1702. * W = |X| - 1
  1703. * R = W >> lsb( W )
  1704. */
  1705. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&W, X, 1));
  1706. s = mbedtls_mpi_lsb(&W);
  1707. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&R, &W));
  1708. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&R, s));
  1709. for (i = 0; i < rounds; i++) {
  1710. /*
  1711. * pick a random A, 1 < A < |X| - 1
  1712. */
  1713. count = 0;
  1714. do {
  1715. MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&A, X->n * ciL, f_rng, p_rng));
  1716. j = mbedtls_mpi_bitlen(&A);
  1717. k = mbedtls_mpi_bitlen(&W);
  1718. if (j > k) {
  1719. A.p[A.n - 1] &= ((mbedtls_mpi_uint) 1 << (k - (A.n - 1) * biL - 1)) - 1;
  1720. }
  1721. if (count++ > 30) {
  1722. ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
  1723. goto cleanup;
  1724. }
  1725. } while (mbedtls_mpi_cmp_mpi(&A, &W) >= 0 ||
  1726. mbedtls_mpi_cmp_int(&A, 1) <= 0);
  1727. /*
  1728. * A = A^R mod |X|
  1729. */
  1730. MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&A, &A, &R, X, &RR));
  1731. if (mbedtls_mpi_cmp_mpi(&A, &W) == 0 ||
  1732. mbedtls_mpi_cmp_int(&A, 1) == 0) {
  1733. continue;
  1734. }
  1735. j = 1;
  1736. while (j < s && mbedtls_mpi_cmp_mpi(&A, &W) != 0) {
  1737. /*
  1738. * A = A * A mod |X|
  1739. */
  1740. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&T, &A, &A));
  1741. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&A, &T, X));
  1742. if (mbedtls_mpi_cmp_int(&A, 1) == 0) {
  1743. break;
  1744. }
  1745. j++;
  1746. }
  1747. /*
  1748. * not prime if A != |X| - 1 or A == 1
  1749. */
  1750. if (mbedtls_mpi_cmp_mpi(&A, &W) != 0 ||
  1751. mbedtls_mpi_cmp_int(&A, 1) == 0) {
  1752. ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
  1753. break;
  1754. }
  1755. }
  1756. cleanup:
  1757. mbedtls_mpi_free(&W); mbedtls_mpi_free(&R);
  1758. mbedtls_mpi_free(&T); mbedtls_mpi_free(&A);
  1759. mbedtls_mpi_free(&RR);
  1760. return ret;
  1761. }
  1762. /*
  1763. * Pseudo-primality test: small factors, then Miller-Rabin
  1764. */
  1765. int mbedtls_mpi_is_prime_ext(const mbedtls_mpi *X, int rounds,
  1766. int (*f_rng)(void *, unsigned char *, size_t),
  1767. void *p_rng)
  1768. {
  1769. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1770. mbedtls_mpi XX;
  1771. XX.s = 1;
  1772. XX.n = X->n;
  1773. XX.p = X->p;
  1774. if (mbedtls_mpi_cmp_int(&XX, 0) == 0 ||
  1775. mbedtls_mpi_cmp_int(&XX, 1) == 0) {
  1776. return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
  1777. }
  1778. if (mbedtls_mpi_cmp_int(&XX, 2) == 0) {
  1779. return 0;
  1780. }
  1781. if ((ret = mpi_check_small_factors(&XX)) != 0) {
  1782. if (ret == 1) {
  1783. return 0;
  1784. }
  1785. return ret;
  1786. }
  1787. return mpi_miller_rabin(&XX, rounds, f_rng, p_rng);
  1788. }
  1789. /*
  1790. * Prime number generation
  1791. *
  1792. * To generate an RSA key in a way recommended by FIPS 186-4, both primes must
  1793. * be either 1024 bits or 1536 bits long, and flags must contain
  1794. * MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR.
  1795. */
  1796. int mbedtls_mpi_gen_prime(mbedtls_mpi *X, size_t nbits, int flags,
  1797. int (*f_rng)(void *, unsigned char *, size_t),
  1798. void *p_rng)
  1799. {
  1800. #ifdef MBEDTLS_HAVE_INT64
  1801. // ceil(2^63.5)
  1802. #define CEIL_MAXUINT_DIV_SQRT2 0xb504f333f9de6485ULL
  1803. #else
  1804. // ceil(2^31.5)
  1805. #define CEIL_MAXUINT_DIV_SQRT2 0xb504f334U
  1806. #endif
  1807. int ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
  1808. size_t k, n;
  1809. int rounds;
  1810. mbedtls_mpi_uint r;
  1811. mbedtls_mpi Y;
  1812. if (nbits < 3 || nbits > MBEDTLS_MPI_MAX_BITS) {
  1813. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  1814. }
  1815. mbedtls_mpi_init(&Y);
  1816. n = BITS_TO_LIMBS(nbits);
  1817. if ((flags & MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR) == 0) {
  1818. /*
  1819. * 2^-80 error probability, number of rounds chosen per HAC, table 4.4
  1820. */
  1821. rounds = ((nbits >= 1300) ? 2 : (nbits >= 850) ? 3 :
  1822. (nbits >= 650) ? 4 : (nbits >= 350) ? 8 :
  1823. (nbits >= 250) ? 12 : (nbits >= 150) ? 18 : 27);
  1824. } else {
  1825. /*
  1826. * 2^-100 error probability, number of rounds computed based on HAC,
  1827. * fact 4.48
  1828. */
  1829. rounds = ((nbits >= 1450) ? 4 : (nbits >= 1150) ? 5 :
  1830. (nbits >= 1000) ? 6 : (nbits >= 850) ? 7 :
  1831. (nbits >= 750) ? 8 : (nbits >= 500) ? 13 :
  1832. (nbits >= 250) ? 28 : (nbits >= 150) ? 40 : 51);
  1833. }
  1834. while (1) {
  1835. MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(X, n * ciL, f_rng, p_rng));
  1836. /* make sure generated number is at least (nbits-1)+0.5 bits (FIPS 186-4 §B.3.3 steps 4.4, 5.5) */
  1837. if (X->p[n-1] < CEIL_MAXUINT_DIV_SQRT2) {
  1838. continue;
  1839. }
  1840. k = n * biL;
  1841. if (k > nbits) {
  1842. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(X, k - nbits));
  1843. }
  1844. X->p[0] |= 1;
  1845. if ((flags & MBEDTLS_MPI_GEN_PRIME_FLAG_DH) == 0) {
  1846. ret = mbedtls_mpi_is_prime_ext(X, rounds, f_rng, p_rng);
  1847. if (ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
  1848. goto cleanup;
  1849. }
  1850. } else {
  1851. /*
  1852. * A necessary condition for Y and X = 2Y + 1 to be prime
  1853. * is X = 2 mod 3 (which is equivalent to Y = 2 mod 3).
  1854. * Make sure it is satisfied, while keeping X = 3 mod 4
  1855. */
  1856. X->p[0] |= 2;
  1857. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_int(&r, X, 3));
  1858. if (r == 0) {
  1859. MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(X, X, 8));
  1860. } else if (r == 1) {
  1861. MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(X, X, 4));
  1862. }
  1863. /* Set Y = (X-1) / 2, which is X / 2 because X is odd */
  1864. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&Y, X));
  1865. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&Y, 1));
  1866. while (1) {
  1867. /*
  1868. * First, check small factors for X and Y
  1869. * before doing Miller-Rabin on any of them
  1870. */
  1871. if ((ret = mpi_check_small_factors(X)) == 0 &&
  1872. (ret = mpi_check_small_factors(&Y)) == 0 &&
  1873. (ret = mpi_miller_rabin(X, rounds, f_rng, p_rng))
  1874. == 0 &&
  1875. (ret = mpi_miller_rabin(&Y, rounds, f_rng, p_rng))
  1876. == 0) {
  1877. goto cleanup;
  1878. }
  1879. if (ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
  1880. goto cleanup;
  1881. }
  1882. /*
  1883. * Next candidates. We want to preserve Y = (X-1) / 2 and
  1884. * Y = 1 mod 2 and Y = 2 mod 3 (eq X = 3 mod 4 and X = 2 mod 3)
  1885. * so up Y by 6 and X by 12.
  1886. */
  1887. MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(X, X, 12));
  1888. MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&Y, &Y, 6));
  1889. }
  1890. }
  1891. }
  1892. cleanup:
  1893. mbedtls_mpi_free(&Y);
  1894. return ret;
  1895. }
  1896. #endif /* MBEDTLS_GENPRIME */
  1897. #if defined(MBEDTLS_SELF_TEST)
  1898. #define GCD_PAIR_COUNT 3
  1899. static const int gcd_pairs[GCD_PAIR_COUNT][3] =
  1900. {
  1901. { 693, 609, 21 },
  1902. { 1764, 868, 28 },
  1903. { 768454923, 542167814, 1 }
  1904. };
  1905. /*
  1906. * Checkup routine
  1907. */
  1908. int mbedtls_mpi_self_test(int verbose)
  1909. {
  1910. int ret, i;
  1911. mbedtls_mpi A, E, N, X, Y, U, V;
  1912. mbedtls_mpi_init(&A); mbedtls_mpi_init(&E); mbedtls_mpi_init(&N); mbedtls_mpi_init(&X);
  1913. mbedtls_mpi_init(&Y); mbedtls_mpi_init(&U); mbedtls_mpi_init(&V);
  1914. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&A, 16,
  1915. "EFE021C2645FD1DC586E69184AF4A31E" \
  1916. "D5F53E93B5F123FA41680867BA110131" \
  1917. "944FE7952E2517337780CB0DB80E61AA" \
  1918. "E7C8DDC6C5C6AADEB34EB38A2F40D5E6"));
  1919. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&E, 16,
  1920. "B2E7EFD37075B9F03FF989C7C5051C20" \
  1921. "34D2A323810251127E7BF8625A4F49A5" \
  1922. "F3E27F4DA8BD59C47D6DAABA4C8127BD" \
  1923. "5B5C25763222FEFCCFC38B832366C29E"));
  1924. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&N, 16,
  1925. "0066A198186C18C10B2F5ED9B522752A" \
  1926. "9830B69916E535C8F047518A889A43A5" \
  1927. "94B6BED27A168D31D4A52F88925AA8F5"));
  1928. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&X, &A, &N));
  1929. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&U, 16,
  1930. "602AB7ECA597A3D6B56FF9829A5E8B85" \
  1931. "9E857EA95A03512E2BAE7391688D264A" \
  1932. "A5663B0341DB9CCFD2C4C5F421FEC814" \
  1933. "8001B72E848A38CAE1C65F78E56ABDEF" \
  1934. "E12D3C039B8A02D6BE593F0BBBDA56F1" \
  1935. "ECF677152EF804370C1A305CAF3B5BF1" \
  1936. "30879B56C61DE584A0F53A2447A51E"));
  1937. if (verbose != 0) {
  1938. mbedtls_printf(" MPI test #1 (mul_mpi): ");
  1939. }
  1940. if (mbedtls_mpi_cmp_mpi(&X, &U) != 0) {
  1941. if (verbose != 0) {
  1942. mbedtls_printf("failed\n");
  1943. }
  1944. ret = 1;
  1945. goto cleanup;
  1946. }
  1947. if (verbose != 0) {
  1948. mbedtls_printf("passed\n");
  1949. }
  1950. MBEDTLS_MPI_CHK(mbedtls_mpi_div_mpi(&X, &Y, &A, &N));
  1951. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&U, 16,
  1952. "256567336059E52CAE22925474705F39A94"));
  1953. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&V, 16,
  1954. "6613F26162223DF488E9CD48CC132C7A" \
  1955. "0AC93C701B001B092E4E5B9F73BCD27B" \
  1956. "9EE50D0657C77F374E903CDFA4C642"));
  1957. if (verbose != 0) {
  1958. mbedtls_printf(" MPI test #2 (div_mpi): ");
  1959. }
  1960. if (mbedtls_mpi_cmp_mpi(&X, &U) != 0 ||
  1961. mbedtls_mpi_cmp_mpi(&Y, &V) != 0) {
  1962. if (verbose != 0) {
  1963. mbedtls_printf("failed\n");
  1964. }
  1965. ret = 1;
  1966. goto cleanup;
  1967. }
  1968. if (verbose != 0) {
  1969. mbedtls_printf("passed\n");
  1970. }
  1971. MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&X, &A, &E, &N, NULL));
  1972. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&U, 16,
  1973. "36E139AEA55215609D2816998ED020BB" \
  1974. "BD96C37890F65171D948E9BC7CBAA4D9" \
  1975. "325D24D6A3C12710F10A09FA08AB87"));
  1976. if (verbose != 0) {
  1977. mbedtls_printf(" MPI test #3 (exp_mod): ");
  1978. }
  1979. if (mbedtls_mpi_cmp_mpi(&X, &U) != 0) {
  1980. if (verbose != 0) {
  1981. mbedtls_printf("failed\n");
  1982. }
  1983. ret = 1;
  1984. goto cleanup;
  1985. }
  1986. if (verbose != 0) {
  1987. mbedtls_printf("passed\n");
  1988. }
  1989. MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&X, &A, &N));
  1990. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&U, 16,
  1991. "003A0AAEDD7E784FC07D8F9EC6E3BFD5" \
  1992. "C3DBA76456363A10869622EAC2DD84EC" \
  1993. "C5B8A74DAC4D09E03B5E0BE779F2DF61"));
  1994. if (verbose != 0) {
  1995. mbedtls_printf(" MPI test #4 (inv_mod): ");
  1996. }
  1997. if (mbedtls_mpi_cmp_mpi(&X, &U) != 0) {
  1998. if (verbose != 0) {
  1999. mbedtls_printf("failed\n");
  2000. }
  2001. ret = 1;
  2002. goto cleanup;
  2003. }
  2004. if (verbose != 0) {
  2005. mbedtls_printf("passed\n");
  2006. }
  2007. if (verbose != 0) {
  2008. mbedtls_printf(" MPI test #5 (simple gcd): ");
  2009. }
  2010. for (i = 0; i < GCD_PAIR_COUNT; i++) {
  2011. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&X, gcd_pairs[i][0]));
  2012. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&Y, gcd_pairs[i][1]));
  2013. MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&A, &X, &Y));
  2014. if (mbedtls_mpi_cmp_int(&A, gcd_pairs[i][2]) != 0) {
  2015. if (verbose != 0) {
  2016. mbedtls_printf("failed at %d\n", i);
  2017. }
  2018. ret = 1;
  2019. goto cleanup;
  2020. }
  2021. }
  2022. if (verbose != 0) {
  2023. mbedtls_printf("passed\n");
  2024. }
  2025. cleanup:
  2026. if (ret != 0 && verbose != 0) {
  2027. mbedtls_printf("Unexpected error, return code = %08X\n", (unsigned int) ret);
  2028. }
  2029. mbedtls_mpi_free(&A); mbedtls_mpi_free(&E); mbedtls_mpi_free(&N); mbedtls_mpi_free(&X);
  2030. mbedtls_mpi_free(&Y); mbedtls_mpi_free(&U); mbedtls_mpi_free(&V);
  2031. if (verbose != 0) {
  2032. mbedtls_printf("\n");
  2033. }
  2034. return ret;
  2035. }
  2036. #endif /* MBEDTLS_SELF_TEST */
  2037. #endif /* MBEDTLS_BIGNUM_C */