bignum.c 70 KB

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