bignum.c 67 KB

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