bignum.c 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426
  1. /*
  2. * Multi-precision integer library
  3. *
  4. * Copyright The Mbed TLS Contributors
  5. * SPDX-License-Identifier: Apache-2.0
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  8. * not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. /*
  20. * The following sources were referenced in the design of this Multi-precision
  21. * Integer library:
  22. *
  23. * [1] Handbook of Applied Cryptography - 1997
  24. * Menezes, van Oorschot and Vanstone
  25. *
  26. * [2] Multi-Precision Math
  27. * Tom St Denis
  28. * https://github.com/libtom/libtommath/blob/develop/tommath.pdf
  29. *
  30. * [3] GNU Multi-Precision Arithmetic Library
  31. * https://gmplib.org/manual/index.html
  32. *
  33. */
  34. #include "common.h"
  35. #if defined(MBEDTLS_BIGNUM_C)
  36. #include "mbedtls/bignum.h"
  37. #include "mbedtls/bn_mul.h"
  38. #include "mbedtls/platform_util.h"
  39. #include "mbedtls/error.h"
  40. #include <string.h>
  41. #if defined(MBEDTLS_PLATFORM_C)
  42. #include "mbedtls/platform.h"
  43. #else
  44. #include <stdio.h>
  45. #include <stdlib.h>
  46. #define mbedtls_printf printf
  47. #define mbedtls_calloc calloc
  48. #define mbedtls_free free
  49. #endif
  50. #define MPI_VALIDATE_RET( cond ) \
  51. MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_MPI_BAD_INPUT_DATA )
  52. #define MPI_VALIDATE( cond ) \
  53. MBEDTLS_INTERNAL_VALIDATE( cond )
  54. #define ciL (sizeof(mbedtls_mpi_uint)) /* chars in limb */
  55. #define biL (ciL << 3) /* bits in limb */
  56. #define biH (ciL << 2) /* half limb size */
  57. #define MPI_SIZE_T_MAX ( (size_t) -1 ) /* SIZE_T_MAX is not standard */
  58. /*
  59. * Convert between bits/chars and number of limbs
  60. * Divide first in order to avoid potential overflows
  61. */
  62. #define BITS_TO_LIMBS(i) ( (i) / biL + ( (i) % biL != 0 ) )
  63. #define CHARS_TO_LIMBS(i) ( (i) / ciL + ( (i) % ciL != 0 ) )
  64. /* Implementation that should never be optimized out by the compiler */
  65. static void mbedtls_mpi_zeroize( mbedtls_mpi_uint *v, size_t n )
  66. {
  67. mbedtls_platform_zeroize( v, ciL * n );
  68. }
  69. /*
  70. * Initialize one MPI
  71. */
  72. void mbedtls_mpi_init( mbedtls_mpi *X )
  73. {
  74. MPI_VALIDATE( X != NULL );
  75. X->s = 1;
  76. X->n = 0;
  77. X->p = NULL;
  78. }
  79. /*
  80. * Unallocate one MPI
  81. */
  82. void mbedtls_mpi_free( mbedtls_mpi *X )
  83. {
  84. if( X == NULL )
  85. return;
  86. if( X->p != NULL )
  87. {
  88. mbedtls_mpi_zeroize( X->p, X->n );
  89. mbedtls_free( X->p );
  90. }
  91. X->s = 1;
  92. X->n = 0;
  93. X->p = NULL;
  94. }
  95. /*
  96. * Enlarge to the specified number of limbs
  97. */
  98. int mbedtls_mpi_grow( mbedtls_mpi *X, size_t nblimbs )
  99. {
  100. mbedtls_mpi_uint *p;
  101. MPI_VALIDATE_RET( X != NULL );
  102. if( nblimbs > MBEDTLS_MPI_MAX_LIMBS )
  103. return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
  104. if( X->n < nblimbs )
  105. {
  106. if( ( p = (mbedtls_mpi_uint*)mbedtls_calloc( nblimbs, ciL ) ) == NULL )
  107. return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
  108. if( X->p != NULL )
  109. {
  110. memcpy( p, X->p, X->n * ciL );
  111. mbedtls_mpi_zeroize( X->p, X->n );
  112. mbedtls_free( X->p );
  113. }
  114. X->n = nblimbs;
  115. X->p = p;
  116. }
  117. return( 0 );
  118. }
  119. /*
  120. * Resize down as much as possible,
  121. * while keeping at least the specified number of limbs
  122. */
  123. int mbedtls_mpi_shrink( mbedtls_mpi *X, size_t nblimbs )
  124. {
  125. mbedtls_mpi_uint *p;
  126. size_t i;
  127. MPI_VALIDATE_RET( X != NULL );
  128. if( nblimbs > MBEDTLS_MPI_MAX_LIMBS )
  129. return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
  130. /* Actually resize up if there are currently fewer than nblimbs limbs. */
  131. if( X->n <= nblimbs )
  132. return( mbedtls_mpi_grow( X, nblimbs ) );
  133. /* After this point, then X->n > nblimbs and in particular X->n > 0. */
  134. for( i = X->n - 1; i > 0; i-- )
  135. if( X->p[i] != 0 )
  136. break;
  137. i++;
  138. if( i < nblimbs )
  139. i = nblimbs;
  140. if( ( p = (mbedtls_mpi_uint*)mbedtls_calloc( i, ciL ) ) == NULL )
  141. return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
  142. if( X->p != NULL )
  143. {
  144. memcpy( p, X->p, i * ciL );
  145. mbedtls_mpi_zeroize( X->p, X->n );
  146. mbedtls_free( X->p );
  147. }
  148. X->n = i;
  149. X->p = p;
  150. return( 0 );
  151. }
  152. /* Resize X to have exactly n limbs and set it to 0. */
  153. static int mbedtls_mpi_resize_clear( mbedtls_mpi *X, size_t limbs )
  154. {
  155. if( limbs == 0 )
  156. {
  157. mbedtls_mpi_free( X );
  158. return( 0 );
  159. }
  160. else if( X->n == limbs )
  161. {
  162. memset( X->p, 0, limbs * ciL );
  163. X->s = 1;
  164. return( 0 );
  165. }
  166. else
  167. {
  168. mbedtls_mpi_free( X );
  169. return( mbedtls_mpi_grow( X, limbs ) );
  170. }
  171. }
  172. /*
  173. * Copy the contents of Y into X.
  174. *
  175. * This function is not constant-time. Leading zeros in Y may be removed.
  176. *
  177. * Ensure that X does not shrink. This is not guaranteed by the public API,
  178. * but some code in the bignum module relies on this property, for example
  179. * in mbedtls_mpi_exp_mod().
  180. */
  181. int mbedtls_mpi_copy( mbedtls_mpi *X, const mbedtls_mpi *Y )
  182. {
  183. int ret = 0;
  184. size_t i;
  185. MPI_VALIDATE_RET( X != NULL );
  186. MPI_VALIDATE_RET( Y != NULL );
  187. if( X == Y )
  188. return( 0 );
  189. if( Y->n == 0 )
  190. {
  191. if( X->n != 0 )
  192. {
  193. X->s = 1;
  194. memset( X->p, 0, X->n * ciL );
  195. }
  196. return( 0 );
  197. }
  198. for( i = Y->n - 1; i > 0; i-- )
  199. if( Y->p[i] != 0 )
  200. break;
  201. i++;
  202. X->s = Y->s;
  203. if( X->n < i )
  204. {
  205. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i ) );
  206. }
  207. else
  208. {
  209. memset( X->p + i, 0, ( X->n - i ) * ciL );
  210. }
  211. memcpy( X->p, Y->p, i * ciL );
  212. cleanup:
  213. return( ret );
  214. }
  215. /*
  216. * Swap the contents of X and Y
  217. */
  218. void mbedtls_mpi_swap( mbedtls_mpi *X, mbedtls_mpi *Y )
  219. {
  220. mbedtls_mpi T;
  221. MPI_VALIDATE( X != NULL );
  222. MPI_VALIDATE( Y != NULL );
  223. memcpy( &T, X, sizeof( mbedtls_mpi ) );
  224. memcpy( X, Y, sizeof( mbedtls_mpi ) );
  225. memcpy( Y, &T, sizeof( mbedtls_mpi ) );
  226. }
  227. /**
  228. * Select between two sign values in constant-time.
  229. *
  230. * This is functionally equivalent to second ? a : b but uses only bit
  231. * operations in order to avoid branches.
  232. *
  233. * \param[in] a The first sign; must be either +1 or -1.
  234. * \param[in] b The second sign; must be either +1 or -1.
  235. * \param[in] second Must be either 1 (return b) or 0 (return a).
  236. *
  237. * \return The selected sign value.
  238. */
  239. static int mpi_safe_cond_select_sign( int a, int b, unsigned char second )
  240. {
  241. /* In order to avoid questions about what we can reasonnably assume about
  242. * the representations of signed integers, move everything to unsigned
  243. * by taking advantage of the fact that a and b are either +1 or -1. */
  244. unsigned ua = a + 1;
  245. unsigned ub = b + 1;
  246. /* second was 0 or 1, mask is 0 or 2 as are ua and ub */
  247. const unsigned mask = second << 1;
  248. /* select ua or ub */
  249. unsigned ur = ( ua & ~mask ) | ( ub & mask );
  250. /* ur is now 0 or 2, convert back to -1 or +1 */
  251. return( (int) ur - 1 );
  252. }
  253. /*
  254. * Conditionally assign dest = src, without leaking information
  255. * about whether the assignment was made or not.
  256. * dest and src must be arrays of limbs of size n.
  257. * assign must be 0 or 1.
  258. */
  259. static void mpi_safe_cond_assign( size_t n,
  260. mbedtls_mpi_uint *dest,
  261. const mbedtls_mpi_uint *src,
  262. unsigned char assign )
  263. {
  264. size_t i;
  265. /* MSVC has a warning about unary minus on unsigned integer types,
  266. * but this is well-defined and precisely what we want to do here. */
  267. #if defined(_MSC_VER)
  268. #pragma warning( push )
  269. #pragma warning( disable : 4146 )
  270. #endif
  271. /* all-bits 1 if assign is 1, all-bits 0 if assign is 0 */
  272. const mbedtls_mpi_uint mask = -assign;
  273. #if defined(_MSC_VER)
  274. #pragma warning( pop )
  275. #endif
  276. for( i = 0; i < n; i++ )
  277. dest[i] = ( src[i] & mask ) | ( dest[i] & ~mask );
  278. }
  279. /*
  280. * Conditionally assign X = Y, without leaking information
  281. * about whether the assignment was made or not.
  282. * (Leaking information about the respective sizes of X and Y is ok however.)
  283. */
  284. int mbedtls_mpi_safe_cond_assign( mbedtls_mpi *X, const mbedtls_mpi *Y, unsigned char assign )
  285. {
  286. int ret = 0;
  287. size_t i;
  288. mbedtls_mpi_uint limb_mask;
  289. MPI_VALIDATE_RET( X != NULL );
  290. MPI_VALIDATE_RET( Y != NULL );
  291. /* MSVC has a warning about unary minus on unsigned integer types,
  292. * but this is well-defined and precisely what we want to do here. */
  293. #if defined(_MSC_VER)
  294. #pragma warning( push )
  295. #pragma warning( disable : 4146 )
  296. #endif
  297. /* make sure assign is 0 or 1 in a time-constant manner */
  298. assign = (assign | (unsigned char)-assign) >> (sizeof( assign ) * 8 - 1);
  299. /* all-bits 1 if assign is 1, all-bits 0 if assign is 0 */
  300. limb_mask = -assign;
  301. #if defined(_MSC_VER)
  302. #pragma warning( pop )
  303. #endif
  304. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
  305. X->s = mpi_safe_cond_select_sign( X->s, Y->s, assign );
  306. mpi_safe_cond_assign( Y->n, X->p, Y->p, assign );
  307. for( i = Y->n; i < X->n; i++ )
  308. X->p[i] &= ~limb_mask;
  309. cleanup:
  310. return( ret );
  311. }
  312. /*
  313. * Conditionally swap X and Y, without leaking information
  314. * about whether the swap was made or not.
  315. * Here it is not ok to simply swap the pointers, which whould lead to
  316. * different memory access patterns when X and Y are used afterwards.
  317. */
  318. int mbedtls_mpi_safe_cond_swap( mbedtls_mpi *X, mbedtls_mpi *Y, unsigned char swap )
  319. {
  320. int ret, s;
  321. size_t i;
  322. mbedtls_mpi_uint limb_mask;
  323. mbedtls_mpi_uint tmp;
  324. MPI_VALIDATE_RET( X != NULL );
  325. MPI_VALIDATE_RET( Y != NULL );
  326. if( X == Y )
  327. return( 0 );
  328. /* MSVC has a warning about unary minus on unsigned integer types,
  329. * but this is well-defined and precisely what we want to do here. */
  330. #if defined(_MSC_VER)
  331. #pragma warning( push )
  332. #pragma warning( disable : 4146 )
  333. #endif
  334. /* make sure swap is 0 or 1 in a time-constant manner */
  335. swap = (swap | (unsigned char)-swap) >> (sizeof( swap ) * 8 - 1);
  336. /* all-bits 1 if swap is 1, all-bits 0 if swap is 0 */
  337. limb_mask = -swap;
  338. #if defined(_MSC_VER)
  339. #pragma warning( pop )
  340. #endif
  341. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
  342. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( Y, X->n ) );
  343. s = X->s;
  344. X->s = mpi_safe_cond_select_sign( X->s, Y->s, swap );
  345. Y->s = mpi_safe_cond_select_sign( Y->s, s, swap );
  346. for( i = 0; i < X->n; i++ )
  347. {
  348. tmp = X->p[i];
  349. X->p[i] = ( X->p[i] & ~limb_mask ) | ( Y->p[i] & limb_mask );
  350. Y->p[i] = ( Y->p[i] & ~limb_mask ) | ( tmp & limb_mask );
  351. }
  352. cleanup:
  353. return( ret );
  354. }
  355. /*
  356. * Set value from integer
  357. */
  358. int mbedtls_mpi_lset( mbedtls_mpi *X, mbedtls_mpi_sint z )
  359. {
  360. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  361. MPI_VALIDATE_RET( X != NULL );
  362. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, 1 ) );
  363. memset( X->p, 0, X->n * ciL );
  364. X->p[0] = ( z < 0 ) ? -z : z;
  365. X->s = ( z < 0 ) ? -1 : 1;
  366. cleanup:
  367. return( ret );
  368. }
  369. /*
  370. * Get a specific bit
  371. */
  372. int mbedtls_mpi_get_bit( const mbedtls_mpi *X, size_t pos )
  373. {
  374. MPI_VALIDATE_RET( X != NULL );
  375. if( X->n * biL <= pos )
  376. return( 0 );
  377. return( ( X->p[pos / biL] >> ( pos % biL ) ) & 0x01 );
  378. }
  379. /* Get a specific byte, without range checks. */
  380. #define GET_BYTE( X, i ) \
  381. ( ( ( X )->p[( i ) / ciL] >> ( ( ( i ) % ciL ) * 8 ) ) & 0xff )
  382. /*
  383. * Set a bit to a specific value of 0 or 1
  384. */
  385. int mbedtls_mpi_set_bit( mbedtls_mpi *X, size_t pos, unsigned char val )
  386. {
  387. int ret = 0;
  388. size_t off = pos / biL;
  389. size_t idx = pos % biL;
  390. MPI_VALIDATE_RET( X != NULL );
  391. if( val != 0 && val != 1 )
  392. return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
  393. if( X->n * biL <= pos )
  394. {
  395. if( val == 0 )
  396. return( 0 );
  397. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, off + 1 ) );
  398. }
  399. X->p[off] &= ~( (mbedtls_mpi_uint) 0x01 << idx );
  400. X->p[off] |= (mbedtls_mpi_uint) val << idx;
  401. cleanup:
  402. return( ret );
  403. }
  404. /*
  405. * Return the number of less significant zero-bits
  406. */
  407. size_t mbedtls_mpi_lsb( const mbedtls_mpi *X )
  408. {
  409. size_t i, j, count = 0;
  410. MBEDTLS_INTERNAL_VALIDATE_RET( X != NULL, 0 );
  411. for( i = 0; i < X->n; i++ )
  412. for( j = 0; j < biL; j++, count++ )
  413. if( ( ( X->p[i] >> j ) & 1 ) != 0 )
  414. return( count );
  415. return( 0 );
  416. }
  417. /*
  418. * Count leading zero bits in a given integer
  419. */
  420. static size_t mbedtls_clz( const mbedtls_mpi_uint x )
  421. {
  422. size_t j;
  423. mbedtls_mpi_uint mask = (mbedtls_mpi_uint) 1 << (biL - 1);
  424. for( j = 0; j < biL; j++ )
  425. {
  426. if( x & mask ) break;
  427. mask >>= 1;
  428. }
  429. return j;
  430. }
  431. /*
  432. * Return the number of bits
  433. */
  434. size_t mbedtls_mpi_bitlen( const mbedtls_mpi *X )
  435. {
  436. size_t i, j;
  437. if( X->n == 0 )
  438. return( 0 );
  439. for( i = X->n - 1; i > 0; i-- )
  440. if( X->p[i] != 0 )
  441. break;
  442. j = biL - mbedtls_clz( X->p[i] );
  443. return( ( i * biL ) + j );
  444. }
  445. /*
  446. * Return the total size in bytes
  447. */
  448. size_t mbedtls_mpi_size( const mbedtls_mpi *X )
  449. {
  450. return( ( mbedtls_mpi_bitlen( X ) + 7 ) >> 3 );
  451. }
  452. /*
  453. * Convert an ASCII character to digit value
  454. */
  455. static int mpi_get_digit( mbedtls_mpi_uint *d, int radix, char c )
  456. {
  457. *d = 255;
  458. if( c >= 0x30 && c <= 0x39 ) *d = c - 0x30;
  459. if( c >= 0x41 && c <= 0x46 ) *d = c - 0x37;
  460. if( c >= 0x61 && c <= 0x66 ) *d = c - 0x57;
  461. if( *d >= (mbedtls_mpi_uint) radix )
  462. return( MBEDTLS_ERR_MPI_INVALID_CHARACTER );
  463. return( 0 );
  464. }
  465. /*
  466. * Import from an ASCII string
  467. */
  468. int mbedtls_mpi_read_string( mbedtls_mpi *X, int radix, const char *s )
  469. {
  470. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  471. size_t i, j, slen, n;
  472. int sign = 1;
  473. mbedtls_mpi_uint d;
  474. mbedtls_mpi T;
  475. MPI_VALIDATE_RET( X != NULL );
  476. MPI_VALIDATE_RET( s != NULL );
  477. if( radix < 2 || radix > 16 )
  478. return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
  479. mbedtls_mpi_init( &T );
  480. if( s[0] == 0 )
  481. {
  482. mbedtls_mpi_free( X );
  483. return( 0 );
  484. }
  485. if( s[0] == '-' )
  486. {
  487. ++s;
  488. sign = -1;
  489. }
  490. slen = strlen( s );
  491. if( radix == 16 )
  492. {
  493. if( slen > MPI_SIZE_T_MAX >> 2 )
  494. return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
  495. n = BITS_TO_LIMBS( slen << 2 );
  496. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, n ) );
  497. MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );
  498. for( i = slen, j = 0; i > 0; i--, j++ )
  499. {
  500. MBEDTLS_MPI_CHK( mpi_get_digit( &d, radix, s[i - 1] ) );
  501. X->p[j / ( 2 * ciL )] |= d << ( ( j % ( 2 * ciL ) ) << 2 );
  502. }
  503. }
  504. else
  505. {
  506. MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );
  507. for( i = 0; i < slen; i++ )
  508. {
  509. MBEDTLS_MPI_CHK( mpi_get_digit( &d, radix, s[i] ) );
  510. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &T, X, radix ) );
  511. MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, &T, d ) );
  512. }
  513. }
  514. if( sign < 0 && mbedtls_mpi_bitlen( X ) != 0 )
  515. X->s = -1;
  516. cleanup:
  517. mbedtls_mpi_free( &T );
  518. return( ret );
  519. }
  520. /*
  521. * Helper to write the digits high-order first.
  522. */
  523. static int mpi_write_hlp( mbedtls_mpi *X, int radix,
  524. char **p, const size_t buflen )
  525. {
  526. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  527. mbedtls_mpi_uint r;
  528. size_t length = 0;
  529. char *p_end = *p + buflen;
  530. do
  531. {
  532. if( length >= buflen )
  533. {
  534. return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
  535. }
  536. MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, radix ) );
  537. MBEDTLS_MPI_CHK( mbedtls_mpi_div_int( X, NULL, X, radix ) );
  538. /*
  539. * Write the residue in the current position, as an ASCII character.
  540. */
  541. if( r < 0xA )
  542. *(--p_end) = (char)( '0' + r );
  543. else
  544. *(--p_end) = (char)( 'A' + ( r - 0xA ) );
  545. length++;
  546. } while( mbedtls_mpi_cmp_int( X, 0 ) != 0 );
  547. memmove( *p, p_end, length );
  548. *p += length;
  549. cleanup:
  550. return( ret );
  551. }
  552. /*
  553. * Export into an ASCII string
  554. */
  555. int mbedtls_mpi_write_string( const mbedtls_mpi *X, int radix,
  556. char *buf, size_t buflen, size_t *olen )
  557. {
  558. int ret = 0;
  559. size_t n;
  560. char *p;
  561. mbedtls_mpi T;
  562. MPI_VALIDATE_RET( X != NULL );
  563. MPI_VALIDATE_RET( olen != NULL );
  564. MPI_VALIDATE_RET( buflen == 0 || buf != NULL );
  565. if( radix < 2 || radix > 16 )
  566. return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
  567. n = mbedtls_mpi_bitlen( X ); /* Number of bits necessary to present `n`. */
  568. if( radix >= 4 ) n >>= 1; /* Number of 4-adic digits necessary to present
  569. * `n`. If radix > 4, this might be a strict
  570. * overapproximation of the number of
  571. * radix-adic digits needed to present `n`. */
  572. if( radix >= 16 ) n >>= 1; /* Number of hexadecimal digits necessary to
  573. * present `n`. */
  574. n += 1; /* Terminating null byte */
  575. n += 1; /* Compensate for the divisions above, which round down `n`
  576. * in case it's not even. */
  577. n += 1; /* Potential '-'-sign. */
  578. n += ( n & 1 ); /* Make n even to have enough space for hexadecimal writing,
  579. * which always uses an even number of hex-digits. */
  580. if( buflen < n )
  581. {
  582. *olen = n;
  583. return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
  584. }
  585. p = buf;
  586. mbedtls_mpi_init( &T );
  587. if( X->s == -1 )
  588. {
  589. *p++ = '-';
  590. buflen--;
  591. }
  592. if( radix == 16 )
  593. {
  594. int c;
  595. size_t i, j, k;
  596. for( i = X->n, k = 0; i > 0; i-- )
  597. {
  598. for( j = ciL; j > 0; j-- )
  599. {
  600. c = ( X->p[i - 1] >> ( ( j - 1 ) << 3) ) & 0xFF;
  601. if( c == 0 && k == 0 && ( i + j ) != 2 )
  602. continue;
  603. *(p++) = "0123456789ABCDEF" [c / 16];
  604. *(p++) = "0123456789ABCDEF" [c % 16];
  605. k = 1;
  606. }
  607. }
  608. }
  609. else
  610. {
  611. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &T, X ) );
  612. if( T.s == -1 )
  613. T.s = 1;
  614. MBEDTLS_MPI_CHK( mpi_write_hlp( &T, radix, &p, buflen ) );
  615. }
  616. *p++ = '\0';
  617. *olen = p - buf;
  618. cleanup:
  619. mbedtls_mpi_free( &T );
  620. return( ret );
  621. }
  622. #if defined(MBEDTLS_FS_IO)
  623. /*
  624. * Read X from an opened file
  625. */
  626. int mbedtls_mpi_read_file( mbedtls_mpi *X, int radix, FILE *fin )
  627. {
  628. mbedtls_mpi_uint d;
  629. size_t slen;
  630. char *p;
  631. /*
  632. * Buffer should have space for (short) label and decimal formatted MPI,
  633. * newline characters and '\0'
  634. */
  635. char s[ MBEDTLS_MPI_RW_BUFFER_SIZE ];
  636. MPI_VALIDATE_RET( X != NULL );
  637. MPI_VALIDATE_RET( fin != NULL );
  638. if( radix < 2 || radix > 16 )
  639. return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
  640. memset( s, 0, sizeof( s ) );
  641. if( fgets( s, sizeof( s ) - 1, fin ) == NULL )
  642. return( MBEDTLS_ERR_MPI_FILE_IO_ERROR );
  643. slen = strlen( s );
  644. if( slen == sizeof( s ) - 2 )
  645. return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
  646. if( slen > 0 && s[slen - 1] == '\n' ) { slen--; s[slen] = '\0'; }
  647. if( slen > 0 && s[slen - 1] == '\r' ) { slen--; s[slen] = '\0'; }
  648. p = s + slen;
  649. while( p-- > s )
  650. if( mpi_get_digit( &d, radix, *p ) != 0 )
  651. break;
  652. return( mbedtls_mpi_read_string( X, radix, p + 1 ) );
  653. }
  654. /*
  655. * Write X into an opened file (or stdout if fout == NULL)
  656. */
  657. int mbedtls_mpi_write_file( const char *p, const mbedtls_mpi *X, int radix, FILE *fout )
  658. {
  659. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  660. size_t n, slen, plen;
  661. /*
  662. * Buffer should have space for (short) label and decimal formatted MPI,
  663. * newline characters and '\0'
  664. */
  665. char s[ MBEDTLS_MPI_RW_BUFFER_SIZE ];
  666. MPI_VALIDATE_RET( X != NULL );
  667. if( radix < 2 || radix > 16 )
  668. return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
  669. memset( s, 0, sizeof( s ) );
  670. MBEDTLS_MPI_CHK( mbedtls_mpi_write_string( X, radix, s, sizeof( s ) - 2, &n ) );
  671. if( p == NULL ) p = "";
  672. plen = strlen( p );
  673. slen = strlen( s );
  674. s[slen++] = '\r';
  675. s[slen++] = '\n';
  676. if( fout != NULL )
  677. {
  678. if( fwrite( p, 1, plen, fout ) != plen ||
  679. fwrite( s, 1, slen, fout ) != slen )
  680. return( MBEDTLS_ERR_MPI_FILE_IO_ERROR );
  681. }
  682. else
  683. mbedtls_printf( "%s%s", p, s );
  684. cleanup:
  685. return( ret );
  686. }
  687. #endif /* MBEDTLS_FS_IO */
  688. /* Convert a big-endian byte array aligned to the size of mbedtls_mpi_uint
  689. * into the storage form used by mbedtls_mpi. */
  690. static mbedtls_mpi_uint mpi_uint_bigendian_to_host_c( mbedtls_mpi_uint x )
  691. {
  692. uint8_t i;
  693. unsigned char *x_ptr;
  694. mbedtls_mpi_uint tmp = 0;
  695. for( i = 0, x_ptr = (unsigned char*) &x; i < ciL; i++, x_ptr++ )
  696. {
  697. tmp <<= CHAR_BIT;
  698. tmp |= (mbedtls_mpi_uint) *x_ptr;
  699. }
  700. return( tmp );
  701. }
  702. static mbedtls_mpi_uint mpi_uint_bigendian_to_host( mbedtls_mpi_uint x )
  703. {
  704. #if defined(__BYTE_ORDER__)
  705. /* Nothing to do on bigendian systems. */
  706. #if ( __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ )
  707. return( x );
  708. #endif /* __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ */
  709. #if ( __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ )
  710. /* For GCC and Clang, have builtins for byte swapping. */
  711. #if defined(__GNUC__) && defined(__GNUC_PREREQ)
  712. #if __GNUC_PREREQ(4,3)
  713. #define have_bswap
  714. #endif
  715. #endif
  716. #if defined(__clang__) && defined(__has_builtin)
  717. #if __has_builtin(__builtin_bswap32) && \
  718. __has_builtin(__builtin_bswap64)
  719. #define have_bswap
  720. #endif
  721. #endif
  722. #if defined(have_bswap)
  723. /* The compiler is hopefully able to statically evaluate this! */
  724. switch( sizeof(mbedtls_mpi_uint) )
  725. {
  726. case 4:
  727. return( __builtin_bswap32(x) );
  728. case 8:
  729. return( __builtin_bswap64(x) );
  730. }
  731. #endif
  732. #endif /* __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ */
  733. #endif /* __BYTE_ORDER__ */
  734. /* Fall back to C-based reordering if we don't know the byte order
  735. * or we couldn't use a compiler-specific builtin. */
  736. return( mpi_uint_bigendian_to_host_c( x ) );
  737. }
  738. static void mpi_bigendian_to_host( mbedtls_mpi_uint * const p, size_t limbs )
  739. {
  740. mbedtls_mpi_uint *cur_limb_left;
  741. mbedtls_mpi_uint *cur_limb_right;
  742. if( limbs == 0 )
  743. return;
  744. /*
  745. * Traverse limbs and
  746. * - adapt byte-order in each limb
  747. * - swap the limbs themselves.
  748. * For that, simultaneously traverse the limbs from left to right
  749. * and from right to left, as long as the left index is not bigger
  750. * than the right index (it's not a problem if limbs is odd and the
  751. * indices coincide in the last iteration).
  752. */
  753. for( cur_limb_left = p, cur_limb_right = p + ( limbs - 1 );
  754. cur_limb_left <= cur_limb_right;
  755. cur_limb_left++, cur_limb_right-- )
  756. {
  757. mbedtls_mpi_uint tmp;
  758. /* Note that if cur_limb_left == cur_limb_right,
  759. * this code effectively swaps the bytes only once. */
  760. tmp = mpi_uint_bigendian_to_host( *cur_limb_left );
  761. *cur_limb_left = mpi_uint_bigendian_to_host( *cur_limb_right );
  762. *cur_limb_right = tmp;
  763. }
  764. }
  765. /*
  766. * Import X from unsigned binary data, little endian
  767. */
  768. int mbedtls_mpi_read_binary_le( mbedtls_mpi *X,
  769. const unsigned char *buf, size_t buflen )
  770. {
  771. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  772. size_t i;
  773. size_t const limbs = CHARS_TO_LIMBS( buflen );
  774. /* Ensure that target MPI has exactly the necessary number of limbs */
  775. MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, limbs ) );
  776. for( i = 0; i < buflen; i++ )
  777. X->p[i / ciL] |= ((mbedtls_mpi_uint) buf[i]) << ((i % ciL) << 3);
  778. cleanup:
  779. /*
  780. * This function is also used to import keys. However, wiping the buffers
  781. * upon failure is not necessary because failure only can happen before any
  782. * input is copied.
  783. */
  784. return( ret );
  785. }
  786. /*
  787. * Import X from unsigned binary data, big endian
  788. */
  789. int mbedtls_mpi_read_binary( mbedtls_mpi *X, const unsigned char *buf, size_t buflen )
  790. {
  791. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  792. size_t const limbs = CHARS_TO_LIMBS( buflen );
  793. size_t const overhead = ( limbs * ciL ) - buflen;
  794. unsigned char *Xp;
  795. MPI_VALIDATE_RET( X != NULL );
  796. MPI_VALIDATE_RET( buflen == 0 || buf != NULL );
  797. /* Ensure that target MPI has exactly the necessary number of limbs */
  798. MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, limbs ) );
  799. /* Avoid calling `memcpy` with NULL source or destination argument,
  800. * even if buflen is 0. */
  801. if( buflen != 0 )
  802. {
  803. Xp = (unsigned char*) X->p;
  804. memcpy( Xp + overhead, buf, buflen );
  805. mpi_bigendian_to_host( X->p, limbs );
  806. }
  807. cleanup:
  808. /*
  809. * This function is also used to import keys. However, wiping the buffers
  810. * upon failure is not necessary because failure only can happen before any
  811. * input is copied.
  812. */
  813. return( ret );
  814. }
  815. /*
  816. * Export X into unsigned binary data, little endian
  817. */
  818. int mbedtls_mpi_write_binary_le( const mbedtls_mpi *X,
  819. unsigned char *buf, size_t buflen )
  820. {
  821. size_t stored_bytes = X->n * ciL;
  822. size_t bytes_to_copy;
  823. size_t i;
  824. if( stored_bytes < buflen )
  825. {
  826. bytes_to_copy = stored_bytes;
  827. }
  828. else
  829. {
  830. bytes_to_copy = buflen;
  831. /* The output buffer is smaller than the allocated size of X.
  832. * However X may fit if its leading bytes are zero. */
  833. for( i = bytes_to_copy; i < stored_bytes; i++ )
  834. {
  835. if( GET_BYTE( X, i ) != 0 )
  836. return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
  837. }
  838. }
  839. for( i = 0; i < bytes_to_copy; i++ )
  840. buf[i] = GET_BYTE( X, i );
  841. if( stored_bytes < buflen )
  842. {
  843. /* Write trailing 0 bytes */
  844. memset( buf + stored_bytes, 0, buflen - stored_bytes );
  845. }
  846. return( 0 );
  847. }
  848. /*
  849. * Export X into unsigned binary data, big endian
  850. */
  851. int mbedtls_mpi_write_binary( const mbedtls_mpi *X,
  852. unsigned char *buf, size_t buflen )
  853. {
  854. size_t stored_bytes;
  855. size_t bytes_to_copy;
  856. unsigned char *p;
  857. size_t i;
  858. MPI_VALIDATE_RET( X != NULL );
  859. MPI_VALIDATE_RET( buflen == 0 || buf != NULL );
  860. stored_bytes = X->n * ciL;
  861. if( stored_bytes < buflen )
  862. {
  863. /* There is enough space in the output buffer. Write initial
  864. * null bytes and record the position at which to start
  865. * writing the significant bytes. In this case, the execution
  866. * trace of this function does not depend on the value of the
  867. * number. */
  868. bytes_to_copy = stored_bytes;
  869. p = buf + buflen - stored_bytes;
  870. memset( buf, 0, buflen - stored_bytes );
  871. }
  872. else
  873. {
  874. /* The output buffer is smaller than the allocated size of X.
  875. * However X may fit if its leading bytes are zero. */
  876. bytes_to_copy = buflen;
  877. p = buf;
  878. for( i = bytes_to_copy; i < stored_bytes; i++ )
  879. {
  880. if( GET_BYTE( X, i ) != 0 )
  881. return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
  882. }
  883. }
  884. for( i = 0; i < bytes_to_copy; i++ )
  885. p[bytes_to_copy - i - 1] = GET_BYTE( X, i );
  886. return( 0 );
  887. }
  888. /*
  889. * Left-shift: X <<= count
  890. */
  891. int mbedtls_mpi_shift_l( mbedtls_mpi *X, size_t count )
  892. {
  893. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  894. size_t i, v0, t1;
  895. mbedtls_mpi_uint r0 = 0, r1;
  896. MPI_VALIDATE_RET( X != NULL );
  897. v0 = count / (biL );
  898. t1 = count & (biL - 1);
  899. i = mbedtls_mpi_bitlen( X ) + count;
  900. if( X->n * biL < i )
  901. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, BITS_TO_LIMBS( i ) ) );
  902. ret = 0;
  903. /*
  904. * shift by count / limb_size
  905. */
  906. if( v0 > 0 )
  907. {
  908. for( i = X->n; i > v0; i-- )
  909. X->p[i - 1] = X->p[i - v0 - 1];
  910. for( ; i > 0; i-- )
  911. X->p[i - 1] = 0;
  912. }
  913. /*
  914. * shift by count % limb_size
  915. */
  916. if( t1 > 0 )
  917. {
  918. for( i = v0; i < X->n; i++ )
  919. {
  920. r1 = X->p[i] >> (biL - t1);
  921. X->p[i] <<= t1;
  922. X->p[i] |= r0;
  923. r0 = r1;
  924. }
  925. }
  926. cleanup:
  927. return( ret );
  928. }
  929. /*
  930. * Right-shift: X >>= count
  931. */
  932. int mbedtls_mpi_shift_r( mbedtls_mpi *X, size_t count )
  933. {
  934. size_t i, v0, v1;
  935. mbedtls_mpi_uint r0 = 0, r1;
  936. MPI_VALIDATE_RET( X != NULL );
  937. v0 = count / biL;
  938. v1 = count & (biL - 1);
  939. if( v0 > X->n || ( v0 == X->n && v1 > 0 ) )
  940. return mbedtls_mpi_lset( X, 0 );
  941. /*
  942. * shift by count / limb_size
  943. */
  944. if( v0 > 0 )
  945. {
  946. for( i = 0; i < X->n - v0; i++ )
  947. X->p[i] = X->p[i + v0];
  948. for( ; i < X->n; i++ )
  949. X->p[i] = 0;
  950. }
  951. /*
  952. * shift by count % limb_size
  953. */
  954. if( v1 > 0 )
  955. {
  956. for( i = X->n; i > 0; i-- )
  957. {
  958. r1 = X->p[i - 1] << (biL - v1);
  959. X->p[i - 1] >>= v1;
  960. X->p[i - 1] |= r0;
  961. r0 = r1;
  962. }
  963. }
  964. return( 0 );
  965. }
  966. /*
  967. * Compare unsigned values
  968. */
  969. int mbedtls_mpi_cmp_abs( const mbedtls_mpi *X, const mbedtls_mpi *Y )
  970. {
  971. size_t i, j;
  972. MPI_VALIDATE_RET( X != NULL );
  973. MPI_VALIDATE_RET( Y != NULL );
  974. for( i = X->n; i > 0; i-- )
  975. if( X->p[i - 1] != 0 )
  976. break;
  977. for( j = Y->n; j > 0; j-- )
  978. if( Y->p[j - 1] != 0 )
  979. break;
  980. if( i == 0 && j == 0 )
  981. return( 0 );
  982. if( i > j ) return( 1 );
  983. if( j > i ) return( -1 );
  984. for( ; i > 0; i-- )
  985. {
  986. if( X->p[i - 1] > Y->p[i - 1] ) return( 1 );
  987. if( X->p[i - 1] < Y->p[i - 1] ) return( -1 );
  988. }
  989. return( 0 );
  990. }
  991. /*
  992. * Compare signed values
  993. */
  994. int mbedtls_mpi_cmp_mpi( const mbedtls_mpi *X, const mbedtls_mpi *Y )
  995. {
  996. size_t i, j;
  997. MPI_VALIDATE_RET( X != NULL );
  998. MPI_VALIDATE_RET( Y != NULL );
  999. for( i = X->n; i > 0; i-- )
  1000. if( X->p[i - 1] != 0 )
  1001. break;
  1002. for( j = Y->n; j > 0; j-- )
  1003. if( Y->p[j - 1] != 0 )
  1004. break;
  1005. if( i == 0 && j == 0 )
  1006. return( 0 );
  1007. if( i > j ) return( X->s );
  1008. if( j > i ) return( -Y->s );
  1009. if( X->s > 0 && Y->s < 0 ) return( 1 );
  1010. if( Y->s > 0 && X->s < 0 ) return( -1 );
  1011. for( ; i > 0; i-- )
  1012. {
  1013. if( X->p[i - 1] > Y->p[i - 1] ) return( X->s );
  1014. if( X->p[i - 1] < Y->p[i - 1] ) return( -X->s );
  1015. }
  1016. return( 0 );
  1017. }
  1018. /** Decide if an integer is less than the other, without branches.
  1019. *
  1020. * \param x First integer.
  1021. * \param y Second integer.
  1022. *
  1023. * \return 1 if \p x is less than \p y, 0 otherwise
  1024. */
  1025. static unsigned ct_lt_mpi_uint( const mbedtls_mpi_uint x,
  1026. const mbedtls_mpi_uint y )
  1027. {
  1028. mbedtls_mpi_uint ret;
  1029. mbedtls_mpi_uint cond;
  1030. /*
  1031. * Check if the most significant bits (MSB) of the operands are different.
  1032. */
  1033. cond = ( x ^ y );
  1034. /*
  1035. * If the MSB are the same then the difference x-y will be negative (and
  1036. * have its MSB set to 1 during conversion to unsigned) if and only if x<y.
  1037. */
  1038. ret = ( x - y ) & ~cond;
  1039. /*
  1040. * If the MSB are different, then the operand with the MSB of 1 is the
  1041. * bigger. (That is if y has MSB of 1, then x<y is true and it is false if
  1042. * the MSB of y is 0.)
  1043. */
  1044. ret |= y & cond;
  1045. ret = ret >> ( biL - 1 );
  1046. return (unsigned) ret;
  1047. }
  1048. /*
  1049. * Compare signed values in constant time
  1050. */
  1051. int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *X, const mbedtls_mpi *Y,
  1052. unsigned *ret )
  1053. {
  1054. size_t i;
  1055. /* The value of any of these variables is either 0 or 1 at all times. */
  1056. unsigned cond, done, X_is_negative, Y_is_negative;
  1057. MPI_VALIDATE_RET( X != NULL );
  1058. MPI_VALIDATE_RET( Y != NULL );
  1059. MPI_VALIDATE_RET( ret != NULL );
  1060. if( X->n != Y->n )
  1061. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  1062. /*
  1063. * Set sign_N to 1 if N >= 0, 0 if N < 0.
  1064. * We know that N->s == 1 if N >= 0 and N->s == -1 if N < 0.
  1065. */
  1066. X_is_negative = ( X->s & 2 ) >> 1;
  1067. Y_is_negative = ( Y->s & 2 ) >> 1;
  1068. /*
  1069. * If the signs are different, then the positive operand is the bigger.
  1070. * That is if X is negative (X_is_negative == 1), then X < Y is true and it
  1071. * is false if X is positive (X_is_negative == 0).
  1072. */
  1073. cond = ( X_is_negative ^ Y_is_negative );
  1074. *ret = cond & X_is_negative;
  1075. /*
  1076. * This is a constant-time function. We might have the result, but we still
  1077. * need to go through the loop. Record if we have the result already.
  1078. */
  1079. done = cond;
  1080. for( i = X->n; i > 0; i-- )
  1081. {
  1082. /*
  1083. * If Y->p[i - 1] < X->p[i - 1] then X < Y is true if and only if both
  1084. * X and Y are negative.
  1085. *
  1086. * Again even if we can make a decision, we just mark the result and
  1087. * the fact that we are done and continue looping.
  1088. */
  1089. cond = ct_lt_mpi_uint( Y->p[i - 1], X->p[i - 1] );
  1090. *ret |= cond & ( 1 - done ) & X_is_negative;
  1091. done |= cond;
  1092. /*
  1093. * If X->p[i - 1] < Y->p[i - 1] then X < Y is true if and only if both
  1094. * X and Y are positive.
  1095. *
  1096. * Again even if we can make a decision, we just mark the result and
  1097. * the fact that we are done and continue looping.
  1098. */
  1099. cond = ct_lt_mpi_uint( X->p[i - 1], Y->p[i - 1] );
  1100. *ret |= cond & ( 1 - done ) & ( 1 - X_is_negative );
  1101. done |= cond;
  1102. }
  1103. return( 0 );
  1104. }
  1105. /*
  1106. * Compare signed values
  1107. */
  1108. int mbedtls_mpi_cmp_int( const mbedtls_mpi *X, mbedtls_mpi_sint z )
  1109. {
  1110. mbedtls_mpi Y;
  1111. mbedtls_mpi_uint p[1];
  1112. MPI_VALIDATE_RET( X != NULL );
  1113. *p = ( z < 0 ) ? -z : z;
  1114. Y.s = ( z < 0 ) ? -1 : 1;
  1115. Y.n = 1;
  1116. Y.p = p;
  1117. return( mbedtls_mpi_cmp_mpi( X, &Y ) );
  1118. }
  1119. /*
  1120. * Unsigned addition: X = |A| + |B| (HAC 14.7)
  1121. */
  1122. /* NXP added for HW accelerators support */
  1123. #if defined(MBEDTLS_MPI_ADD_ABS_ALT)
  1124. int mbedtls_mpi_add_abs_orig( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
  1125. #else
  1126. int mbedtls_mpi_add_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
  1127. #endif /* MBEDTLS_MPI_ADD_ABS_ALT */
  1128. {
  1129. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1130. size_t i, j;
  1131. mbedtls_mpi_uint *o, *p, c, tmp;
  1132. MPI_VALIDATE_RET( X != NULL );
  1133. MPI_VALIDATE_RET( A != NULL );
  1134. MPI_VALIDATE_RET( B != NULL );
  1135. if( X == B )
  1136. {
  1137. const mbedtls_mpi *T = A; A = X; B = T;
  1138. }
  1139. if( X != A )
  1140. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, A ) );
  1141. /*
  1142. * X should always be positive as a result of unsigned additions.
  1143. */
  1144. X->s = 1;
  1145. for( j = B->n; j > 0; j-- )
  1146. if( B->p[j - 1] != 0 )
  1147. break;
  1148. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, j ) );
  1149. o = B->p; p = X->p; c = 0;
  1150. /*
  1151. * tmp is used because it might happen that p == o
  1152. */
  1153. for( i = 0; i < j; i++, o++, p++ )
  1154. {
  1155. tmp= *o;
  1156. *p += c; c = ( *p < c );
  1157. *p += tmp; c += ( *p < tmp );
  1158. }
  1159. while( c != 0 )
  1160. {
  1161. if( i >= X->n )
  1162. {
  1163. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i + 1 ) );
  1164. p = X->p + i;
  1165. }
  1166. *p += c; c = ( *p < c ); i++; p++;
  1167. }
  1168. cleanup:
  1169. return( ret );
  1170. }
  1171. /**
  1172. * Helper for mbedtls_mpi subtraction.
  1173. *
  1174. * Calculate l - r where l and r have the same size.
  1175. * This function operates modulo (2^ciL)^n and returns the carry
  1176. * (1 if there was a wraparound, i.e. if `l < r`, and 0 otherwise).
  1177. *
  1178. * d may be aliased to l or r.
  1179. *
  1180. * \param n Number of limbs of \p d, \p l and \p r.
  1181. * \param[out] d The result of the subtraction.
  1182. * \param[in] l The left operand.
  1183. * \param[in] r The right operand.
  1184. *
  1185. * \return 1 if `l < r`.
  1186. * 0 if `l >= r`.
  1187. */
  1188. static mbedtls_mpi_uint mpi_sub_hlp( size_t n,
  1189. mbedtls_mpi_uint *d,
  1190. const mbedtls_mpi_uint *l,
  1191. const mbedtls_mpi_uint *r )
  1192. {
  1193. size_t i;
  1194. mbedtls_mpi_uint c = 0, t, z;
  1195. for( i = 0; i < n; i++ )
  1196. {
  1197. z = ( l[i] < c ); t = l[i] - c;
  1198. c = ( t < r[i] ) + z; d[i] = t - r[i];
  1199. }
  1200. return( c );
  1201. }
  1202. /*
  1203. * Unsigned subtraction: X = |A| - |B| (HAC 14.9, 14.10)
  1204. */
  1205. /* NXP added for HW accelerators support */
  1206. #if defined(MBEDTLS_MPI_SUB_ABS_ALT)
  1207. int mbedtls_mpi_sub_abs_orig( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
  1208. #else
  1209. int mbedtls_mpi_sub_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
  1210. #endif /* MBEDTLS_MPI_SUB_ABS_ALT */
  1211. {
  1212. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1213. size_t n;
  1214. mbedtls_mpi_uint carry;
  1215. MPI_VALIDATE_RET( X != NULL );
  1216. MPI_VALIDATE_RET( A != NULL );
  1217. MPI_VALIDATE_RET( B != NULL );
  1218. for( n = B->n; n > 0; n-- )
  1219. if( B->p[n - 1] != 0 )
  1220. break;
  1221. if( n > A->n )
  1222. {
  1223. /* B >= (2^ciL)^n > A */
  1224. ret = MBEDTLS_ERR_MPI_NEGATIVE_VALUE;
  1225. goto cleanup;
  1226. }
  1227. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, A->n ) );
  1228. /* Set the high limbs of X to match A. Don't touch the lower limbs
  1229. * because X might be aliased to B, and we must not overwrite the
  1230. * significant digits of B. */
  1231. if( A->n > n )
  1232. memcpy( X->p + n, A->p + n, ( A->n - n ) * ciL );
  1233. if( X->n > A->n )
  1234. memset( X->p + A->n, 0, ( X->n - A->n ) * ciL );
  1235. carry = mpi_sub_hlp( n, X->p, A->p, B->p );
  1236. if( carry != 0 )
  1237. {
  1238. /* Propagate the carry to the first nonzero limb of X. */
  1239. for( ; n < X->n && X->p[n] == 0; n++ )
  1240. --X->p[n];
  1241. /* If we ran out of space for the carry, it means that the result
  1242. * is negative. */
  1243. if( n == X->n )
  1244. {
  1245. ret = MBEDTLS_ERR_MPI_NEGATIVE_VALUE;
  1246. goto cleanup;
  1247. }
  1248. --X->p[n];
  1249. }
  1250. /* X should always be positive as a result of unsigned subtractions. */
  1251. X->s = 1;
  1252. cleanup:
  1253. return( ret );
  1254. }
  1255. /*
  1256. * Signed addition: X = A + B
  1257. */
  1258. int mbedtls_mpi_add_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
  1259. {
  1260. int ret, s;
  1261. MPI_VALIDATE_RET( X != NULL );
  1262. MPI_VALIDATE_RET( A != NULL );
  1263. MPI_VALIDATE_RET( B != NULL );
  1264. s = A->s;
  1265. if( A->s * B->s < 0 )
  1266. {
  1267. if( mbedtls_mpi_cmp_abs( A, B ) >= 0 )
  1268. {
  1269. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( X, A, B ) );
  1270. X->s = s;
  1271. }
  1272. else
  1273. {
  1274. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( X, B, A ) );
  1275. X->s = -s;
  1276. }
  1277. }
  1278. else
  1279. {
  1280. MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( X, A, B ) );
  1281. X->s = s;
  1282. }
  1283. cleanup:
  1284. return( ret );
  1285. }
  1286. /*
  1287. * Signed subtraction: X = A - B
  1288. */
  1289. int mbedtls_mpi_sub_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
  1290. {
  1291. int ret, s;
  1292. MPI_VALIDATE_RET( X != NULL );
  1293. MPI_VALIDATE_RET( A != NULL );
  1294. MPI_VALIDATE_RET( B != NULL );
  1295. s = A->s;
  1296. if( A->s * B->s > 0 )
  1297. {
  1298. if( mbedtls_mpi_cmp_abs( A, B ) >= 0 )
  1299. {
  1300. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( X, A, B ) );
  1301. X->s = s;
  1302. }
  1303. else
  1304. {
  1305. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( X, B, A ) );
  1306. X->s = -s;
  1307. }
  1308. }
  1309. else
  1310. {
  1311. MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( X, A, B ) );
  1312. X->s = s;
  1313. }
  1314. cleanup:
  1315. return( ret );
  1316. }
  1317. /*
  1318. * Signed addition: X = A + b
  1319. */
  1320. int mbedtls_mpi_add_int( mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_sint b )
  1321. {
  1322. mbedtls_mpi _B;
  1323. mbedtls_mpi_uint p[1];
  1324. MPI_VALIDATE_RET( X != NULL );
  1325. MPI_VALIDATE_RET( A != NULL );
  1326. p[0] = ( b < 0 ) ? -b : b;
  1327. _B.s = ( b < 0 ) ? -1 : 1;
  1328. _B.n = 1;
  1329. _B.p = p;
  1330. return( mbedtls_mpi_add_mpi( X, A, &_B ) );
  1331. }
  1332. /*
  1333. * Signed subtraction: X = A - b
  1334. */
  1335. int mbedtls_mpi_sub_int( mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_sint b )
  1336. {
  1337. mbedtls_mpi _B;
  1338. mbedtls_mpi_uint p[1];
  1339. MPI_VALIDATE_RET( X != NULL );
  1340. MPI_VALIDATE_RET( A != NULL );
  1341. p[0] = ( b < 0 ) ? -b : b;
  1342. _B.s = ( b < 0 ) ? -1 : 1;
  1343. _B.n = 1;
  1344. _B.p = p;
  1345. return( mbedtls_mpi_sub_mpi( X, A, &_B ) );
  1346. }
  1347. /** Helper for mbedtls_mpi multiplication.
  1348. *
  1349. * Add \p b * \p s to \p d.
  1350. *
  1351. * \param i The number of limbs of \p s.
  1352. * \param[in] s A bignum to multiply, of size \p i.
  1353. * It may overlap with \p d, but only if
  1354. * \p d <= \p s.
  1355. * Its leading limb must not be \c 0.
  1356. * \param[in,out] d The bignum to add to.
  1357. * It must be sufficiently large to store the
  1358. * result of the multiplication. This means
  1359. * \p i + 1 limbs if \p d[\p i - 1] started as 0 and \p b
  1360. * is not known a priori.
  1361. * \param b A scalar to multiply.
  1362. */
  1363. static
  1364. #if defined(__APPLE__) && defined(__arm__)
  1365. /*
  1366. * Apple LLVM version 4.2 (clang-425.0.24) (based on LLVM 3.2svn)
  1367. * appears to need this to prevent bad ARM code generation at -O3.
  1368. */
  1369. __attribute__ ((noinline))
  1370. #endif
  1371. void mpi_mul_hlp( size_t i,
  1372. const mbedtls_mpi_uint *s,
  1373. mbedtls_mpi_uint *d,
  1374. mbedtls_mpi_uint b )
  1375. {
  1376. mbedtls_mpi_uint c = 0, t = 0;
  1377. #if defined(MULADDC_HUIT)
  1378. for( ; i >= 8; i -= 8 )
  1379. {
  1380. MULADDC_INIT
  1381. MULADDC_HUIT
  1382. MULADDC_STOP
  1383. }
  1384. for( ; i > 0; i-- )
  1385. {
  1386. MULADDC_INIT
  1387. MULADDC_CORE
  1388. MULADDC_STOP
  1389. }
  1390. #else /* MULADDC_HUIT */
  1391. for( ; i >= 16; i -= 16 )
  1392. {
  1393. MULADDC_INIT
  1394. MULADDC_CORE MULADDC_CORE
  1395. MULADDC_CORE MULADDC_CORE
  1396. MULADDC_CORE MULADDC_CORE
  1397. MULADDC_CORE MULADDC_CORE
  1398. MULADDC_CORE MULADDC_CORE
  1399. MULADDC_CORE MULADDC_CORE
  1400. MULADDC_CORE MULADDC_CORE
  1401. MULADDC_CORE MULADDC_CORE
  1402. MULADDC_STOP
  1403. }
  1404. for( ; i >= 8; i -= 8 )
  1405. {
  1406. MULADDC_INIT
  1407. MULADDC_CORE MULADDC_CORE
  1408. MULADDC_CORE MULADDC_CORE
  1409. MULADDC_CORE MULADDC_CORE
  1410. MULADDC_CORE MULADDC_CORE
  1411. MULADDC_STOP
  1412. }
  1413. for( ; i > 0; i-- )
  1414. {
  1415. MULADDC_INIT
  1416. MULADDC_CORE
  1417. MULADDC_STOP
  1418. }
  1419. #endif /* MULADDC_HUIT */
  1420. t++;
  1421. while( c != 0 )
  1422. {
  1423. *d += c; c = ( *d < c ); d++;
  1424. }
  1425. }
  1426. /*
  1427. * Baseline multiplication: X = A * B (HAC 14.12)
  1428. */
  1429. /* NXP added for HW accelerators support */
  1430. #if defined(MBEDTLS_MPI_MUL_MPI_ALT)
  1431. int mbedtls_mpi_mul_mpi_orig( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
  1432. #else
  1433. int mbedtls_mpi_mul_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
  1434. #endif /* MBEDTLS_MPI_MUL_MPI_ALT */
  1435. {
  1436. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1437. size_t i, j;
  1438. mbedtls_mpi TA, TB;
  1439. int result_is_zero = 0;
  1440. MPI_VALIDATE_RET( X != NULL );
  1441. MPI_VALIDATE_RET( A != NULL );
  1442. MPI_VALIDATE_RET( B != NULL );
  1443. mbedtls_mpi_init( &TA ); mbedtls_mpi_init( &TB );
  1444. if( X == A ) { MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TA, A ) ); A = &TA; }
  1445. if( X == B ) { MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, B ) ); B = &TB; }
  1446. for( i = A->n; i > 0; i-- )
  1447. if( A->p[i - 1] != 0 )
  1448. break;
  1449. if( i == 0 )
  1450. result_is_zero = 1;
  1451. for( j = B->n; j > 0; j-- )
  1452. if( B->p[j - 1] != 0 )
  1453. break;
  1454. if( j == 0 )
  1455. result_is_zero = 1;
  1456. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i + j ) );
  1457. MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );
  1458. for( ; j > 0; j-- )
  1459. mpi_mul_hlp( i, A->p, X->p + j - 1, B->p[j - 1] );
  1460. /* If the result is 0, we don't shortcut the operation, which reduces
  1461. * but does not eliminate side channels leaking the zero-ness. We do
  1462. * need to take care to set the sign bit properly since the library does
  1463. * not fully support an MPI object with a value of 0 and s == -1. */
  1464. if( result_is_zero )
  1465. X->s = 1;
  1466. else
  1467. X->s = A->s * B->s;
  1468. cleanup:
  1469. mbedtls_mpi_free( &TB ); mbedtls_mpi_free( &TA );
  1470. return( ret );
  1471. }
  1472. /*
  1473. * Baseline multiplication: X = A * b
  1474. */
  1475. int mbedtls_mpi_mul_int( mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_uint b )
  1476. {
  1477. MPI_VALIDATE_RET( X != NULL );
  1478. MPI_VALIDATE_RET( A != NULL );
  1479. /* mpi_mul_hlp can't deal with a leading 0. */
  1480. size_t n = A->n;
  1481. while( n > 0 && A->p[n - 1] == 0 )
  1482. --n;
  1483. /* The general method below doesn't work if n==0 or b==0. By chance
  1484. * calculating the result is trivial in those cases. */
  1485. if( b == 0 || n == 0 )
  1486. {
  1487. return( mbedtls_mpi_lset( X, 0 ) );
  1488. }
  1489. /* Calculate A*b as A + A*(b-1) to take advantage of mpi_mul_hlp */
  1490. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1491. /* In general, A * b requires 1 limb more than b. If
  1492. * A->p[n - 1] * b / b == A->p[n - 1], then A * b fits in the same
  1493. * number of limbs as A and the call to grow() is not required since
  1494. * copy() will take care of the growth if needed. However, experimentally,
  1495. * making the call to grow() unconditional causes slightly fewer
  1496. * calls to calloc() in ECP code, presumably because it reuses the
  1497. * same mpi for a while and this way the mpi is more likely to directly
  1498. * grow to its final size. */
  1499. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, n + 1 ) );
  1500. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, A ) );
  1501. mpi_mul_hlp( n, A->p, X->p, b - 1 );
  1502. cleanup:
  1503. return( ret );
  1504. }
  1505. /*
  1506. * Unsigned integer divide - double mbedtls_mpi_uint dividend, u1/u0, and
  1507. * mbedtls_mpi_uint divisor, d
  1508. */
  1509. static mbedtls_mpi_uint mbedtls_int_div_int( mbedtls_mpi_uint u1,
  1510. mbedtls_mpi_uint u0, mbedtls_mpi_uint d, mbedtls_mpi_uint *r )
  1511. {
  1512. #if defined(MBEDTLS_HAVE_UDBL)
  1513. mbedtls_t_udbl dividend, quotient;
  1514. #else
  1515. const mbedtls_mpi_uint radix = (mbedtls_mpi_uint) 1 << biH;
  1516. const mbedtls_mpi_uint uint_halfword_mask = ( (mbedtls_mpi_uint) 1 << biH ) - 1;
  1517. mbedtls_mpi_uint d0, d1, q0, q1, rAX, r0, quotient;
  1518. mbedtls_mpi_uint u0_msw, u0_lsw;
  1519. size_t s;
  1520. #endif
  1521. /*
  1522. * Check for overflow
  1523. */
  1524. if( 0 == d || u1 >= d )
  1525. {
  1526. if (r != NULL) *r = ~0;
  1527. return ( ~0 );
  1528. }
  1529. #if defined(MBEDTLS_HAVE_UDBL)
  1530. dividend = (mbedtls_t_udbl) u1 << biL;
  1531. dividend |= (mbedtls_t_udbl) u0;
  1532. quotient = dividend / d;
  1533. if( quotient > ( (mbedtls_t_udbl) 1 << biL ) - 1 )
  1534. quotient = ( (mbedtls_t_udbl) 1 << biL ) - 1;
  1535. if( r != NULL )
  1536. *r = (mbedtls_mpi_uint)( dividend - (quotient * d ) );
  1537. return (mbedtls_mpi_uint) quotient;
  1538. #else
  1539. /*
  1540. * Algorithm D, Section 4.3.1 - The Art of Computer Programming
  1541. * Vol. 2 - Seminumerical Algorithms, Knuth
  1542. */
  1543. /*
  1544. * Normalize the divisor, d, and dividend, u0, u1
  1545. */
  1546. s = mbedtls_clz( d );
  1547. d = d << s;
  1548. u1 = u1 << s;
  1549. u1 |= ( u0 >> ( biL - s ) ) & ( -(mbedtls_mpi_sint)s >> ( biL - 1 ) );
  1550. u0 = u0 << s;
  1551. d1 = d >> biH;
  1552. d0 = d & uint_halfword_mask;
  1553. u0_msw = u0 >> biH;
  1554. u0_lsw = u0 & uint_halfword_mask;
  1555. /*
  1556. * Find the first quotient and remainder
  1557. */
  1558. q1 = u1 / d1;
  1559. r0 = u1 - d1 * q1;
  1560. while( q1 >= radix || ( q1 * d0 > radix * r0 + u0_msw ) )
  1561. {
  1562. q1 -= 1;
  1563. r0 += d1;
  1564. if ( r0 >= radix ) break;
  1565. }
  1566. rAX = ( u1 * radix ) + ( u0_msw - q1 * d );
  1567. q0 = rAX / d1;
  1568. r0 = rAX - q0 * d1;
  1569. while( q0 >= radix || ( q0 * d0 > radix * r0 + u0_lsw ) )
  1570. {
  1571. q0 -= 1;
  1572. r0 += d1;
  1573. if ( r0 >= radix ) break;
  1574. }
  1575. if (r != NULL)
  1576. *r = ( rAX * radix + u0_lsw - q0 * d ) >> s;
  1577. quotient = q1 * radix + q0;
  1578. return quotient;
  1579. #endif
  1580. }
  1581. /*
  1582. * Division by mbedtls_mpi: A = Q * B + R (HAC 14.20)
  1583. */
  1584. int mbedtls_mpi_div_mpi( mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A,
  1585. const mbedtls_mpi *B )
  1586. {
  1587. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1588. size_t i, n, t, k;
  1589. mbedtls_mpi X, Y, Z, T1, T2;
  1590. mbedtls_mpi_uint TP2[3];
  1591. MPI_VALIDATE_RET( A != NULL );
  1592. MPI_VALIDATE_RET( B != NULL );
  1593. if( mbedtls_mpi_cmp_int( B, 0 ) == 0 )
  1594. return( MBEDTLS_ERR_MPI_DIVISION_BY_ZERO );
  1595. mbedtls_mpi_init( &X ); mbedtls_mpi_init( &Y ); mbedtls_mpi_init( &Z );
  1596. mbedtls_mpi_init( &T1 );
  1597. /*
  1598. * Avoid dynamic memory allocations for constant-size T2.
  1599. *
  1600. * T2 is used for comparison only and the 3 limbs are assigned explicitly,
  1601. * so nobody increase the size of the MPI and we're safe to use an on-stack
  1602. * buffer.
  1603. */
  1604. T2.s = 1;
  1605. T2.n = sizeof( TP2 ) / sizeof( *TP2 );
  1606. T2.p = TP2;
  1607. if( mbedtls_mpi_cmp_abs( A, B ) < 0 )
  1608. {
  1609. if( Q != NULL ) MBEDTLS_MPI_CHK( mbedtls_mpi_lset( Q, 0 ) );
  1610. if( R != NULL ) MBEDTLS_MPI_CHK( mbedtls_mpi_copy( R, A ) );
  1611. return( 0 );
  1612. }
  1613. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &X, A ) );
  1614. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Y, B ) );
  1615. X.s = Y.s = 1;
  1616. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &Z, A->n + 2 ) );
  1617. MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &Z, 0 ) );
  1618. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &T1, A->n + 2 ) );
  1619. k = mbedtls_mpi_bitlen( &Y ) % biL;
  1620. if( k < biL - 1 )
  1621. {
  1622. k = biL - 1 - k;
  1623. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &X, k ) );
  1624. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &Y, k ) );
  1625. }
  1626. else k = 0;
  1627. n = X.n - 1;
  1628. t = Y.n - 1;
  1629. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &Y, biL * ( n - t ) ) );
  1630. while( mbedtls_mpi_cmp_mpi( &X, &Y ) >= 0 )
  1631. {
  1632. Z.p[n - t]++;
  1633. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &X, &X, &Y ) );
  1634. }
  1635. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &Y, biL * ( n - t ) ) );
  1636. for( i = n; i > t ; i-- )
  1637. {
  1638. if( X.p[i] >= Y.p[t] )
  1639. Z.p[i - t - 1] = ~0;
  1640. else
  1641. {
  1642. Z.p[i - t - 1] = mbedtls_int_div_int( X.p[i], X.p[i - 1],
  1643. Y.p[t], NULL);
  1644. }
  1645. T2.p[0] = ( i < 2 ) ? 0 : X.p[i - 2];
  1646. T2.p[1] = ( i < 1 ) ? 0 : X.p[i - 1];
  1647. T2.p[2] = X.p[i];
  1648. Z.p[i - t - 1]++;
  1649. do
  1650. {
  1651. Z.p[i - t - 1]--;
  1652. MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &T1, 0 ) );
  1653. T1.p[0] = ( t < 1 ) ? 0 : Y.p[t - 1];
  1654. T1.p[1] = Y.p[t];
  1655. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &T1, &T1, Z.p[i - t - 1] ) );
  1656. }
  1657. while( mbedtls_mpi_cmp_mpi( &T1, &T2 ) > 0 );
  1658. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &T1, &Y, Z.p[i - t - 1] ) );
  1659. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &T1, biL * ( i - t - 1 ) ) );
  1660. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &X, &X, &T1 ) );
  1661. if( mbedtls_mpi_cmp_int( &X, 0 ) < 0 )
  1662. {
  1663. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &T1, &Y ) );
  1664. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &T1, biL * ( i - t - 1 ) ) );
  1665. MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &X, &X, &T1 ) );
  1666. Z.p[i - t - 1]--;
  1667. }
  1668. }
  1669. if( Q != NULL )
  1670. {
  1671. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( Q, &Z ) );
  1672. Q->s = A->s * B->s;
  1673. }
  1674. if( R != NULL )
  1675. {
  1676. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &X, k ) );
  1677. X.s = A->s;
  1678. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( R, &X ) );
  1679. if( mbedtls_mpi_cmp_int( R, 0 ) == 0 )
  1680. R->s = 1;
  1681. }
  1682. cleanup:
  1683. mbedtls_mpi_free( &X ); mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &Z );
  1684. mbedtls_mpi_free( &T1 );
  1685. mbedtls_platform_zeroize( TP2, sizeof( TP2 ) );
  1686. return( ret );
  1687. }
  1688. /*
  1689. * Division by int: A = Q * b + R
  1690. */
  1691. int mbedtls_mpi_div_int( mbedtls_mpi *Q, mbedtls_mpi *R,
  1692. const mbedtls_mpi *A,
  1693. mbedtls_mpi_sint b )
  1694. {
  1695. mbedtls_mpi _B;
  1696. mbedtls_mpi_uint p[1];
  1697. MPI_VALIDATE_RET( A != NULL );
  1698. p[0] = ( b < 0 ) ? -b : b;
  1699. _B.s = ( b < 0 ) ? -1 : 1;
  1700. _B.n = 1;
  1701. _B.p = p;
  1702. return( mbedtls_mpi_div_mpi( Q, R, A, &_B ) );
  1703. }
  1704. /*
  1705. * Modulo: R = A mod B
  1706. */
  1707. /* NXP added for HW accelerators support */
  1708. #if defined(MBEDTLS_MPI_MOD_MPI_ALT)
  1709. int mbedtls_mpi_mod_mpi_orig( mbedtls_mpi *R, const mbedtls_mpi *A, const mbedtls_mpi *B )
  1710. #else
  1711. int mbedtls_mpi_mod_mpi( mbedtls_mpi *R, const mbedtls_mpi *A, const mbedtls_mpi *B )
  1712. #endif /* MBEDTLS_MPI_MOD_MPI_ALT */
  1713. {
  1714. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1715. MPI_VALIDATE_RET( R != NULL );
  1716. MPI_VALIDATE_RET( A != NULL );
  1717. MPI_VALIDATE_RET( B != NULL );
  1718. if( mbedtls_mpi_cmp_int( B, 0 ) < 0 )
  1719. return( MBEDTLS_ERR_MPI_NEGATIVE_VALUE );
  1720. MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( NULL, R, A, B ) );
  1721. while( mbedtls_mpi_cmp_int( R, 0 ) < 0 )
  1722. MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( R, R, B ) );
  1723. while( mbedtls_mpi_cmp_mpi( R, B ) >= 0 )
  1724. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( R, R, B ) );
  1725. cleanup:
  1726. return( ret );
  1727. }
  1728. /*
  1729. * Modulo: r = A mod b
  1730. */
  1731. int mbedtls_mpi_mod_int( mbedtls_mpi_uint *r, const mbedtls_mpi *A, mbedtls_mpi_sint b )
  1732. {
  1733. size_t i;
  1734. mbedtls_mpi_uint x, y, z;
  1735. MPI_VALIDATE_RET( r != NULL );
  1736. MPI_VALIDATE_RET( A != NULL );
  1737. if( b == 0 )
  1738. return( MBEDTLS_ERR_MPI_DIVISION_BY_ZERO );
  1739. if( b < 0 )
  1740. return( MBEDTLS_ERR_MPI_NEGATIVE_VALUE );
  1741. /*
  1742. * handle trivial cases
  1743. */
  1744. if( b == 1 )
  1745. {
  1746. *r = 0;
  1747. return( 0 );
  1748. }
  1749. if( b == 2 )
  1750. {
  1751. *r = A->p[0] & 1;
  1752. return( 0 );
  1753. }
  1754. /*
  1755. * general case
  1756. */
  1757. for( i = A->n, y = 0; i > 0; i-- )
  1758. {
  1759. x = A->p[i - 1];
  1760. y = ( y << biH ) | ( x >> biH );
  1761. z = y / b;
  1762. y -= z * b;
  1763. x <<= biH;
  1764. y = ( y << biH ) | ( x >> biH );
  1765. z = y / b;
  1766. y -= z * b;
  1767. }
  1768. /*
  1769. * If A is negative, then the current y represents a negative value.
  1770. * Flipping it to the positive side.
  1771. */
  1772. if( A->s < 0 && y != 0 )
  1773. y = b - y;
  1774. *r = y;
  1775. return( 0 );
  1776. }
  1777. /*
  1778. * Fast Montgomery initialization (thanks to Tom St Denis)
  1779. */
  1780. static void mpi_montg_init( mbedtls_mpi_uint *mm, const mbedtls_mpi *N )
  1781. {
  1782. mbedtls_mpi_uint x, m0 = N->p[0];
  1783. unsigned int i;
  1784. x = m0;
  1785. x += ( ( m0 + 2 ) & 4 ) << 1;
  1786. for( i = biL; i >= 8; i /= 2 )
  1787. x *= ( 2 - ( m0 * x ) );
  1788. *mm = ~x + 1;
  1789. }
  1790. /** Montgomery multiplication: A = A * B * R^-1 mod N (HAC 14.36)
  1791. *
  1792. * \param[in,out] A One of the numbers to multiply.
  1793. * It must have at least as many limbs as N
  1794. * (A->n >= N->n), and any limbs beyond n are ignored.
  1795. * On successful completion, A contains the result of
  1796. * the multiplication A * B * R^-1 mod N where
  1797. * R = (2^ciL)^n.
  1798. * \param[in] B One of the numbers to multiply.
  1799. * It must be nonzero and must not have more limbs than N
  1800. * (B->n <= N->n).
  1801. * \param[in] N The modulo. N must be odd.
  1802. * \param mm The value calculated by `mpi_montg_init(&mm, N)`.
  1803. * This is -N^-1 mod 2^ciL.
  1804. * \param[in,out] T A bignum for temporary storage.
  1805. * It must be at least twice the limb size of N plus 2
  1806. * (T->n >= 2 * (N->n + 1)).
  1807. * Its initial content is unused and
  1808. * its final content is indeterminate.
  1809. * Note that unlike the usual convention in the library
  1810. * for `const mbedtls_mpi*`, the content of T can change.
  1811. */
  1812. static void mpi_montmul( mbedtls_mpi *A, const mbedtls_mpi *B, const mbedtls_mpi *N, mbedtls_mpi_uint mm,
  1813. const mbedtls_mpi *T )
  1814. {
  1815. size_t i, n, m;
  1816. mbedtls_mpi_uint u0, u1, *d;
  1817. memset( T->p, 0, T->n * ciL );
  1818. d = T->p;
  1819. n = N->n;
  1820. m = ( B->n < n ) ? B->n : n;
  1821. for( i = 0; i < n; i++ )
  1822. {
  1823. /*
  1824. * T = (T + u0*B + u1*N) / 2^biL
  1825. */
  1826. u0 = A->p[i];
  1827. u1 = ( d[0] + u0 * B->p[0] ) * mm;
  1828. mpi_mul_hlp( m, B->p, d, u0 );
  1829. mpi_mul_hlp( n, N->p, d, u1 );
  1830. *d++ = u0; d[n + 1] = 0;
  1831. }
  1832. /* At this point, d is either the desired result or the desired result
  1833. * plus N. We now potentially subtract N, avoiding leaking whether the
  1834. * subtraction is performed through side channels. */
  1835. /* Copy the n least significant limbs of d to A, so that
  1836. * A = d if d < N (recall that N has n limbs). */
  1837. memcpy( A->p, d, n * ciL );
  1838. /* If d >= N then we want to set A to d - N. To prevent timing attacks,
  1839. * do the calculation without using conditional tests. */
  1840. /* Set d to d0 + (2^biL)^n - N where d0 is the current value of d. */
  1841. d[n] += 1;
  1842. d[n] -= mpi_sub_hlp( n, d, d, N->p );
  1843. /* If d0 < N then d < (2^biL)^n
  1844. * so d[n] == 0 and we want to keep A as it is.
  1845. * If d0 >= N then d >= (2^biL)^n, and d <= (2^biL)^n + N < 2 * (2^biL)^n
  1846. * so d[n] == 1 and we want to set A to the result of the subtraction
  1847. * which is d - (2^biL)^n, i.e. the n least significant limbs of d.
  1848. * This exactly corresponds to a conditional assignment. */
  1849. mpi_safe_cond_assign( n, A->p, d, (unsigned char) d[n] );
  1850. }
  1851. /*
  1852. * Montgomery reduction: A = A * R^-1 mod N
  1853. *
  1854. * See mpi_montmul() regarding constraints and guarantees on the parameters.
  1855. */
  1856. static void mpi_montred( mbedtls_mpi *A, const mbedtls_mpi *N,
  1857. mbedtls_mpi_uint mm, const mbedtls_mpi *T )
  1858. {
  1859. mbedtls_mpi_uint z = 1;
  1860. mbedtls_mpi U;
  1861. U.n = U.s = (int) z;
  1862. U.p = &z;
  1863. mpi_montmul( A, &U, N, mm, T );
  1864. }
  1865. /*
  1866. * Constant-flow boolean "equal" comparison:
  1867. * return x == y
  1868. *
  1869. * This function can be used to write constant-time code by replacing branches
  1870. * with bit operations - it can be used in conjunction with
  1871. * mbedtls_ssl_cf_mask_from_bit().
  1872. *
  1873. * This function is implemented without using comparison operators, as those
  1874. * might be translated to branches by some compilers on some platforms.
  1875. */
  1876. static size_t mbedtls_mpi_cf_bool_eq( size_t x, size_t y )
  1877. {
  1878. /* diff = 0 if x == y, non-zero otherwise */
  1879. const size_t diff = x ^ y;
  1880. /* MSVC has a warning about unary minus on unsigned integer types,
  1881. * but this is well-defined and precisely what we want to do here. */
  1882. #if defined(_MSC_VER)
  1883. #pragma warning( push )
  1884. #pragma warning( disable : 4146 )
  1885. #endif
  1886. /* diff_msb's most significant bit is equal to x != y */
  1887. const size_t diff_msb = ( diff | (size_t) -diff );
  1888. #if defined(_MSC_VER)
  1889. #pragma warning( pop )
  1890. #endif
  1891. /* diff1 = (x != y) ? 1 : 0 */
  1892. const size_t diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 );
  1893. return( 1 ^ diff1 );
  1894. }
  1895. /**
  1896. * Select an MPI from a table without leaking the index.
  1897. *
  1898. * This is functionally equivalent to mbedtls_mpi_copy(R, T[idx]) except it
  1899. * reads the entire table in order to avoid leaking the value of idx to an
  1900. * attacker able to observe memory access patterns.
  1901. *
  1902. * \param[out] R Where to write the selected MPI.
  1903. * \param[in] T The table to read from.
  1904. * \param[in] T_size The number of elements in the table.
  1905. * \param[in] idx The index of the element to select;
  1906. * this must satisfy 0 <= idx < T_size.
  1907. *
  1908. * \return \c 0 on success, or a negative error code.
  1909. */
  1910. static int mpi_select( mbedtls_mpi *R, const mbedtls_mpi *T, size_t T_size, size_t idx )
  1911. {
  1912. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1913. for( size_t i = 0; i < T_size; i++ )
  1914. {
  1915. MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( R, &T[i],
  1916. (unsigned char) mbedtls_mpi_cf_bool_eq( i, idx ) ) );
  1917. }
  1918. cleanup:
  1919. return( ret );
  1920. }
  1921. /*
  1922. * Sliding-window exponentiation: X = A^E mod N (HAC 14.85)
  1923. */
  1924. /* NXP added for HW accelerators support */
  1925. #if defined(MBEDTLS_MPI_EXP_MOD_ALT)
  1926. int mbedtls_mpi_exp_mod_orig( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *E, const mbedtls_mpi *N, mbedtls_mpi *_RR )
  1927. #else
  1928. int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A,
  1929. const mbedtls_mpi *E, const mbedtls_mpi *N,
  1930. mbedtls_mpi *_RR )
  1931. #endif /* MBEDTLS_MPI_EXP_MOD_ALT */
  1932. {
  1933. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1934. size_t wbits, wsize, one = 1;
  1935. size_t i, j, nblimbs;
  1936. size_t bufsize, nbits;
  1937. mbedtls_mpi_uint ei, mm, state;
  1938. mbedtls_mpi RR, T, W[ 1 << MBEDTLS_MPI_WINDOW_SIZE ], WW, Apos;
  1939. int neg;
  1940. MPI_VALIDATE_RET( X != NULL );
  1941. MPI_VALIDATE_RET( A != NULL );
  1942. MPI_VALIDATE_RET( E != NULL );
  1943. MPI_VALIDATE_RET( N != NULL );
  1944. if( mbedtls_mpi_cmp_int( N, 0 ) <= 0 || ( N->p[0] & 1 ) == 0 )
  1945. return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
  1946. if( mbedtls_mpi_cmp_int( E, 0 ) < 0 )
  1947. return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
  1948. if( mbedtls_mpi_bitlen( E ) > MBEDTLS_MPI_MAX_BITS ||
  1949. mbedtls_mpi_bitlen( N ) > MBEDTLS_MPI_MAX_BITS )
  1950. return ( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
  1951. /*
  1952. * Init temps and window size
  1953. */
  1954. mpi_montg_init( &mm, N );
  1955. mbedtls_mpi_init( &RR ); mbedtls_mpi_init( &T );
  1956. mbedtls_mpi_init( &Apos );
  1957. mbedtls_mpi_init( &WW );
  1958. memset( W, 0, sizeof( W ) );
  1959. i = mbedtls_mpi_bitlen( E );
  1960. wsize = ( i > 671 ) ? 6 : ( i > 239 ) ? 5 :
  1961. ( i > 79 ) ? 4 : ( i > 23 ) ? 3 : 1;
  1962. #if( MBEDTLS_MPI_WINDOW_SIZE < 6 )
  1963. if( wsize > MBEDTLS_MPI_WINDOW_SIZE )
  1964. wsize = MBEDTLS_MPI_WINDOW_SIZE;
  1965. #endif
  1966. j = N->n + 1;
  1967. /* All W[i] and X must have at least N->n limbs for the mpi_montmul()
  1968. * and mpi_montred() calls later. Here we ensure that W[1] and X are
  1969. * large enough, and later we'll grow other W[i] to the same length.
  1970. * They must not be shrunk midway through this function!
  1971. */
  1972. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, j ) );
  1973. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[1], j ) );
  1974. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &T, j * 2 ) );
  1975. /*
  1976. * Compensate for negative A (and correct at the end)
  1977. */
  1978. neg = ( A->s == -1 );
  1979. if( neg )
  1980. {
  1981. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Apos, A ) );
  1982. Apos.s = 1;
  1983. A = &Apos;
  1984. }
  1985. /*
  1986. * If 1st call, pre-compute R^2 mod N
  1987. */
  1988. if( _RR == NULL || _RR->p == NULL )
  1989. {
  1990. MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &RR, 1 ) );
  1991. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &RR, N->n * 2 * biL ) );
  1992. MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &RR, &RR, N ) );
  1993. if( _RR != NULL )
  1994. memcpy( _RR, &RR, sizeof( mbedtls_mpi ) );
  1995. }
  1996. else
  1997. memcpy( &RR, _RR, sizeof( mbedtls_mpi ) );
  1998. /*
  1999. * W[1] = A * R^2 * R^-1 mod N = A * R mod N
  2000. */
  2001. if( mbedtls_mpi_cmp_mpi( A, N ) >= 0 )
  2002. {
  2003. MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &W[1], A, N ) );
  2004. /* This should be a no-op because W[1] is already that large before
  2005. * mbedtls_mpi_mod_mpi(), but it's necessary to avoid an overflow
  2006. * in mpi_montmul() below, so let's make sure. */
  2007. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[1], N->n + 1 ) );
  2008. }
  2009. else
  2010. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[1], A ) );
  2011. /* Note that this is safe because W[1] always has at least N->n limbs
  2012. * (it grew above and was preserved by mbedtls_mpi_copy()). */
  2013. mpi_montmul( &W[1], &RR, N, mm, &T );
  2014. /*
  2015. * X = R^2 * R^-1 mod N = R mod N
  2016. */
  2017. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, &RR ) );
  2018. mpi_montred( X, N, mm, &T );
  2019. if( wsize > 1 )
  2020. {
  2021. /*
  2022. * W[1 << (wsize - 1)] = W[1] ^ (wsize - 1)
  2023. */
  2024. j = one << ( wsize - 1 );
  2025. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[j], N->n + 1 ) );
  2026. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[j], &W[1] ) );
  2027. for( i = 0; i < wsize - 1; i++ )
  2028. mpi_montmul( &W[j], &W[j], N, mm, &T );
  2029. /*
  2030. * W[i] = W[i - 1] * W[1]
  2031. */
  2032. for( i = j + 1; i < ( one << wsize ); i++ )
  2033. {
  2034. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[i], N->n + 1 ) );
  2035. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[i], &W[i - 1] ) );
  2036. mpi_montmul( &W[i], &W[1], N, mm, &T );
  2037. }
  2038. }
  2039. nblimbs = E->n;
  2040. bufsize = 0;
  2041. nbits = 0;
  2042. wbits = 0;
  2043. state = 0;
  2044. while( 1 )
  2045. {
  2046. if( bufsize == 0 )
  2047. {
  2048. if( nblimbs == 0 )
  2049. break;
  2050. nblimbs--;
  2051. bufsize = sizeof( mbedtls_mpi_uint ) << 3;
  2052. }
  2053. bufsize--;
  2054. ei = (E->p[nblimbs] >> bufsize) & 1;
  2055. /*
  2056. * skip leading 0s
  2057. */
  2058. if( ei == 0 && state == 0 )
  2059. continue;
  2060. if( ei == 0 && state == 1 )
  2061. {
  2062. /*
  2063. * out of window, square X
  2064. */
  2065. mpi_montmul( X, X, N, mm, &T );
  2066. continue;
  2067. }
  2068. /*
  2069. * add ei to current window
  2070. */
  2071. state = 2;
  2072. nbits++;
  2073. wbits |= ( ei << ( wsize - nbits ) );
  2074. if( nbits == wsize )
  2075. {
  2076. /*
  2077. * X = X^wsize R^-1 mod N
  2078. */
  2079. for( i = 0; i < wsize; i++ )
  2080. mpi_montmul( X, X, N, mm, &T );
  2081. /*
  2082. * X = X * W[wbits] R^-1 mod N
  2083. */
  2084. MBEDTLS_MPI_CHK( mpi_select( &WW, W, (size_t) 1 << wsize, wbits ) );
  2085. mpi_montmul( X, &WW, N, mm, &T );
  2086. state--;
  2087. nbits = 0;
  2088. wbits = 0;
  2089. }
  2090. }
  2091. /*
  2092. * process the remaining bits
  2093. */
  2094. for( i = 0; i < nbits; i++ )
  2095. {
  2096. mpi_montmul( X, X, N, mm, &T );
  2097. wbits <<= 1;
  2098. if( ( wbits & ( one << wsize ) ) != 0 )
  2099. mpi_montmul( X, &W[1], N, mm, &T );
  2100. }
  2101. /*
  2102. * X = A^E * R * R^-1 mod N = A^E mod N
  2103. */
  2104. mpi_montred( X, N, mm, &T );
  2105. if( neg && E->n != 0 && ( E->p[0] & 1 ) != 0 )
  2106. {
  2107. X->s = -1;
  2108. MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( X, N, X ) );
  2109. }
  2110. cleanup:
  2111. for( i = ( one << ( wsize - 1 ) ); i < ( one << wsize ); i++ )
  2112. mbedtls_mpi_free( &W[i] );
  2113. mbedtls_mpi_free( &W[1] ); mbedtls_mpi_free( &T ); mbedtls_mpi_free( &Apos );
  2114. mbedtls_mpi_free( &WW );
  2115. if( _RR == NULL || _RR->p == NULL )
  2116. mbedtls_mpi_free( &RR );
  2117. return( ret );
  2118. }
  2119. /*
  2120. * Greatest common divisor: G = gcd(A, B) (HAC 14.54)
  2121. */
  2122. /* NXP added for HW accelerators support */
  2123. #if defined(MBEDTLS_MPI_GCD_ALT)
  2124. int mbedtls_mpi_gcd_orig( mbedtls_mpi *G, const mbedtls_mpi *A, const mbedtls_mpi *B )
  2125. #else
  2126. int mbedtls_mpi_gcd( mbedtls_mpi *G, const mbedtls_mpi *A, const mbedtls_mpi *B )
  2127. #endif /* MBEDTLS_MPI_GCD_ALT */
  2128. {
  2129. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2130. size_t lz, lzt;
  2131. mbedtls_mpi TA, TB;
  2132. MPI_VALIDATE_RET( G != NULL );
  2133. MPI_VALIDATE_RET( A != NULL );
  2134. MPI_VALIDATE_RET( B != NULL );
  2135. mbedtls_mpi_init( &TA ); mbedtls_mpi_init( &TB );
  2136. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TA, A ) );
  2137. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, B ) );
  2138. lz = mbedtls_mpi_lsb( &TA );
  2139. lzt = mbedtls_mpi_lsb( &TB );
  2140. /* The loop below gives the correct result when A==0 but not when B==0.
  2141. * So have a special case for B==0. Leverage the fact that we just
  2142. * calculated the lsb and lsb(B)==0 iff B is odd or 0 to make the test
  2143. * slightly more efficient than cmp_int(). */
  2144. if( lzt == 0 && mbedtls_mpi_get_bit( &TB, 0 ) == 0 )
  2145. {
  2146. ret = mbedtls_mpi_copy( G, A );
  2147. goto cleanup;
  2148. }
  2149. if( lzt < lz )
  2150. lz = lzt;
  2151. TA.s = TB.s = 1;
  2152. /* We mostly follow the procedure described in HAC 14.54, but with some
  2153. * minor differences:
  2154. * - Sequences of multiplications or divisions by 2 are grouped into a
  2155. * single shift operation.
  2156. * - The procedure in HAC assumes that 0 < TB <= TA.
  2157. * - The condition TB <= TA is not actually necessary for correctness.
  2158. * TA and TB have symmetric roles except for the loop termination
  2159. * condition, and the shifts at the beginning of the loop body
  2160. * remove any significance from the ordering of TA vs TB before
  2161. * the shifts.
  2162. * - If TA = 0, the loop goes through 0 iterations and the result is
  2163. * correctly TB.
  2164. * - The case TB = 0 was short-circuited above.
  2165. *
  2166. * For the correctness proof below, decompose the original values of
  2167. * A and B as
  2168. * A = sa * 2^a * A' with A'=0 or A' odd, and sa = +-1
  2169. * B = sb * 2^b * B' with B'=0 or B' odd, and sb = +-1
  2170. * Then gcd(A, B) = 2^{min(a,b)} * gcd(A',B'),
  2171. * and gcd(A',B') is odd or 0.
  2172. *
  2173. * At the beginning, we have TA = |A| and TB = |B| so gcd(A,B) = gcd(TA,TB).
  2174. * The code maintains the following invariant:
  2175. * gcd(A,B) = 2^k * gcd(TA,TB) for some k (I)
  2176. */
  2177. /* Proof that the loop terminates:
  2178. * At each iteration, either the right-shift by 1 is made on a nonzero
  2179. * value and the nonnegative integer bitlen(TA) + bitlen(TB) decreases
  2180. * by at least 1, or the right-shift by 1 is made on zero and then
  2181. * TA becomes 0 which ends the loop (TB cannot be 0 if it is right-shifted
  2182. * since in that case TB is calculated from TB-TA with the condition TB>TA).
  2183. */
  2184. while( mbedtls_mpi_cmp_int( &TA, 0 ) != 0 )
  2185. {
  2186. /* Divisions by 2 preserve the invariant (I). */
  2187. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TA, mbedtls_mpi_lsb( &TA ) ) );
  2188. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TB, mbedtls_mpi_lsb( &TB ) ) );
  2189. /* Set either TA or TB to |TA-TB|/2. Since TA and TB are both odd,
  2190. * TA-TB is even so the division by 2 has an integer result.
  2191. * Invariant (I) is preserved since any odd divisor of both TA and TB
  2192. * also divides |TA-TB|/2, and any odd divisor of both TA and |TA-TB|/2
  2193. * also divides TB, and any odd divisior of both TB and |TA-TB|/2 also
  2194. * divides TA.
  2195. */
  2196. if( mbedtls_mpi_cmp_mpi( &TA, &TB ) >= 0 )
  2197. {
  2198. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &TA, &TA, &TB ) );
  2199. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TA, 1 ) );
  2200. }
  2201. else
  2202. {
  2203. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &TB, &TB, &TA ) );
  2204. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TB, 1 ) );
  2205. }
  2206. /* Note that one of TA or TB is still odd. */
  2207. }
  2208. /* By invariant (I), gcd(A,B) = 2^k * gcd(TA,TB) for some k.
  2209. * At the loop exit, TA = 0, so gcd(TA,TB) = TB.
  2210. * - If there was at least one loop iteration, then one of TA or TB is odd,
  2211. * and TA = 0, so TB is odd and gcd(TA,TB) = gcd(A',B'). In this case,
  2212. * lz = min(a,b) so gcd(A,B) = 2^lz * TB.
  2213. * - If there was no loop iteration, then A was 0, and gcd(A,B) = B.
  2214. * In this case, lz = 0 and B = TB so gcd(A,B) = B = 2^lz * TB as well.
  2215. */
  2216. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &TB, lz ) );
  2217. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( G, &TB ) );
  2218. cleanup:
  2219. mbedtls_mpi_free( &TA ); mbedtls_mpi_free( &TB );
  2220. return( ret );
  2221. }
  2222. /* Fill X with n_bytes random bytes.
  2223. * X must already have room for those bytes.
  2224. * The ordering of the bytes returned from the RNG is suitable for
  2225. * deterministic ECDSA (see RFC 6979 §3.3 and mbedtls_mpi_random()).
  2226. * The size and sign of X are unchanged.
  2227. * n_bytes must not be 0.
  2228. */
  2229. static int mpi_fill_random_internal(
  2230. mbedtls_mpi *X, size_t n_bytes,
  2231. int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
  2232. {
  2233. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2234. const size_t limbs = CHARS_TO_LIMBS( n_bytes );
  2235. const size_t overhead = ( limbs * ciL ) - n_bytes;
  2236. if( X->n < limbs )
  2237. return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
  2238. memset( X->p, 0, overhead );
  2239. memset( (unsigned char *) X->p + limbs * ciL, 0, ( X->n - limbs ) * ciL );
  2240. MBEDTLS_MPI_CHK( f_rng( p_rng, (unsigned char *) X->p + overhead, n_bytes ) );
  2241. mpi_bigendian_to_host( X->p, limbs );
  2242. cleanup:
  2243. return( ret );
  2244. }
  2245. /*
  2246. * Fill X with size bytes of random.
  2247. *
  2248. * Use a temporary bytes representation to make sure the result is the same
  2249. * regardless of the platform endianness (useful when f_rng is actually
  2250. * deterministic, eg for tests).
  2251. */
  2252. int mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size,
  2253. int (*f_rng)(void *, unsigned char *, size_t),
  2254. void *p_rng )
  2255. {
  2256. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2257. size_t const limbs = CHARS_TO_LIMBS( size );
  2258. MPI_VALIDATE_RET( X != NULL );
  2259. MPI_VALIDATE_RET( f_rng != NULL );
  2260. /* Ensure that target MPI has exactly the necessary number of limbs */
  2261. MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, limbs ) );
  2262. if( size == 0 )
  2263. return( 0 );
  2264. ret = mpi_fill_random_internal( X, size, f_rng, p_rng );
  2265. cleanup:
  2266. return( ret );
  2267. }
  2268. int mbedtls_mpi_random( mbedtls_mpi *X,
  2269. mbedtls_mpi_sint min,
  2270. const mbedtls_mpi *N,
  2271. int (*f_rng)(void *, unsigned char *, size_t),
  2272. void *p_rng )
  2273. {
  2274. int ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  2275. int count;
  2276. unsigned lt_lower = 1, lt_upper = 0;
  2277. size_t n_bits = mbedtls_mpi_bitlen( N );
  2278. size_t n_bytes = ( n_bits + 7 ) / 8;
  2279. mbedtls_mpi lower_bound;
  2280. if( min < 0 )
  2281. return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
  2282. if( mbedtls_mpi_cmp_int( N, min ) <= 0 )
  2283. return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
  2284. /*
  2285. * When min == 0, each try has at worst a probability 1/2 of failing
  2286. * (the msb has a probability 1/2 of being 0, and then the result will
  2287. * be < N), so after 30 tries failure probability is a most 2**(-30).
  2288. *
  2289. * When N is just below a power of 2, as is the case when generating
  2290. * a random scalar on most elliptic curves, 1 try is enough with
  2291. * overwhelming probability. When N is just above a power of 2,
  2292. * as when generating a random scalar on secp224k1, each try has
  2293. * a probability of failing that is almost 1/2.
  2294. *
  2295. * The probabilities are almost the same if min is nonzero but negligible
  2296. * compared to N. This is always the case when N is crypto-sized, but
  2297. * it's convenient to support small N for testing purposes. When N
  2298. * is small, use a higher repeat count, otherwise the probability of
  2299. * failure is macroscopic.
  2300. */
  2301. count = ( n_bytes > 4 ? 30 : 250 );
  2302. mbedtls_mpi_init( &lower_bound );
  2303. /* Ensure that target MPI has exactly the same number of limbs
  2304. * as the upper bound, even if the upper bound has leading zeros.
  2305. * This is necessary for the mbedtls_mpi_lt_mpi_ct() check. */
  2306. MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, N->n ) );
  2307. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &lower_bound, N->n ) );
  2308. MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &lower_bound, min ) );
  2309. /*
  2310. * Match the procedure given in RFC 6979 §3.3 (deterministic ECDSA)
  2311. * when f_rng is a suitably parametrized instance of HMAC_DRBG:
  2312. * - use the same byte ordering;
  2313. * - keep the leftmost n_bits bits of the generated octet string;
  2314. * - try until result is in the desired range.
  2315. * This also avoids any bias, which is especially important for ECDSA.
  2316. */
  2317. do
  2318. {
  2319. MBEDTLS_MPI_CHK( mpi_fill_random_internal( X, n_bytes, f_rng, p_rng ) );
  2320. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( X, 8 * n_bytes - n_bits ) );
  2321. if( --count == 0 )
  2322. {
  2323. ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
  2324. goto cleanup;
  2325. }
  2326. MBEDTLS_MPI_CHK( mbedtls_mpi_lt_mpi_ct( X, &lower_bound, &lt_lower ) );
  2327. MBEDTLS_MPI_CHK( mbedtls_mpi_lt_mpi_ct( X, N, &lt_upper ) );
  2328. }
  2329. while( lt_lower != 0 || lt_upper == 0 );
  2330. cleanup:
  2331. mbedtls_mpi_free( &lower_bound );
  2332. return( ret );
  2333. }
  2334. /*
  2335. * Modular inverse: X = A^-1 mod N (HAC 14.61 / 14.64)
  2336. */
  2337. /* NXP added for HW accelerators support */
  2338. #if defined(MBEDTLS_MPI_INV_MOD_ALT)
  2339. int mbedtls_mpi_inv_mod_orig( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *N )
  2340. #else
  2341. int mbedtls_mpi_inv_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *N )
  2342. #endif /* MBEDTLS_MPI_INV_MOD_ALT */
  2343. {
  2344. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2345. mbedtls_mpi G, TA, TU, U1, U2, TB, TV, V1, V2;
  2346. MPI_VALIDATE_RET( X != NULL );
  2347. MPI_VALIDATE_RET( A != NULL );
  2348. MPI_VALIDATE_RET( N != NULL );
  2349. if( mbedtls_mpi_cmp_int( N, 1 ) <= 0 )
  2350. return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
  2351. mbedtls_mpi_init( &TA ); mbedtls_mpi_init( &TU ); mbedtls_mpi_init( &U1 ); mbedtls_mpi_init( &U2 );
  2352. mbedtls_mpi_init( &G ); mbedtls_mpi_init( &TB ); mbedtls_mpi_init( &TV );
  2353. mbedtls_mpi_init( &V1 ); mbedtls_mpi_init( &V2 );
  2354. MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, A, N ) );
  2355. if( mbedtls_mpi_cmp_int( &G, 1 ) != 0 )
  2356. {
  2357. ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
  2358. goto cleanup;
  2359. }
  2360. MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &TA, A, N ) );
  2361. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TU, &TA ) );
  2362. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, N ) );
  2363. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TV, N ) );
  2364. MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &U1, 1 ) );
  2365. MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &U2, 0 ) );
  2366. MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &V1, 0 ) );
  2367. MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &V2, 1 ) );
  2368. do
  2369. {
  2370. while( ( TU.p[0] & 1 ) == 0 )
  2371. {
  2372. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TU, 1 ) );
  2373. if( ( U1.p[0] & 1 ) != 0 || ( U2.p[0] & 1 ) != 0 )
  2374. {
  2375. MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &U1, &U1, &TB ) );
  2376. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U2, &U2, &TA ) );
  2377. }
  2378. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &U1, 1 ) );
  2379. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &U2, 1 ) );
  2380. }
  2381. while( ( TV.p[0] & 1 ) == 0 )
  2382. {
  2383. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TV, 1 ) );
  2384. if( ( V1.p[0] & 1 ) != 0 || ( V2.p[0] & 1 ) != 0 )
  2385. {
  2386. MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &V1, &V1, &TB ) );
  2387. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V2, &V2, &TA ) );
  2388. }
  2389. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &V1, 1 ) );
  2390. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &V2, 1 ) );
  2391. }
  2392. if( mbedtls_mpi_cmp_mpi( &TU, &TV ) >= 0 )
  2393. {
  2394. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &TU, &TU, &TV ) );
  2395. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U1, &U1, &V1 ) );
  2396. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U2, &U2, &V2 ) );
  2397. }
  2398. else
  2399. {
  2400. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &TV, &TV, &TU ) );
  2401. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V1, &V1, &U1 ) );
  2402. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V2, &V2, &U2 ) );
  2403. }
  2404. }
  2405. while( mbedtls_mpi_cmp_int( &TU, 0 ) != 0 );
  2406. while( mbedtls_mpi_cmp_int( &V1, 0 ) < 0 )
  2407. MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &V1, &V1, N ) );
  2408. while( mbedtls_mpi_cmp_mpi( &V1, N ) >= 0 )
  2409. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V1, &V1, N ) );
  2410. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, &V1 ) );
  2411. cleanup:
  2412. mbedtls_mpi_free( &TA ); mbedtls_mpi_free( &TU ); mbedtls_mpi_free( &U1 ); mbedtls_mpi_free( &U2 );
  2413. mbedtls_mpi_free( &G ); mbedtls_mpi_free( &TB ); mbedtls_mpi_free( &TV );
  2414. mbedtls_mpi_free( &V1 ); mbedtls_mpi_free( &V2 );
  2415. return( ret );
  2416. }
  2417. #if defined(MBEDTLS_GENPRIME)
  2418. static const int small_prime[] =
  2419. {
  2420. 3, 5, 7, 11, 13, 17, 19, 23,
  2421. 29, 31, 37, 41, 43, 47, 53, 59,
  2422. 61, 67, 71, 73, 79, 83, 89, 97,
  2423. 101, 103, 107, 109, 113, 127, 131, 137,
  2424. 139, 149, 151, 157, 163, 167, 173, 179,
  2425. 181, 191, 193, 197, 199, 211, 223, 227,
  2426. 229, 233, 239, 241, 251, 257, 263, 269,
  2427. 271, 277, 281, 283, 293, 307, 311, 313,
  2428. 317, 331, 337, 347, 349, 353, 359, 367,
  2429. 373, 379, 383, 389, 397, 401, 409, 419,
  2430. 421, 431, 433, 439, 443, 449, 457, 461,
  2431. 463, 467, 479, 487, 491, 499, 503, 509,
  2432. 521, 523, 541, 547, 557, 563, 569, 571,
  2433. 577, 587, 593, 599, 601, 607, 613, 617,
  2434. 619, 631, 641, 643, 647, 653, 659, 661,
  2435. 673, 677, 683, 691, 701, 709, 719, 727,
  2436. 733, 739, 743, 751, 757, 761, 769, 773,
  2437. 787, 797, 809, 811, 821, 823, 827, 829,
  2438. 839, 853, 857, 859, 863, 877, 881, 883,
  2439. 887, 907, 911, 919, 929, 937, 941, 947,
  2440. 953, 967, 971, 977, 983, 991, 997, -103
  2441. };
  2442. /*
  2443. * Small divisors test (X must be positive)
  2444. *
  2445. * Return values:
  2446. * 0: no small factor (possible prime, more tests needed)
  2447. * 1: certain prime
  2448. * MBEDTLS_ERR_MPI_NOT_ACCEPTABLE: certain non-prime
  2449. * other negative: error
  2450. */
  2451. static int mpi_check_small_factors( const mbedtls_mpi *X )
  2452. {
  2453. int ret = 0;
  2454. size_t i;
  2455. mbedtls_mpi_uint r;
  2456. if( ( X->p[0] & 1 ) == 0 )
  2457. return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
  2458. for( i = 0; small_prime[i] > 0; i++ )
  2459. {
  2460. if( mbedtls_mpi_cmp_int( X, small_prime[i] ) <= 0 )
  2461. return( 1 );
  2462. MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, small_prime[i] ) );
  2463. if( r == 0 )
  2464. return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
  2465. }
  2466. cleanup:
  2467. return( ret );
  2468. }
  2469. /*
  2470. * Miller-Rabin pseudo-primality test (HAC 4.24)
  2471. */
  2472. static int mpi_miller_rabin( const mbedtls_mpi *X, size_t rounds,
  2473. int (*f_rng)(void *, unsigned char *, size_t),
  2474. void *p_rng )
  2475. {
  2476. int ret, count;
  2477. size_t i, j, k, s;
  2478. mbedtls_mpi W, R, T, A, RR;
  2479. MPI_VALIDATE_RET( X != NULL );
  2480. MPI_VALIDATE_RET( f_rng != NULL );
  2481. mbedtls_mpi_init( &W ); mbedtls_mpi_init( &R );
  2482. mbedtls_mpi_init( &T ); mbedtls_mpi_init( &A );
  2483. mbedtls_mpi_init( &RR );
  2484. /*
  2485. * W = |X| - 1
  2486. * R = W >> lsb( W )
  2487. */
  2488. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &W, X, 1 ) );
  2489. s = mbedtls_mpi_lsb( &W );
  2490. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R, &W ) );
  2491. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &R, s ) );
  2492. for( i = 0; i < rounds; i++ )
  2493. {
  2494. /*
  2495. * pick a random A, 1 < A < |X| - 1
  2496. */
  2497. count = 0;
  2498. do {
  2499. MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &A, X->n * ciL, f_rng, p_rng ) );
  2500. j = mbedtls_mpi_bitlen( &A );
  2501. k = mbedtls_mpi_bitlen( &W );
  2502. if (j > k) {
  2503. A.p[A.n - 1] &= ( (mbedtls_mpi_uint) 1 << ( k - ( A.n - 1 ) * biL - 1 ) ) - 1;
  2504. }
  2505. if (count++ > 30) {
  2506. ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
  2507. goto cleanup;
  2508. }
  2509. } while ( mbedtls_mpi_cmp_mpi( &A, &W ) >= 0 ||
  2510. mbedtls_mpi_cmp_int( &A, 1 ) <= 0 );
  2511. /*
  2512. * A = A^R mod |X|
  2513. */
  2514. MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &A, &A, &R, X, &RR ) );
  2515. if( mbedtls_mpi_cmp_mpi( &A, &W ) == 0 ||
  2516. mbedtls_mpi_cmp_int( &A, 1 ) == 0 )
  2517. continue;
  2518. j = 1;
  2519. while( j < s && mbedtls_mpi_cmp_mpi( &A, &W ) != 0 )
  2520. {
  2521. /*
  2522. * A = A * A mod |X|
  2523. */
  2524. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &A, &A ) );
  2525. MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &A, &T, X ) );
  2526. if( mbedtls_mpi_cmp_int( &A, 1 ) == 0 )
  2527. break;
  2528. j++;
  2529. }
  2530. /*
  2531. * not prime if A != |X| - 1 or A == 1
  2532. */
  2533. if( mbedtls_mpi_cmp_mpi( &A, &W ) != 0 ||
  2534. mbedtls_mpi_cmp_int( &A, 1 ) == 0 )
  2535. {
  2536. ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
  2537. break;
  2538. }
  2539. }
  2540. cleanup:
  2541. mbedtls_mpi_free( &W ); mbedtls_mpi_free( &R );
  2542. mbedtls_mpi_free( &T ); mbedtls_mpi_free( &A );
  2543. mbedtls_mpi_free( &RR );
  2544. return( ret );
  2545. }
  2546. /*
  2547. * Pseudo-primality test: small factors, then Miller-Rabin
  2548. */
  2549. int mbedtls_mpi_is_prime_ext( const mbedtls_mpi *X, int rounds,
  2550. int (*f_rng)(void *, unsigned char *, size_t),
  2551. void *p_rng )
  2552. {
  2553. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2554. mbedtls_mpi XX;
  2555. MPI_VALIDATE_RET( X != NULL );
  2556. MPI_VALIDATE_RET( f_rng != NULL );
  2557. XX.s = 1;
  2558. XX.n = X->n;
  2559. XX.p = X->p;
  2560. if( mbedtls_mpi_cmp_int( &XX, 0 ) == 0 ||
  2561. mbedtls_mpi_cmp_int( &XX, 1 ) == 0 )
  2562. return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
  2563. if( mbedtls_mpi_cmp_int( &XX, 2 ) == 0 )
  2564. return( 0 );
  2565. if( ( ret = mpi_check_small_factors( &XX ) ) != 0 )
  2566. {
  2567. if( ret == 1 )
  2568. return( 0 );
  2569. return( ret );
  2570. }
  2571. return( mpi_miller_rabin( &XX, rounds, f_rng, p_rng ) );
  2572. }
  2573. #if !defined(MBEDTLS_DEPRECATED_REMOVED)
  2574. /*
  2575. * Pseudo-primality test, error probability 2^-80
  2576. */
  2577. /* NXP added for HW accelerators support */
  2578. #if defined(MBEDTLS_MPI_IS_PRIME_ALT)
  2579. int mbedtls_mpi_is_prime_orig( const mbedtls_mpi *X,
  2580. int (*f_rng)(void *, unsigned char *, size_t),
  2581. void *p_rng )
  2582. #else
  2583. int mbedtls_mpi_is_prime( const mbedtls_mpi *X,
  2584. int (*f_rng)(void *, unsigned char *, size_t),
  2585. void *p_rng )
  2586. #endif /* MBEDTLS_MPI_IS_PRIME_ALT */
  2587. {
  2588. MPI_VALIDATE_RET( X != NULL );
  2589. MPI_VALIDATE_RET( f_rng != NULL );
  2590. /*
  2591. * In the past our key generation aimed for an error rate of at most
  2592. * 2^-80. Since this function is deprecated, aim for the same certainty
  2593. * here as well.
  2594. */
  2595. return( mbedtls_mpi_is_prime_ext( X, 40, f_rng, p_rng ) );
  2596. }
  2597. #endif
  2598. /*
  2599. * Prime number generation
  2600. *
  2601. * To generate an RSA key in a way recommended by FIPS 186-4, both primes must
  2602. * be either 1024 bits or 1536 bits long, and flags must contain
  2603. * MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR.
  2604. */
  2605. int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int flags,
  2606. int (*f_rng)(void *, unsigned char *, size_t),
  2607. void *p_rng )
  2608. {
  2609. #ifdef MBEDTLS_HAVE_INT64
  2610. // ceil(2^63.5)
  2611. #define CEIL_MAXUINT_DIV_SQRT2 0xb504f333f9de6485ULL
  2612. #else
  2613. // ceil(2^31.5)
  2614. #define CEIL_MAXUINT_DIV_SQRT2 0xb504f334U
  2615. #endif
  2616. int ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
  2617. size_t k, n;
  2618. int rounds;
  2619. mbedtls_mpi_uint r;
  2620. mbedtls_mpi Y;
  2621. MPI_VALIDATE_RET( X != NULL );
  2622. MPI_VALIDATE_RET( f_rng != NULL );
  2623. if( nbits < 3 || nbits > MBEDTLS_MPI_MAX_BITS )
  2624. return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
  2625. mbedtls_mpi_init( &Y );
  2626. n = BITS_TO_LIMBS( nbits );
  2627. if( ( flags & MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR ) == 0 )
  2628. {
  2629. /*
  2630. * 2^-80 error probability, number of rounds chosen per HAC, table 4.4
  2631. */
  2632. rounds = ( ( nbits >= 1300 ) ? 2 : ( nbits >= 850 ) ? 3 :
  2633. ( nbits >= 650 ) ? 4 : ( nbits >= 350 ) ? 8 :
  2634. ( nbits >= 250 ) ? 12 : ( nbits >= 150 ) ? 18 : 27 );
  2635. }
  2636. else
  2637. {
  2638. /*
  2639. * 2^-100 error probability, number of rounds computed based on HAC,
  2640. * fact 4.48
  2641. */
  2642. rounds = ( ( nbits >= 1450 ) ? 4 : ( nbits >= 1150 ) ? 5 :
  2643. ( nbits >= 1000 ) ? 6 : ( nbits >= 850 ) ? 7 :
  2644. ( nbits >= 750 ) ? 8 : ( nbits >= 500 ) ? 13 :
  2645. ( nbits >= 250 ) ? 28 : ( nbits >= 150 ) ? 40 : 51 );
  2646. }
  2647. while( 1 )
  2648. {
  2649. MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( X, n * ciL, f_rng, p_rng ) );
  2650. /* make sure generated number is at least (nbits-1)+0.5 bits (FIPS 186-4 §B.3.3 steps 4.4, 5.5) */
  2651. if( X->p[n-1] < CEIL_MAXUINT_DIV_SQRT2 ) continue;
  2652. k = n * biL;
  2653. if( k > nbits ) MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( X, k - nbits ) );
  2654. X->p[0] |= 1;
  2655. if( ( flags & MBEDTLS_MPI_GEN_PRIME_FLAG_DH ) == 0 )
  2656. {
  2657. ret = mbedtls_mpi_is_prime_ext( X, rounds, f_rng, p_rng );
  2658. if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
  2659. goto cleanup;
  2660. }
  2661. else
  2662. {
  2663. /*
  2664. * An necessary condition for Y and X = 2Y + 1 to be prime
  2665. * is X = 2 mod 3 (which is equivalent to Y = 2 mod 3).
  2666. * Make sure it is satisfied, while keeping X = 3 mod 4
  2667. */
  2668. X->p[0] |= 2;
  2669. MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, 3 ) );
  2670. if( r == 0 )
  2671. MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 8 ) );
  2672. else if( r == 1 )
  2673. MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 4 ) );
  2674. /* Set Y = (X-1) / 2, which is X / 2 because X is odd */
  2675. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Y, X ) );
  2676. MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &Y, 1 ) );
  2677. while( 1 )
  2678. {
  2679. /*
  2680. * First, check small factors for X and Y
  2681. * before doing Miller-Rabin on any of them
  2682. */
  2683. if( ( ret = mpi_check_small_factors( X ) ) == 0 &&
  2684. ( ret = mpi_check_small_factors( &Y ) ) == 0 &&
  2685. ( ret = mpi_miller_rabin( X, rounds, f_rng, p_rng ) )
  2686. == 0 &&
  2687. ( ret = mpi_miller_rabin( &Y, rounds, f_rng, p_rng ) )
  2688. == 0 )
  2689. goto cleanup;
  2690. if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
  2691. goto cleanup;
  2692. /*
  2693. * Next candidates. We want to preserve Y = (X-1) / 2 and
  2694. * Y = 1 mod 2 and Y = 2 mod 3 (eq X = 3 mod 4 and X = 2 mod 3)
  2695. * so up Y by 6 and X by 12.
  2696. */
  2697. MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 12 ) );
  2698. MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &Y, &Y, 6 ) );
  2699. }
  2700. }
  2701. }
  2702. cleanup:
  2703. mbedtls_mpi_free( &Y );
  2704. return( ret );
  2705. }
  2706. #endif /* MBEDTLS_GENPRIME */
  2707. #if defined(MBEDTLS_SELF_TEST)
  2708. #define GCD_PAIR_COUNT 3
  2709. static const int gcd_pairs[GCD_PAIR_COUNT][3] =
  2710. {
  2711. { 693, 609, 21 },
  2712. { 1764, 868, 28 },
  2713. { 768454923, 542167814, 1 }
  2714. };
  2715. /*
  2716. * Checkup routine
  2717. */
  2718. int mbedtls_mpi_self_test( int verbose )
  2719. {
  2720. int ret, i;
  2721. mbedtls_mpi A, E, N, X, Y, U, V;
  2722. mbedtls_mpi_init( &A ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &N ); mbedtls_mpi_init( &X );
  2723. mbedtls_mpi_init( &Y ); mbedtls_mpi_init( &U ); mbedtls_mpi_init( &V );
  2724. MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &A, 16,
  2725. "EFE021C2645FD1DC586E69184AF4A31E" \
  2726. "D5F53E93B5F123FA41680867BA110131" \
  2727. "944FE7952E2517337780CB0DB80E61AA" \
  2728. "E7C8DDC6C5C6AADEB34EB38A2F40D5E6" ) );
  2729. MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &E, 16,
  2730. "B2E7EFD37075B9F03FF989C7C5051C20" \
  2731. "34D2A323810251127E7BF8625A4F49A5" \
  2732. "F3E27F4DA8BD59C47D6DAABA4C8127BD" \
  2733. "5B5C25763222FEFCCFC38B832366C29E" ) );
  2734. MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &N, 16,
  2735. "0066A198186C18C10B2F5ED9B522752A" \
  2736. "9830B69916E535C8F047518A889A43A5" \
  2737. "94B6BED27A168D31D4A52F88925AA8F5" ) );
  2738. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &X, &A, &N ) );
  2739. MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
  2740. "602AB7ECA597A3D6B56FF9829A5E8B85" \
  2741. "9E857EA95A03512E2BAE7391688D264A" \
  2742. "A5663B0341DB9CCFD2C4C5F421FEC814" \
  2743. "8001B72E848A38CAE1C65F78E56ABDEF" \
  2744. "E12D3C039B8A02D6BE593F0BBBDA56F1" \
  2745. "ECF677152EF804370C1A305CAF3B5BF1" \
  2746. "30879B56C61DE584A0F53A2447A51E" ) );
  2747. if( verbose != 0 )
  2748. mbedtls_printf( " MPI test #1 (mul_mpi): " );
  2749. if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 )
  2750. {
  2751. if( verbose != 0 )
  2752. mbedtls_printf( "failed\n" );
  2753. ret = 1;
  2754. goto cleanup;
  2755. }
  2756. if( verbose != 0 )
  2757. mbedtls_printf( "passed\n" );
  2758. MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &X, &Y, &A, &N ) );
  2759. MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
  2760. "256567336059E52CAE22925474705F39A94" ) );
  2761. MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &V, 16,
  2762. "6613F26162223DF488E9CD48CC132C7A" \
  2763. "0AC93C701B001B092E4E5B9F73BCD27B" \
  2764. "9EE50D0657C77F374E903CDFA4C642" ) );
  2765. if( verbose != 0 )
  2766. mbedtls_printf( " MPI test #2 (div_mpi): " );
  2767. if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 ||
  2768. mbedtls_mpi_cmp_mpi( &Y, &V ) != 0 )
  2769. {
  2770. if( verbose != 0 )
  2771. mbedtls_printf( "failed\n" );
  2772. ret = 1;
  2773. goto cleanup;
  2774. }
  2775. if( verbose != 0 )
  2776. mbedtls_printf( "passed\n" );
  2777. MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &X, &A, &E, &N, NULL ) );
  2778. MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
  2779. "36E139AEA55215609D2816998ED020BB" \
  2780. "BD96C37890F65171D948E9BC7CBAA4D9" \
  2781. "325D24D6A3C12710F10A09FA08AB87" ) );
  2782. if( verbose != 0 )
  2783. mbedtls_printf( " MPI test #3 (exp_mod): " );
  2784. if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 )
  2785. {
  2786. if( verbose != 0 )
  2787. mbedtls_printf( "failed\n" );
  2788. ret = 1;
  2789. goto cleanup;
  2790. }
  2791. if( verbose != 0 )
  2792. mbedtls_printf( "passed\n" );
  2793. MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &X, &A, &N ) );
  2794. MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
  2795. "003A0AAEDD7E784FC07D8F9EC6E3BFD5" \
  2796. "C3DBA76456363A10869622EAC2DD84EC" \
  2797. "C5B8A74DAC4D09E03B5E0BE779F2DF61" ) );
  2798. if( verbose != 0 )
  2799. mbedtls_printf( " MPI test #4 (inv_mod): " );
  2800. if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 )
  2801. {
  2802. if( verbose != 0 )
  2803. mbedtls_printf( "failed\n" );
  2804. ret = 1;
  2805. goto cleanup;
  2806. }
  2807. if( verbose != 0 )
  2808. mbedtls_printf( "passed\n" );
  2809. if( verbose != 0 )
  2810. mbedtls_printf( " MPI test #5 (simple gcd): " );
  2811. for( i = 0; i < GCD_PAIR_COUNT; i++ )
  2812. {
  2813. MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &X, gcd_pairs[i][0] ) );
  2814. MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &Y, gcd_pairs[i][1] ) );
  2815. MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &A, &X, &Y ) );
  2816. if( mbedtls_mpi_cmp_int( &A, gcd_pairs[i][2] ) != 0 )
  2817. {
  2818. if( verbose != 0 )
  2819. mbedtls_printf( "failed at %d\n", i );
  2820. ret = 1;
  2821. goto cleanup;
  2822. }
  2823. }
  2824. if( verbose != 0 )
  2825. mbedtls_printf( "passed\n" );
  2826. cleanup:
  2827. if( ret != 0 && verbose != 0 )
  2828. mbedtls_printf( "Unexpected error, return code = %08X\n", (unsigned int) ret );
  2829. mbedtls_mpi_free( &A ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &N ); mbedtls_mpi_free( &X );
  2830. mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &U ); mbedtls_mpi_free( &V );
  2831. if( verbose != 0 )
  2832. mbedtls_printf( "\n" );
  2833. return( ret );
  2834. }
  2835. #endif /* MBEDTLS_SELF_TEST */
  2836. #endif /* MBEDTLS_BIGNUM_C */