bignum.c 83 KB

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