bignum.c 86 KB

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