bignum.c 82 KB

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