bignum.c 72 KB

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