bignum.c 85 KB

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