bignum.c 82 KB

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