1
0

mpint.c 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027
  1. /*
  2. * Multiprecision integer arithmetic, implementing mpint.h.
  3. */
  4. #include <assert.h>
  5. #include <limits.h>
  6. #include <stdio.h>
  7. #include "defs.h"
  8. #include "misc.h"
  9. #include "puttymem.h"
  10. #include "mpint.h"
  11. #include "mpint_i.h"
  12. #pragma warn -ngu // WINSCP
  13. #define SIZE_T_BITS (CHAR_BIT * sizeof(size_t))
  14. /*
  15. * Inline helpers to take min and max of size_t values, used
  16. * throughout this code.
  17. */
  18. static inline size_t size_t_min(size_t a, size_t b)
  19. {
  20. return a < b ? a : b;
  21. }
  22. static inline size_t size_t_max(size_t a, size_t b)
  23. {
  24. return a > b ? a : b;
  25. }
  26. /*
  27. * Helper to fetch a word of data from x with array overflow checking.
  28. * If x is too short to have that word, 0 is returned.
  29. */
  30. static inline BignumInt mp_word(mp_int *x, size_t i)
  31. {
  32. return i < x->nw ? x->w[i] : 0;
  33. }
  34. /*
  35. * Shift an ordinary C integer by BIGNUM_INT_BITS, in a way that
  36. * avoids writing a shift operator whose RHS is greater or equal to
  37. * the size of the type, because that's undefined behaviour in C.
  38. *
  39. * In fact we must avoid even writing it in a definitely-untaken
  40. * branch of an if, because compilers will sometimes warn about
  41. * that. So you can't just write 'shift too big ? 0 : n >> shift',
  42. * because even if 'shift too big' is a constant-expression
  43. * evaluating to false, you can still get complaints about the
  44. * else clause of the ?:.
  45. *
  46. * So we have to re-check _inside_ that clause, so that the shift
  47. * count is reset to something nonsensical but safe in the case
  48. * where the clause wasn't going to be taken anyway.
  49. */
  50. static uintmax_t shift_right_by_one_word(uintmax_t n)
  51. {
  52. bool shift_too_big = BIGNUM_INT_BYTES >= sizeof(n);
  53. return shift_too_big ? 0 :
  54. n >> (shift_too_big ? 0 : BIGNUM_INT_BITS);
  55. }
  56. static uintmax_t shift_left_by_one_word(uintmax_t n)
  57. {
  58. bool shift_too_big = BIGNUM_INT_BYTES >= sizeof(n);
  59. return shift_too_big ? 0 :
  60. n << (shift_too_big ? 0 : BIGNUM_INT_BITS);
  61. }
  62. mp_int *mp_make_sized(size_t nw)
  63. {
  64. mp_int *x = snew_plus(mp_int, nw * sizeof(BignumInt));
  65. assert(nw); /* we outlaw the zero-word mp_int */
  66. x->nw = nw;
  67. x->w = snew_plus_get_aux(x);
  68. mp_clear(x);
  69. return x;
  70. }
  71. mp_int *mp_new(size_t maxbits)
  72. {
  73. size_t words = (maxbits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS;
  74. return mp_make_sized(words);
  75. }
  76. mp_int *mp_resize(mp_int *mp, size_t newmaxbits)
  77. {
  78. mp_int *copy = mp_new(newmaxbits);
  79. mp_copy_into(copy, mp);
  80. mp_free(mp);
  81. return copy;
  82. }
  83. mp_int *mp_from_integer(uintmax_t n)
  84. {
  85. mp_int *x = mp_make_sized(
  86. (sizeof(n) + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES);
  87. size_t i; // WINSCP
  88. for (i = 0; i < x->nw; i++)
  89. x->w[i] = n >> (i * BIGNUM_INT_BITS);
  90. return x;
  91. }
  92. size_t mp_max_bytes(mp_int *x)
  93. {
  94. return x->nw * BIGNUM_INT_BYTES;
  95. }
  96. size_t mp_max_bits(mp_int *x)
  97. {
  98. return x->nw * BIGNUM_INT_BITS;
  99. }
  100. void mp_free(mp_int *x)
  101. {
  102. mp_clear(x);
  103. smemclr(x, sizeof(*x));
  104. sfree(x);
  105. }
  106. void mp_dump(FILE *fp, const char *prefix, mp_int *x, const char *suffix)
  107. {
  108. size_t i; // WINSCP
  109. fprintf(fp, "%s0x", prefix);
  110. for (i = mp_max_bytes(x); i-- > 0 ;)
  111. fprintf(fp, "%02X", mp_get_byte(x, i));
  112. fputs(suffix, fp);
  113. }
  114. void mp_copy_into(mp_int *dest, mp_int *src)
  115. {
  116. size_t copy_nw = size_t_min(dest->nw, src->nw);
  117. memmove(dest->w, src->w, copy_nw * sizeof(BignumInt));
  118. smemclr(dest->w + copy_nw, (dest->nw - copy_nw) * sizeof(BignumInt));
  119. }
  120. void mp_copy_integer_into(mp_int *r, uintmax_t n)
  121. {
  122. size_t i; // WINSCP
  123. for (i = 0; i < r->nw; i++) {
  124. r->w[i] = n;
  125. n = shift_right_by_one_word(n);
  126. }
  127. }
  128. /*
  129. * Conditional selection is done by negating 'which', to give a mask
  130. * word which is all 1s if which==1 and all 0s if which==0. Then you
  131. * can select between two inputs a,b without data-dependent control
  132. * flow by XORing them to get their difference; ANDing with the mask
  133. * word to replace that difference with 0 if which==0; and XORing that
  134. * into a, which will either turn it into b or leave it alone.
  135. *
  136. * This trick will be used throughout this code and taken as read the
  137. * rest of the time (or else I'd be here all week typing comments),
  138. * but I felt I ought to explain it in words _once_.
  139. */
  140. void mp_select_into(mp_int *dest, mp_int *src0, mp_int *src1,
  141. unsigned which)
  142. {
  143. BignumInt mask = -(BignumInt)(1 & which);
  144. size_t i; // WINSCP
  145. for (i = 0; i < dest->nw; i++) {
  146. BignumInt srcword0 = mp_word(src0, i), srcword1 = mp_word(src1, i);
  147. dest->w[i] = srcword0 ^ ((srcword1 ^ srcword0) & mask);
  148. }
  149. }
  150. void mp_cond_swap(mp_int *x0, mp_int *x1, unsigned swap)
  151. {
  152. pinitassert(x0->nw == x1->nw);
  153. volatile BignumInt mask = -(BignumInt)(1 & swap);
  154. size_t i; // WINSCP
  155. for (i = 0; i < x0->nw; i++) {
  156. BignumInt diff = (x0->w[i] ^ x1->w[i]) & mask;
  157. x0->w[i] ^= diff;
  158. x1->w[i] ^= diff;
  159. }
  160. }
  161. void mp_clear(mp_int *x)
  162. {
  163. smemclr(x->w, x->nw * sizeof(BignumInt));
  164. }
  165. void mp_cond_clear(mp_int *x, unsigned clear)
  166. {
  167. BignumInt mask = ~-(BignumInt)(1 & clear);
  168. size_t i; // WINSCP
  169. for (i = 0; i < x->nw; i++)
  170. x->w[i] &= mask;
  171. }
  172. /*
  173. * Common code between mp_from_bytes_{le,be} which reads bytes in an
  174. * arbitrary arithmetic progression.
  175. */
  176. static mp_int *mp_from_bytes_int(ptrlen bytes, size_t m, size_t c)
  177. {
  178. size_t nw = (bytes.len + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES;
  179. nw = size_t_max(nw, 1);
  180. { // WINSCP
  181. mp_int *n = mp_make_sized(nw);
  182. size_t i; // WINSCP
  183. for (i = 0; i < bytes.len; i++)
  184. n->w[i / BIGNUM_INT_BYTES] |=
  185. (BignumInt)(((const unsigned char *)bytes.ptr)[m*i+c]) <<
  186. (8 * (i % BIGNUM_INT_BYTES));
  187. return n;
  188. } // WINSCP
  189. }
  190. mp_int *mp_from_bytes_le(ptrlen bytes)
  191. {
  192. return mp_from_bytes_int(bytes, 1, 0);
  193. }
  194. mp_int *mp_from_bytes_be(ptrlen bytes)
  195. {
  196. return mp_from_bytes_int(bytes, -1, bytes.len - 1);
  197. }
  198. static mp_int *mp_from_words(size_t nw, const BignumInt *w)
  199. {
  200. mp_int *x = mp_make_sized(nw);
  201. memcpy(x->w, w, x->nw * sizeof(BignumInt));
  202. return x;
  203. }
  204. /*
  205. * Decimal-to-binary conversion: just go through the input string
  206. * adding on the decimal value of each digit, and then multiplying the
  207. * number so far by 10.
  208. */
  209. mp_int *mp_from_decimal_pl(ptrlen decimal)
  210. {
  211. /* 196/59 is an upper bound (and also a continued-fraction
  212. * convergent) for log2(10), so this conservatively estimates the
  213. * number of bits that will be needed to store any number that can
  214. * be written in this many decimal digits. */
  215. pinitassert(decimal.len < (~(size_t)0) / 196);
  216. size_t bits = 196 * decimal.len / 59;
  217. /* Now round that up to words. */
  218. size_t words = bits / BIGNUM_INT_BITS + 1;
  219. mp_int *x = mp_make_sized(words);
  220. size_t i; // WINSCP
  221. for (i = 0; i < decimal.len; i++) {
  222. mp_add_integer_into(x, x, ((const char *)decimal.ptr)[i] - '0');
  223. if (i+1 == decimal.len)
  224. break;
  225. mp_mul_integer_into(x, x, 10);
  226. }
  227. return x;
  228. }
  229. mp_int *mp_from_decimal(const char *decimal)
  230. {
  231. return mp_from_decimal_pl(ptrlen_from_asciz(decimal));
  232. }
  233. /*
  234. * Hex-to-binary conversion: _algorithmically_ simpler than decimal
  235. * (none of those multiplications by 10), but there's some fiddly
  236. * bit-twiddling needed to process each hex digit without diverging
  237. * control flow depending on whether it's a letter or a number.
  238. */
  239. mp_int *mp_from_hex_pl(ptrlen hex)
  240. {
  241. pinitassert(hex.len <= (~(size_t)0) / 4);
  242. size_t bits = hex.len * 4;
  243. size_t words = (bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS;
  244. words = size_t_max(words, 1);
  245. { // WINSCP
  246. mp_int *x = mp_make_sized(words);
  247. size_t nibble; // WINSCP
  248. for (nibble = 0; nibble < hex.len; nibble++) {
  249. BignumInt digit = ((const char *)hex.ptr)[hex.len-1 - nibble];
  250. BignumInt lmask = ~-((BignumInt)((digit-'a')|('f'-digit))
  251. >> (BIGNUM_INT_BITS-1));
  252. BignumInt umask = ~-((BignumInt)((digit-'A')|('F'-digit))
  253. >> (BIGNUM_INT_BITS-1));
  254. BignumInt digitval = digit - '0';
  255. digitval ^= (digitval ^ (digit - 'a' + 10)) & lmask;
  256. digitval ^= (digitval ^ (digit - 'A' + 10)) & umask;
  257. digitval &= 0xF; /* at least be _slightly_ nice about weird input */
  258. { // WINSCP
  259. size_t word_idx = nibble / (BIGNUM_INT_BYTES*2);
  260. size_t nibble_within_word = nibble % (BIGNUM_INT_BYTES*2);
  261. x->w[word_idx] |= digitval << (nibble_within_word * 4);
  262. } // WINSCP
  263. }
  264. return x;
  265. } // WINSCP
  266. }
  267. mp_int *mp_from_hex(const char *hex)
  268. {
  269. return mp_from_hex_pl(ptrlen_from_asciz(hex));
  270. }
  271. mp_int *mp_copy(mp_int *x)
  272. {
  273. return mp_from_words(x->nw, x->w);
  274. }
  275. uint8_t mp_get_byte(mp_int *x, size_t byte)
  276. {
  277. return 0xFF & (mp_word(x, byte / BIGNUM_INT_BYTES) >>
  278. (8 * (byte % BIGNUM_INT_BYTES)));
  279. }
  280. unsigned mp_get_bit(mp_int *x, size_t bit)
  281. {
  282. return 1 & (mp_word(x, bit / BIGNUM_INT_BITS) >>
  283. (bit % BIGNUM_INT_BITS));
  284. }
  285. uintmax_t mp_get_integer(mp_int *x)
  286. {
  287. uintmax_t toret = 0;
  288. size_t i; // WINSCP
  289. for (i = x->nw; i-- > 0 ;)
  290. toret = shift_left_by_one_word(toret) | x->w[i];
  291. return toret;
  292. }
  293. void mp_set_bit(mp_int *x, size_t bit, unsigned val)
  294. {
  295. size_t word = bit / BIGNUM_INT_BITS;
  296. pinitassert(word < x->nw);
  297. unsigned shift = (bit % BIGNUM_INT_BITS);
  298. x->w[word] &= ~((BignumInt)1 << shift);
  299. x->w[word] |= (BignumInt)(val & 1) << shift;
  300. }
  301. /*
  302. * Helper function used here and there to normalise any nonzero input
  303. * value to 1.
  304. */
  305. static inline unsigned normalise_to_1(BignumInt n)
  306. {
  307. n = (n >> 1) | (n & 1); /* ensure top bit is clear */
  308. n = (BignumInt)(-n) >> (BIGNUM_INT_BITS - 1); /* normalise to 0 or 1 */
  309. return n;
  310. }
  311. static inline unsigned normalise_to_1_u64(uint64_t n)
  312. {
  313. n = (n >> 1) | (n & 1); /* ensure top bit is clear */
  314. n = (-n) >> 63; /* normalise to 0 or 1 */
  315. return n;
  316. }
  317. /*
  318. * Find the highest nonzero word in a number. Returns the index of the
  319. * word in x->w, and also a pair of output uint64_t in which that word
  320. * appears in the high one shifted left by 'shift_wanted' bits, the
  321. * words immediately below it occupy the space to the right, and the
  322. * words below _that_ fill up the low one.
  323. *
  324. * If there is no nonzero word at all, the passed-by-reference output
  325. * variables retain their original values.
  326. */
  327. static inline void mp_find_highest_nonzero_word_pair(
  328. mp_int *x, size_t shift_wanted, size_t *index,
  329. uint64_t *hi, uint64_t *lo)
  330. {
  331. uint64_t curr_hi = 0, curr_lo = 0;
  332. size_t curr_index; // WINSCP
  333. for (curr_index = 0; curr_index < x->nw; curr_index++) {
  334. BignumInt curr_word = x->w[curr_index];
  335. unsigned indicator = normalise_to_1(curr_word);
  336. curr_lo = (BIGNUM_INT_BITS < 64 ? (curr_lo >> BIGNUM_INT_BITS) : 0) |
  337. (curr_hi << (64 - BIGNUM_INT_BITS));
  338. curr_hi = (BIGNUM_INT_BITS < 64 ? (curr_hi >> BIGNUM_INT_BITS) : 0) |
  339. ((uint64_t)curr_word << shift_wanted);
  340. if (hi) *hi ^= (curr_hi ^ *hi ) & -(uint64_t)indicator;
  341. if (lo) *lo ^= (curr_lo ^ *lo ) & -(uint64_t)indicator;
  342. if (index) *index ^= (curr_index ^ *index) & -(size_t) indicator;
  343. }
  344. }
  345. size_t mp_get_nbits(mp_int *x)
  346. {
  347. /* Sentinel values in case there are no bits set at all: we
  348. * imagine that there's a word at position -1 (i.e. the topmost
  349. * fraction word) which is all 1s, because that way, we handle a
  350. * zero input by considering its highest set bit to be the top one
  351. * of that word, i.e. just below the units digit, i.e. at bit
  352. * index -1, i.e. so we'll return 0 on output. */
  353. size_t hiword_index = -(size_t)1;
  354. uint64_t hiword64 = ~(BignumInt)0;
  355. /*
  356. * Find the highest nonzero word and its index.
  357. */
  358. mp_find_highest_nonzero_word_pair(x, 0, &hiword_index, &hiword64, NULL);
  359. { // WINSCP
  360. BignumInt hiword = hiword64; /* in case BignumInt is a narrower type */
  361. /*
  362. * Find the index of the highest set bit within hiword.
  363. */
  364. BignumInt hibit_index = 0;
  365. size_t i; // WINSCP
  366. for (i = (1 << (BIGNUM_INT_BITS_BITS-1)); i != 0; i >>= 1) {
  367. BignumInt shifted_word = hiword >> i;
  368. BignumInt indicator =
  369. (BignumInt)(-shifted_word) >> (BIGNUM_INT_BITS-1);
  370. hiword ^= (shifted_word ^ hiword ) & -indicator;
  371. hibit_index += i & -(size_t)indicator;
  372. }
  373. /*
  374. * Put together the result.
  375. */
  376. return (hiword_index << BIGNUM_INT_BITS_BITS) + hibit_index + 1;
  377. } // WINSCP
  378. }
  379. /*
  380. * Shared code between the hex and decimal output functions to get rid
  381. * of leading zeroes on the output string. The idea is that we wrote
  382. * out a fixed number of digits and a trailing \0 byte into 'buf', and
  383. * now we want to shift it all left so that the first nonzero digit
  384. * moves to buf[0] (or, if there are no nonzero digits at all, we move
  385. * up by 'maxtrim', so that we return 0 as "0" instead of "").
  386. */
  387. static void trim_leading_zeroes(char *buf, size_t bufsize, size_t maxtrim)
  388. {
  389. size_t trim = maxtrim;
  390. /*
  391. * Look for the first character not equal to '0', to find the
  392. * shift count.
  393. */
  394. if (trim > 0) {
  395. size_t pos; // WINSCP
  396. for (pos = trim; pos-- > 0 ;) {
  397. uint8_t diff = buf[pos] ^ '0';
  398. size_t mask = -((((size_t)diff) - 1) >> (SIZE_T_BITS - 1));
  399. trim ^= (trim ^ pos) & ~mask;
  400. }
  401. }
  402. /*
  403. * Now do the shift, in log n passes each of which does a
  404. * conditional shift by 2^i bytes if bit i is set in the shift
  405. * count.
  406. */
  407. { // WINSCP
  408. uint8_t *ubuf = (uint8_t *)buf;
  409. size_t logd; // WINSCP
  410. for (logd = 0; bufsize >> logd; logd++) {
  411. uint8_t mask = -(uint8_t)((trim >> logd) & 1);
  412. size_t d = (size_t)1 << logd;
  413. size_t i; // WINSCP
  414. for (i = 0; i+d < bufsize; i++) {
  415. uint8_t diff = mask & (ubuf[i] ^ ubuf[i+d]);
  416. ubuf[i] ^= diff;
  417. ubuf[i+d] ^= diff;
  418. }
  419. }
  420. } // WINSCP
  421. }
  422. /*
  423. * Binary to decimal conversion. Our strategy here is to extract each
  424. * decimal digit by finding the input number's residue mod 10, then
  425. * subtract that off to give an exact multiple of 10, which then means
  426. * you can safely divide by 10 by means of shifting right one bit and
  427. * then multiplying by the inverse of 5 mod 2^n.
  428. */
  429. char *mp_get_decimal(mp_int *x_orig)
  430. {
  431. mp_int *x = mp_copy(x_orig), *y = mp_make_sized(x->nw);
  432. /*
  433. * The inverse of 5 mod 2^lots is 0xccccccccccccccccccccd, for an
  434. * appropriate number of 'c's. Manually construct an integer the
  435. * right size.
  436. */
  437. mp_int *inv5 = mp_make_sized(x->nw);
  438. pinitassert(BIGNUM_INT_BITS % 8 == 0);
  439. size_t i; // WINSCP
  440. for (i = 0; i < inv5->nw; i++)
  441. inv5->w[i] = BIGNUM_INT_MASK / 5 * 4;
  442. inv5->w[0]++;
  443. /*
  444. * 146/485 is an upper bound (and also a continued-fraction
  445. * convergent) of log10(2), so this is a conservative estimate of
  446. * the number of decimal digits needed to store a value that fits
  447. * in this many binary bits.
  448. */
  449. assert(x->nw < (~(size_t)1) / (146 * BIGNUM_INT_BITS));
  450. { // WINSCP
  451. size_t bufsize = size_t_max(x->nw * (146 * BIGNUM_INT_BITS) / 485, 1) + 2;
  452. char *outbuf = snewn(bufsize, char);
  453. outbuf[bufsize - 1] = '\0';
  454. /*
  455. * Loop over the number generating digits from the least
  456. * significant upwards, so that we write to outbuf in reverse
  457. * order.
  458. */
  459. { // WINSCP
  460. size_t pos; // WINSCP
  461. for (pos = bufsize - 1; pos-- > 0 ;) {
  462. /*
  463. * Find the current residue mod 10. We do this by first
  464. * summing the bytes of the number, with all but the lowest
  465. * one multiplied by 6 (because 256^i == 6 mod 10 for all
  466. * i>0). That gives us a single word congruent mod 10 to the
  467. * input number, and then we reduce it further by manual
  468. * multiplication and shifting, just in case the compiler
  469. * target implements the C division operator in a way that has
  470. * input-dependent timing.
  471. */
  472. uint32_t low_digit = 0, maxval = 0, mult = 1;
  473. size_t i; // WINSCP
  474. for (i = 0; i < x->nw; i++) {
  475. unsigned j; // WINSCP
  476. for (j = 0; j < BIGNUM_INT_BYTES; j++) {
  477. low_digit += mult * (0xFF & (x->w[i] >> (8*j)));
  478. maxval += mult * 0xFF;
  479. mult = 6;
  480. }
  481. /*
  482. * For _really_ big numbers, prevent overflow of t by
  483. * periodically folding the top half of the accumulator
  484. * into the bottom half, using the same rule 'multiply by
  485. * 6 when shifting down by one or more whole bytes'.
  486. */
  487. if (maxval > UINT32_MAX - (6 * 0xFF * BIGNUM_INT_BYTES)) {
  488. low_digit = (low_digit & 0xFFFF) + 6 * (low_digit >> 16);
  489. maxval = (maxval & 0xFFFF) + 6 * (maxval >> 16);
  490. }
  491. }
  492. /*
  493. * Final reduction of low_digit. We multiply by 2^32 / 10
  494. * (that's the constant 0x19999999) to get a 64-bit value
  495. * whose top 32 bits are the approximate quotient
  496. * low_digit/10; then we subtract off 10 times that; and
  497. * finally we do one last trial subtraction of 10 by adding 6
  498. * (which sets bit 4 if the number was just over 10) and then
  499. * testing bit 4.
  500. */
  501. low_digit -= 10 * ((0x19999999ULL * low_digit) >> 32);
  502. low_digit -= 10 * ((low_digit + 6) >> 4);
  503. assert(low_digit < 10); /* make sure we did reduce fully */
  504. outbuf[pos] = '0' + low_digit;
  505. /*
  506. * Now subtract off that digit, divide by 2 (using a right
  507. * shift) and by 5 (using the modular inverse), to get the
  508. * next output digit into the units position.
  509. */
  510. mp_sub_integer_into(x, x, low_digit);
  511. mp_rshift_fixed_into(y, x, 1);
  512. mp_mul_into(x, y, inv5);
  513. }
  514. mp_free(x);
  515. mp_free(y);
  516. mp_free(inv5);
  517. trim_leading_zeroes(outbuf, bufsize, bufsize - 2);
  518. return outbuf;
  519. } // WINSCP
  520. } // WINSCP
  521. }
  522. /*
  523. * Binary to hex conversion. Reasonably simple (only a spot of bit
  524. * twiddling to choose whether to output a digit or a letter for each
  525. * nibble).
  526. */
  527. static char *mp_get_hex_internal(mp_int *x, uint8_t letter_offset)
  528. {
  529. size_t nibbles = x->nw * BIGNUM_INT_BYTES * 2;
  530. size_t bufsize = nibbles + 1;
  531. char *outbuf = snewn(bufsize, char);
  532. size_t nibble; // WINSCP
  533. outbuf[nibbles] = '\0';
  534. for (nibble = 0; nibble < nibbles; nibble++) {
  535. size_t word_idx = nibble / (BIGNUM_INT_BYTES*2);
  536. size_t nibble_within_word = nibble % (BIGNUM_INT_BYTES*2);
  537. uint8_t digitval = 0xF & (x->w[word_idx] >> (nibble_within_word * 4));
  538. uint8_t mask = -((digitval + 6) >> 4);
  539. char digit = digitval + '0' + (letter_offset & mask);
  540. outbuf[nibbles-1 - nibble] = digit;
  541. }
  542. trim_leading_zeroes(outbuf, bufsize, nibbles - 1);
  543. return outbuf;
  544. }
  545. char *mp_get_hex(mp_int *x)
  546. {
  547. return mp_get_hex_internal(x, 'a' - ('0'+10));
  548. }
  549. char *mp_get_hex_uppercase(mp_int *x)
  550. {
  551. return mp_get_hex_internal(x, 'A' - ('0'+10));
  552. }
  553. /*
  554. * Routines for reading and writing the SSH-1 and SSH-2 wire formats
  555. * for multiprecision integers, declared in marshal.h.
  556. *
  557. * These can't avoid having control flow dependent on the true bit
  558. * size of the number, because the wire format requires the number of
  559. * output bytes to depend on that.
  560. */
  561. void BinarySink_put_mp_ssh1(BinarySink *bs, mp_int *x)
  562. {
  563. size_t bits = mp_get_nbits(x);
  564. size_t bytes = (bits + 7) / 8;
  565. size_t i; // WINSCP
  566. assert(bits < 0x10000);
  567. put_uint16(bs, bits);
  568. for (i = bytes; i-- > 0 ;)
  569. put_byte(bs, mp_get_byte(x, i));
  570. }
  571. void BinarySink_put_mp_ssh2(BinarySink *bs, mp_int *x)
  572. {
  573. size_t bytes = (mp_get_nbits(x) + 8) / 8;
  574. size_t i; // WINSCP
  575. put_uint32(bs, bytes);
  576. for (i = bytes; i-- > 0 ;)
  577. put_byte(bs, mp_get_byte(x, i));
  578. }
  579. mp_int *BinarySource_get_mp_ssh1(BinarySource *src)
  580. {
  581. unsigned bitc = get_uint16(src);
  582. ptrlen bytes = get_data(src, (bitc + 7) / 8);
  583. if (get_err(src)) {
  584. return mp_from_integer(0);
  585. } else {
  586. mp_int *toret = mp_from_bytes_be(bytes);
  587. /* SSH-1.5 spec says that it's OK for the prefix uint16 to be
  588. * _greater_ than the actual number of bits */
  589. if (mp_get_nbits(toret) > bitc) {
  590. src->err = BSE_INVALID;
  591. mp_free(toret);
  592. toret = mp_from_integer(0);
  593. }
  594. return toret;
  595. }
  596. }
  597. mp_int *BinarySource_get_mp_ssh2(BinarySource *src)
  598. {
  599. ptrlen bytes = get_string(src);
  600. if (get_err(src)) {
  601. return mp_from_integer(0);
  602. } else {
  603. const unsigned char *p = bytes.ptr;
  604. if ((bytes.len > 0 &&
  605. ((p[0] & 0x80) ||
  606. (p[0] == 0 && (bytes.len <= 1 || !(p[1] & 0x80)))))) {
  607. src->err = BSE_INVALID;
  608. return mp_from_integer(0);
  609. }
  610. return mp_from_bytes_be(bytes);
  611. }
  612. }
  613. /*
  614. * Make an mp_int structure whose words array aliases a subinterval of
  615. * some other mp_int. This makes it easy to read or write just the low
  616. * or high words of a number, e.g. to add a number starting from a
  617. * high bit position, or to reduce mod 2^{n*BIGNUM_INT_BITS}.
  618. *
  619. * The convention throughout this code is that when we store an mp_int
  620. * directly by value, we always expect it to be an alias of some kind,
  621. * so its words array won't ever need freeing. Whereas an 'mp_int *'
  622. * has an owner, who knows whether it needs freeing or whether it was
  623. * created by address-taking an alias.
  624. */
  625. static mp_int mp_make_alias(mp_int *in, size_t offset, size_t len)
  626. {
  627. /*
  628. * Bounds-check the offset and length so that we always return
  629. * something valid, even if it's not necessarily the length the
  630. * caller asked for.
  631. */
  632. if (offset > in->nw)
  633. offset = in->nw;
  634. if (len > in->nw - offset)
  635. len = in->nw - offset;
  636. { // WINSCP
  637. mp_int toret;
  638. toret.nw = len;
  639. toret.w = in->w + offset;
  640. return toret;
  641. } // WINSCP
  642. }
  643. /*
  644. * A special case of mp_make_alias: in some cases we preallocate a
  645. * large mp_int to use as scratch space (to avoid pointless
  646. * malloc/free churn in recursive or iterative work).
  647. *
  648. * mp_alloc_from_scratch creates an alias of size 'len' to part of
  649. * 'pool', and adjusts 'pool' itself so that further allocations won't
  650. * overwrite that space.
  651. *
  652. * There's no free function to go with this. Typically you just copy
  653. * the pool mp_int by value, allocate from the copy, and when you're
  654. * done with those allocations, throw the copy away and go back to the
  655. * original value of pool. (A mark/release system.)
  656. */
  657. static mp_int mp_alloc_from_scratch(mp_int *pool, size_t len)
  658. {
  659. pinitassert(len <= pool->nw);
  660. mp_int toret = mp_make_alias(pool, 0, len);
  661. *pool = mp_make_alias(pool, len, pool->nw);
  662. return toret;
  663. }
  664. /*
  665. * Internal component common to lots of assorted add/subtract code.
  666. * Reads words from a,b; writes into w_out (which might be NULL if the
  667. * output isn't even needed). Takes an input carry flag in 'carry',
  668. * and returns the output carry. Each word read from b is ANDed with
  669. * b_and and then XORed with b_xor.
  670. *
  671. * So you can implement addition by setting b_and to all 1s and b_xor
  672. * to 0; you can subtract by making b_xor all 1s too (effectively
  673. * bit-flipping b) and also passing 1 as the input carry (to turn
  674. * one's complement into two's complement). And you can do conditional
  675. * add/subtract by choosing b_and to be all 1s or all 0s based on a
  676. * condition, because the value of b will be totally ignored if b_and
  677. * == 0.
  678. */
  679. static BignumCarry mp_add_masked_into(
  680. BignumInt *w_out, size_t rw, mp_int *a, mp_int *b,
  681. BignumInt b_and, BignumInt b_xor, BignumCarry carry)
  682. {
  683. size_t i; // WINSCP
  684. for (i = 0; i < rw; i++) {
  685. BignumInt aword = mp_word(a, i), bword = mp_word(b, i), out;
  686. bword = (bword & b_and) ^ b_xor;
  687. BignumADC(out, carry, aword, bword, carry);
  688. if (w_out)
  689. w_out[i] = out;
  690. }
  691. return carry;
  692. }
  693. /*
  694. * Like the public mp_add_into except that it returns the output carry.
  695. */
  696. static inline BignumCarry mp_add_into_internal(mp_int *r, mp_int *a, mp_int *b)
  697. {
  698. return mp_add_masked_into(r->w, r->nw, a, b, ~(BignumInt)0, 0, 0);
  699. }
  700. void mp_add_into(mp_int *r, mp_int *a, mp_int *b)
  701. {
  702. mp_add_into_internal(r, a, b);
  703. }
  704. void mp_sub_into(mp_int *r, mp_int *a, mp_int *b)
  705. {
  706. mp_add_masked_into(r->w, r->nw, a, b, ~(BignumInt)0, ~(BignumInt)0, 1);
  707. }
  708. void mp_and_into(mp_int *r, mp_int *a, mp_int *b)
  709. {
  710. size_t i; // WINSCP
  711. for (i = 0; i < r->nw; i++) {
  712. BignumInt aword = mp_word(a, i), bword = mp_word(b, i);
  713. r->w[i] = aword & bword;
  714. }
  715. }
  716. void mp_or_into(mp_int *r, mp_int *a, mp_int *b)
  717. {
  718. size_t i; // WINSCP
  719. for (i = 0; i < r->nw; i++) {
  720. BignumInt aword = mp_word(a, i), bword = mp_word(b, i);
  721. r->w[i] = aword | bword;
  722. }
  723. }
  724. void mp_xor_into(mp_int *r, mp_int *a, mp_int *b)
  725. {
  726. size_t i; // WINSCP
  727. for (i = 0; i < r->nw; i++) {
  728. BignumInt aword = mp_word(a, i), bword = mp_word(b, i);
  729. r->w[i] = aword ^ bword;
  730. }
  731. }
  732. void mp_bic_into(mp_int *r, mp_int *a, mp_int *b)
  733. {
  734. size_t i; // WINSCP
  735. for (i = 0; i < r->nw; i++) {
  736. BignumInt aword = mp_word(a, i), bword = mp_word(b, i);
  737. r->w[i] = aword & ~bword;
  738. }
  739. }
  740. static void mp_cond_negate(mp_int *r, mp_int *x, unsigned yes)
  741. {
  742. BignumCarry carry = yes;
  743. BignumInt flip = -(BignumInt)yes;
  744. size_t i; // WINSCP
  745. for (i = 0; i < r->nw; i++) {
  746. BignumInt xword = mp_word(x, i);
  747. xword ^= flip;
  748. BignumADC(r->w[i], carry, 0, xword, carry);
  749. }
  750. }
  751. /*
  752. * Similar to mp_add_masked_into, but takes a C integer instead of an
  753. * mp_int as the masked operand.
  754. */
  755. static BignumCarry mp_add_masked_integer_into(
  756. BignumInt *w_out, size_t rw, mp_int *a, uintmax_t b,
  757. BignumInt b_and, BignumInt b_xor, BignumCarry carry)
  758. {
  759. size_t i; // WINSCP
  760. for (i = 0; i < rw; i++) {
  761. BignumInt aword = mp_word(a, i);
  762. BignumInt bword = b;
  763. b = shift_right_by_one_word(b);
  764. { // WINSCP
  765. BignumInt out;
  766. bword = (bword ^ b_xor) & b_and;
  767. BignumADC(out, carry, aword, bword, carry);
  768. if (w_out)
  769. w_out[i] = out;
  770. } // WINSCP
  771. }
  772. return carry;
  773. }
  774. void mp_add_integer_into(mp_int *r, mp_int *a, uintmax_t n)
  775. {
  776. mp_add_masked_integer_into(r->w, r->nw, a, n, ~(BignumInt)0, 0, 0);
  777. }
  778. void mp_sub_integer_into(mp_int *r, mp_int *a, uintmax_t n)
  779. {
  780. mp_add_masked_integer_into(r->w, r->nw, a, n,
  781. ~(BignumInt)0, ~(BignumInt)0, 1);
  782. }
  783. /*
  784. * Sets r to a + n << (word_index * BIGNUM_INT_BITS), treating
  785. * word_index as secret data.
  786. */
  787. static void mp_add_integer_into_shifted_by_words(
  788. mp_int *r, mp_int *a, uintmax_t n, size_t word_index)
  789. {
  790. unsigned indicator = 0;
  791. BignumCarry carry = 0;
  792. size_t i; // WINSCP
  793. for (i = 0; i < r->nw; i++) {
  794. /* indicator becomes 1 when we reach the index that the least
  795. * significant bits of n want to be placed at, and it stays 1
  796. * thereafter. */
  797. indicator |= 1 ^ normalise_to_1(i ^ word_index);
  798. /* If indicator is 1, we add the low bits of n into r, and
  799. * shift n down. If it's 0, we add zero bits into r, and
  800. * leave n alone. */
  801. { // WINSCP
  802. BignumInt bword = n & -(BignumInt)indicator;
  803. uintmax_t new_n = shift_right_by_one_word(n);
  804. n ^= (n ^ new_n) & -(uintmax_t)indicator;
  805. { // WINSCP
  806. BignumInt aword = mp_word(a, i);
  807. BignumInt out;
  808. BignumADC(out, carry, aword, bword, carry);
  809. r->w[i] = out;
  810. } // WINSCP
  811. } // WINSCP
  812. }
  813. }
  814. void mp_mul_integer_into(mp_int *r, mp_int *a, uint16_t n)
  815. {
  816. BignumInt carry = 0, mult = n;
  817. size_t i; // WINSCP
  818. for (i = 0; i < r->nw; i++) {
  819. BignumInt aword = mp_word(a, i);
  820. BignumMULADD(carry, r->w[i], aword, mult, carry);
  821. }
  822. assert(!carry);
  823. }
  824. void mp_cond_add_into(mp_int *r, mp_int *a, mp_int *b, unsigned yes)
  825. {
  826. BignumInt mask = -(BignumInt)(yes & 1);
  827. mp_add_masked_into(r->w, r->nw, a, b, mask, 0, 0);
  828. }
  829. void mp_cond_sub_into(mp_int *r, mp_int *a, mp_int *b, unsigned yes)
  830. {
  831. BignumInt mask = -(BignumInt)(yes & 1);
  832. mp_add_masked_into(r->w, r->nw, a, b, mask, mask, 1 & mask);
  833. }
  834. /*
  835. * Ordered comparison between unsigned numbers is done by subtracting
  836. * one from the other and looking at the output carry.
  837. */
  838. unsigned mp_cmp_hs(mp_int *a, mp_int *b)
  839. {
  840. size_t rw = size_t_max(a->nw, b->nw);
  841. return mp_add_masked_into(NULL, rw, a, b, ~(BignumInt)0, ~(BignumInt)0, 1);
  842. }
  843. unsigned mp_hs_integer(mp_int *x, uintmax_t n)
  844. {
  845. BignumInt carry = 1;
  846. size_t nwords = sizeof(n)/BIGNUM_INT_BYTES;
  847. size_t i, e; // WINSCP
  848. for (i = 0, e = size_t_max(x->nw, nwords); i < e; i++) {
  849. BignumInt nword = n;
  850. n = shift_right_by_one_word(n);
  851. { // WINSCP
  852. BignumInt dummy_out;
  853. BignumADC(dummy_out, carry, mp_word(x, i), ~nword, carry);
  854. (void)dummy_out;
  855. } // WINSCP
  856. }
  857. return carry;
  858. }
  859. /*
  860. * Equality comparison is done by bitwise XOR of the input numbers,
  861. * ORing together all the output words, and normalising the result
  862. * using our careful normalise_to_1 helper function.
  863. */
  864. unsigned mp_cmp_eq(mp_int *a, mp_int *b)
  865. {
  866. BignumInt diff = 0;
  867. size_t i, limit; // WINSCP
  868. for (i = 0, limit = size_t_max(a->nw, b->nw); i < limit; i++)
  869. diff |= mp_word(a, i) ^ mp_word(b, i);
  870. return 1 ^ normalise_to_1(diff); /* return 1 if diff _is_ zero */
  871. }
  872. unsigned mp_eq_integer(mp_int *x, uintmax_t n)
  873. {
  874. BignumInt diff = 0;
  875. size_t nwords = sizeof(n)/BIGNUM_INT_BYTES;
  876. size_t i, e; // WINSCP
  877. for (i = 0, e = size_t_max(x->nw, nwords); i < e; i++) {
  878. BignumInt nword = n;
  879. n = shift_right_by_one_word(n);
  880. diff |= mp_word(x, i) ^ nword;
  881. }
  882. return 1 ^ normalise_to_1(diff); /* return 1 if diff _is_ zero */
  883. }
  884. static void mp_neg_into(mp_int *r, mp_int *a)
  885. {
  886. mp_int zero;
  887. zero.nw = 0;
  888. mp_sub_into(r, &zero, a);
  889. }
  890. mp_int *mp_add(mp_int *x, mp_int *y)
  891. {
  892. mp_int *r = mp_make_sized(size_t_max(x->nw, y->nw) + 1);
  893. mp_add_into(r, x, y);
  894. return r;
  895. }
  896. mp_int *mp_sub(mp_int *x, mp_int *y)
  897. {
  898. mp_int *r = mp_make_sized(size_t_max(x->nw, y->nw));
  899. mp_sub_into(r, x, y);
  900. return r;
  901. }
  902. /*
  903. * Internal routine: multiply and accumulate in the trivial O(N^2)
  904. * way. Sets r <- r + a*b.
  905. */
  906. static void mp_mul_add_simple(mp_int *r, mp_int *a, mp_int *b)
  907. {
  908. BignumInt *aend = a->w + a->nw, *bend = b->w + b->nw, *rend = r->w + r->nw;
  909. BignumInt *ap, *rp; // WINSCP
  910. for (ap = a->w, rp = r->w;
  911. ap < aend && rp < rend; ap++, rp++) {
  912. BignumInt adata = *ap, carry = 0, *rq = rp;
  913. { // WINSCP
  914. BignumInt *bp; // WINSCP
  915. for (bp = b->w; bp < bend && rq < rend; bp++, rq++) {
  916. BignumInt bdata = bp < bend ? *bp : 0;
  917. BignumMULADD2(carry, *rq, adata, bdata, *rq, carry);
  918. }
  919. } // WINSCP
  920. for (; rq < rend; rq++)
  921. BignumADC(*rq, carry, carry, *rq, 0);
  922. }
  923. }
  924. #ifndef KARATSUBA_THRESHOLD /* allow redefinition via -D for testing */
  925. #define KARATSUBA_THRESHOLD 24
  926. #endif
  927. static inline size_t mp_mul_scratchspace_unary(size_t n)
  928. {
  929. /*
  930. * Simplistic and overcautious bound on the amount of scratch
  931. * space that the recursive multiply function will need.
  932. *
  933. * The rationale is: on the main Karatsuba branch of
  934. * mp_mul_internal, which is the most space-intensive one, we
  935. * allocate space for (a0+a1) and (b0+b1) (each just over half the
  936. * input length n) and their product (the sum of those sizes, i.e.
  937. * just over n itself). Then in order to actually compute the
  938. * product, we do a recursive multiplication of size just over n.
  939. *
  940. * If all those 'just over' weren't there, and everything was
  941. * _exactly_ half the length, you'd get the amount of space for a
  942. * size-n multiply defined by the recurrence M(n) = 2n + M(n/2),
  943. * which is satisfied by M(n) = 4n. But instead it's (2n plus a
  944. * word or two) and M(n/2 plus a word or two). On the assumption
  945. * that there's still some constant k such that M(n) <= kn, this
  946. * gives us kn = 2n + w + k(n/2 + w), where w is a small constant
  947. * (one or two words). That simplifies to kn/2 = 2n + (k+1)w, and
  948. * since we don't even _start_ needing scratch space until n is at
  949. * least 50, we can bound 2n + (k+1)w above by 3n, giving k=6.
  950. *
  951. * So I claim that 6n words of scratch space will suffice, and I
  952. * check that by assertion at every stage of the recursion.
  953. */
  954. return n * 6;
  955. }
  956. static size_t mp_mul_scratchspace(size_t rw, size_t aw, size_t bw)
  957. {
  958. size_t inlen = size_t_min(rw, size_t_max(aw, bw));
  959. return mp_mul_scratchspace_unary(inlen);
  960. }
  961. static void mp_mul_internal(mp_int *r, mp_int *a, mp_int *b, mp_int scratch)
  962. {
  963. size_t inlen = size_t_min(r->nw, size_t_max(a->nw, b->nw));
  964. assert(scratch.nw >= mp_mul_scratchspace_unary(inlen));
  965. mp_clear(r);
  966. if (inlen < KARATSUBA_THRESHOLD || a->nw == 0 || b->nw == 0) {
  967. /*
  968. * The input numbers are too small to bother optimising. Go
  969. * straight to the simple primitive approach.
  970. */
  971. mp_mul_add_simple(r, a, b);
  972. return;
  973. }
  974. /*
  975. * Karatsuba divide-and-conquer algorithm. We cut each input in
  976. * half, so that it's expressed as two big 'digits' in a giant
  977. * base D:
  978. *
  979. * a = a_1 D + a_0
  980. * b = b_1 D + b_0
  981. *
  982. * Then the product is of course
  983. *
  984. * ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0
  985. *
  986. * and we compute the three coefficients by recursively calling
  987. * ourself to do half-length multiplications.
  988. *
  989. * The clever bit that makes this worth doing is that we only need
  990. * _one_ half-length multiplication for the central coefficient
  991. * rather than the two that it obviouly looks like, because we can
  992. * use a single multiplication to compute
  993. *
  994. * (a_1 + a_0) (b_1 + b_0) = a_1 b_1 + a_1 b_0 + a_0 b_1 + a_0 b_0
  995. *
  996. * and then we subtract the other two coefficients (a_1 b_1 and
  997. * a_0 b_0) which we were computing anyway.
  998. *
  999. * Hence we get to multiply two numbers of length N in about three
  1000. * times as much work as it takes to multiply numbers of length
  1001. * N/2, which is obviously better than the four times as much work
  1002. * it would take if we just did a long conventional multiply.
  1003. */
  1004. { // WINSCP
  1005. /* Break up the input as botlen + toplen, with botlen >= toplen.
  1006. * The 'base' D is equal to 2^{botlen * BIGNUM_INT_BITS}. */
  1007. size_t toplen = inlen / 2;
  1008. size_t botlen = inlen - toplen;
  1009. /* Alias bignums that address the two halves of a,b, and useful
  1010. * pieces of r. */
  1011. mp_int a0 = mp_make_alias(a, 0, botlen);
  1012. mp_int b0 = mp_make_alias(b, 0, botlen);
  1013. mp_int a1 = mp_make_alias(a, botlen, toplen);
  1014. mp_int b1 = mp_make_alias(b, botlen, toplen);
  1015. mp_int r0 = mp_make_alias(r, 0, botlen*2);
  1016. mp_int r1 = mp_make_alias(r, botlen, r->nw);
  1017. mp_int r2 = mp_make_alias(r, botlen*2, r->nw);
  1018. /* Recurse to compute a0*b0 and a1*b1, in their correct positions
  1019. * in the output bignum. They can't overlap. */
  1020. mp_mul_internal(&r0, &a0, &b0, scratch);
  1021. mp_mul_internal(&r2, &a1, &b1, scratch);
  1022. if (r->nw < inlen*2) {
  1023. /*
  1024. * The output buffer isn't large enough to require the whole
  1025. * product, so some of a1*b1 won't have been stored. In that
  1026. * case we won't try to do the full Karatsuba optimisation;
  1027. * we'll just recurse again to compute a0*b1 and a1*b0 - or at
  1028. * least as much of them as the output buffer size requires -
  1029. * and add each one in.
  1030. */
  1031. mp_int s = mp_alloc_from_scratch(
  1032. &scratch, size_t_min(botlen+toplen, r1.nw));
  1033. mp_mul_internal(&s, &a0, &b1, scratch);
  1034. mp_add_into(&r1, &r1, &s);
  1035. mp_mul_internal(&s, &a1, &b0, scratch);
  1036. mp_add_into(&r1, &r1, &s);
  1037. return;
  1038. }
  1039. { // WINSCP
  1040. /* a0+a1 and b0+b1 */
  1041. mp_int asum = mp_alloc_from_scratch(&scratch, botlen+1);
  1042. mp_int bsum = mp_alloc_from_scratch(&scratch, botlen+1);
  1043. mp_add_into(&asum, &a0, &a1);
  1044. mp_add_into(&bsum, &b0, &b1);
  1045. { // WINSCP
  1046. /* Their product */
  1047. mp_int product = mp_alloc_from_scratch(&scratch, botlen*2+1);
  1048. mp_mul_internal(&product, &asum, &bsum, scratch);
  1049. /* Subtract off the outer terms we already have */
  1050. mp_sub_into(&product, &product, &r0);
  1051. mp_sub_into(&product, &product, &r2);
  1052. /* And add it in with the right offset. */
  1053. mp_add_into(&r1, &r1, &product);
  1054. } // WINSCP
  1055. } // WINSCP
  1056. } // WINSCP
  1057. }
  1058. void mp_mul_into(mp_int *r, mp_int *a, mp_int *b)
  1059. {
  1060. mp_int *scratch = mp_make_sized(mp_mul_scratchspace(r->nw, a->nw, b->nw));
  1061. mp_mul_internal(r, a, b, *scratch);
  1062. mp_free(scratch);
  1063. }
  1064. mp_int *mp_mul(mp_int *x, mp_int *y)
  1065. {
  1066. mp_int *r = mp_make_sized(x->nw + y->nw);
  1067. mp_mul_into(r, x, y);
  1068. return r;
  1069. }
  1070. void mp_lshift_fixed_into(mp_int *r, mp_int *a, size_t bits)
  1071. {
  1072. size_t words = bits / BIGNUM_INT_BITS;
  1073. size_t bitoff = bits % BIGNUM_INT_BITS;
  1074. size_t i; // WINSCP
  1075. for (i = r->nw; i-- > 0 ;) {
  1076. if (i < words) {
  1077. r->w[i] = 0;
  1078. } else {
  1079. r->w[i] = mp_word(a, i - words);
  1080. if (bitoff != 0) {
  1081. r->w[i] <<= bitoff;
  1082. if (i > words)
  1083. r->w[i] |= mp_word(a, i - words - 1) >>
  1084. (BIGNUM_INT_BITS - bitoff);
  1085. }
  1086. }
  1087. }
  1088. }
  1089. void mp_rshift_fixed_into(mp_int *r, mp_int *a, size_t bits)
  1090. {
  1091. size_t words = bits / BIGNUM_INT_BITS;
  1092. size_t bitoff = bits % BIGNUM_INT_BITS;
  1093. size_t i; // WINSCP
  1094. for (i = 0; i < r->nw; i++) {
  1095. r->w[i] = mp_word(a, i + words);
  1096. if (bitoff != 0) {
  1097. r->w[i] >>= bitoff;
  1098. r->w[i] |= mp_word(a, i + words + 1) << (BIGNUM_INT_BITS - bitoff);
  1099. }
  1100. }
  1101. }
  1102. mp_int *mp_lshift_fixed(mp_int *x, size_t bits)
  1103. {
  1104. size_t words = (bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS;
  1105. mp_int *r = mp_make_sized(x->nw + words);
  1106. mp_lshift_fixed_into(r, x, bits);
  1107. return r;
  1108. }
  1109. mp_int *mp_rshift_fixed(mp_int *x, size_t bits)
  1110. {
  1111. size_t words = bits / BIGNUM_INT_BITS;
  1112. size_t nw = x->nw - size_t_min(x->nw, words);
  1113. mp_int *r = mp_make_sized(size_t_max(nw, 1));
  1114. mp_rshift_fixed_into(r, x, bits);
  1115. return r;
  1116. }
  1117. /*
  1118. * Safe right shift is done using the same technique as
  1119. * trim_leading_zeroes above: you make an n-word left shift by
  1120. * composing an appropriate subset of power-of-2-sized shifts, so it
  1121. * takes log_2(n) loop iterations each of which does a different shift
  1122. * by a power of 2 words, using the usual bit twiddling to make the
  1123. * whole shift conditional on the appropriate bit of n.
  1124. */
  1125. static void mp_rshift_safe_in_place(mp_int *r, size_t bits)
  1126. {
  1127. size_t wordshift = bits / BIGNUM_INT_BITS;
  1128. size_t bitshift = bits % BIGNUM_INT_BITS;
  1129. unsigned bit; // WINSCP
  1130. unsigned clear = (r->nw - wordshift) >> (CHAR_BIT * sizeof(size_t) - 1);
  1131. mp_cond_clear(r, clear);
  1132. for (bit = 0; r->nw >> bit; bit++) {
  1133. size_t word_offset = (size_t)1 << bit;
  1134. BignumInt mask = -(BignumInt)((wordshift >> bit) & 1);
  1135. size_t i; // WINSCP
  1136. for (i = 0; i < r->nw; i++) {
  1137. BignumInt w = mp_word(r, i + word_offset);
  1138. r->w[i] ^= (r->w[i] ^ w) & mask;
  1139. }
  1140. }
  1141. /*
  1142. * That's done the shifting by words; now we do the shifting by
  1143. * bits.
  1144. */
  1145. for (bit = 0; bit < BIGNUM_INT_BITS_BITS; bit++) { // WINSCP
  1146. unsigned shift = 1 << bit, upshift = BIGNUM_INT_BITS - shift;
  1147. BignumInt mask = -(BignumInt)((bitshift >> bit) & 1);
  1148. size_t i; // WINSCP
  1149. for (i = 0; i < r->nw; i++) {
  1150. BignumInt w = ((r->w[i] >> shift) | (mp_word(r, i+1) << upshift));
  1151. r->w[i] ^= (r->w[i] ^ w) & mask;
  1152. }
  1153. }
  1154. }
  1155. mp_int *mp_rshift_safe(mp_int *x, size_t bits)
  1156. {
  1157. mp_int *r = mp_copy(x);
  1158. mp_rshift_safe_in_place(r, bits);
  1159. return r;
  1160. }
  1161. void mp_rshift_safe_into(mp_int *r, mp_int *x, size_t bits)
  1162. {
  1163. mp_copy_into(r, x);
  1164. mp_rshift_safe_in_place(r, bits);
  1165. }
  1166. static void mp_lshift_safe_in_place(mp_int *r, size_t bits)
  1167. {
  1168. size_t wordshift = bits / BIGNUM_INT_BITS;
  1169. size_t bitshift = bits % BIGNUM_INT_BITS;
  1170. /*
  1171. * Same strategy as mp_rshift_safe_in_place, but of course the
  1172. * other way up.
  1173. */
  1174. unsigned clear = (r->nw - wordshift) >> (CHAR_BIT * sizeof(size_t) - 1);
  1175. mp_cond_clear(r, clear);
  1176. { // WINSCP
  1177. unsigned bit; // WINSCP
  1178. for (bit = 0; r->nw >> bit; bit++) {
  1179. size_t word_offset = (size_t)1 << bit;
  1180. BignumInt mask = -(BignumInt)((wordshift >> bit) & 1);
  1181. size_t i; // WINSCP
  1182. for (i = r->nw; i-- > 0 ;) {
  1183. BignumInt w = mp_word(r, i - word_offset);
  1184. r->w[i] ^= (r->w[i] ^ w) & mask;
  1185. }
  1186. }
  1187. { // WINSCP
  1188. size_t downshift = BIGNUM_INT_BITS - bitshift;
  1189. size_t no_shift = (downshift >> BIGNUM_INT_BITS_BITS);
  1190. downshift &= ~-(size_t)no_shift;
  1191. { // WINSCP
  1192. BignumInt downshifted_mask = ~-(BignumInt)no_shift;
  1193. size_t i; // WINSCP
  1194. for (i = r->nw; i-- > 0 ;) {
  1195. r->w[i] = (r->w[i] << bitshift) |
  1196. ((mp_word(r, i-1) >> downshift) & downshifted_mask);
  1197. }
  1198. } // WINSCP
  1199. } // WINSCP
  1200. } // WINSCP
  1201. }
  1202. void mp_lshift_safe_into(mp_int *r, mp_int *x, size_t bits)
  1203. {
  1204. mp_copy_into(r, x);
  1205. mp_lshift_safe_in_place(r, bits);
  1206. }
  1207. void mp_reduce_mod_2to(mp_int *x, size_t p)
  1208. {
  1209. size_t word = p / BIGNUM_INT_BITS;
  1210. size_t mask = ((size_t)1 << (p % BIGNUM_INT_BITS)) - 1;
  1211. for (; word < x->nw; word++) {
  1212. x->w[word] &= mask;
  1213. mask = 0;
  1214. }
  1215. }
  1216. /*
  1217. * Inverse mod 2^n is computed by an iterative technique which doubles
  1218. * the number of bits at each step.
  1219. */
  1220. mp_int *mp_invert_mod_2to(mp_int *x, size_t p)
  1221. {
  1222. /* Input checks: x must be coprime to the modulus, i.e. odd, and p
  1223. * can't be zero */
  1224. assert(x->nw > 0);
  1225. assert(x->w[0] & 1);
  1226. assert(p > 0);
  1227. { // WINSCP
  1228. size_t rw = (p + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS;
  1229. rw = size_t_max(rw, 1);
  1230. { // WINSCP
  1231. mp_int *r = mp_make_sized(rw);
  1232. size_t mul_scratchsize = mp_mul_scratchspace(2*rw, rw, rw);
  1233. mp_int *scratch_orig = mp_make_sized(6 * rw + mul_scratchsize);
  1234. mp_int scratch_per_iter = *scratch_orig;
  1235. mp_int mul_scratch = mp_alloc_from_scratch(
  1236. &scratch_per_iter, mul_scratchsize);
  1237. size_t b; // WINSCP
  1238. r->w[0] = 1;
  1239. for (b = 1; b < p; b <<= 1) {
  1240. /*
  1241. * In each step of this iteration, we have the inverse of x
  1242. * mod 2^b, and we want the inverse of x mod 2^{2b}.
  1243. *
  1244. * Write B = 2^b for convenience, so we want x^{-1} mod B^2.
  1245. * Let x = x_0 + B x_1 + k B^2, with 0 <= x_0,x_1 < B.
  1246. *
  1247. * We want to find r_0 and r_1 such that
  1248. * (r_1 B + r_0) (x_1 B + x_0) == 1 (mod B^2)
  1249. *
  1250. * To begin with, we know r_0 must be the inverse mod B of
  1251. * x_0, i.e. of x, i.e. it is the inverse we computed in the
  1252. * previous iteration. So now all we need is r_1.
  1253. *
  1254. * Multiplying out, neglecting multiples of B^2, and writing
  1255. * x_0 r_0 = K B + 1, we have
  1256. *
  1257. * r_1 x_0 B + r_0 x_1 B + K B == 0 (mod B^2)
  1258. * => r_1 x_0 B == - r_0 x_1 B - K B (mod B^2)
  1259. * => r_1 x_0 == - r_0 x_1 - K (mod B)
  1260. * => r_1 == r_0 (- r_0 x_1 - K) (mod B)
  1261. *
  1262. * (the last step because we multiply through by the inverse
  1263. * of x_0, which we already know is r_0).
  1264. */
  1265. mp_int scratch_this_iter = scratch_per_iter;
  1266. size_t Bw = (b + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS;
  1267. size_t B2w = (2*b + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS;
  1268. /* Start by finding K: multiply x_0 by r_0, and shift down. */
  1269. mp_int x0 = mp_alloc_from_scratch(&scratch_this_iter, Bw);
  1270. mp_copy_into(&x0, x);
  1271. mp_reduce_mod_2to(&x0, b);
  1272. { // WINSCP
  1273. mp_int r0 = mp_make_alias(r, 0, Bw);
  1274. mp_int Kshift = mp_alloc_from_scratch(&scratch_this_iter, B2w);
  1275. mp_mul_internal(&Kshift, &x0, &r0, mul_scratch);
  1276. { // WINSCP
  1277. mp_int K = mp_alloc_from_scratch(&scratch_this_iter, Bw);
  1278. mp_rshift_fixed_into(&K, &Kshift, b);
  1279. /* Now compute the product r_0 x_1, reusing the space of Kshift. */
  1280. { // WINSCP
  1281. mp_int x1 = mp_alloc_from_scratch(&scratch_this_iter, Bw);
  1282. mp_rshift_fixed_into(&x1, x, b);
  1283. mp_reduce_mod_2to(&x1, b);
  1284. { // WINSCP
  1285. mp_int r0x1 = mp_make_alias(&Kshift, 0, Bw);
  1286. mp_mul_internal(&r0x1, &r0, &x1, mul_scratch);
  1287. /* Add K to that. */
  1288. mp_add_into(&r0x1, &r0x1, &K);
  1289. /* Negate it. */
  1290. mp_neg_into(&r0x1, &r0x1);
  1291. /* Multiply by r_0. */
  1292. { // WINSCP
  1293. mp_int r1 = mp_alloc_from_scratch(&scratch_this_iter, Bw);
  1294. mp_mul_internal(&r1, &r0, &r0x1, mul_scratch);
  1295. mp_reduce_mod_2to(&r1, b);
  1296. /* That's our r_1, so add it on to r_0 to get the full inverse
  1297. * output from this iteration. */
  1298. mp_lshift_fixed_into(&K, &r1, (b % BIGNUM_INT_BITS));
  1299. { // WINSCP
  1300. size_t Bpos = b / BIGNUM_INT_BITS;
  1301. mp_int r1_position = mp_make_alias(r, Bpos, B2w-Bpos);
  1302. mp_add_into(&r1_position, &r1_position, &K);
  1303. } // WINSCP
  1304. } // WINSCP
  1305. } // WINSCP
  1306. } // WINSCP
  1307. } // WINSCP
  1308. } // WINSCP
  1309. }
  1310. /* Finally, reduce mod the precise desired number of bits. */
  1311. mp_reduce_mod_2to(r, p);
  1312. mp_free(scratch_orig);
  1313. return r;
  1314. } // WINSCP
  1315. } // WINSCP
  1316. }
  1317. static size_t monty_scratch_size(MontyContext *mc)
  1318. {
  1319. return 3*mc->rw + mc->pw + mp_mul_scratchspace(mc->pw, mc->rw, mc->rw);
  1320. }
  1321. MontyContext *monty_new(mp_int *modulus)
  1322. {
  1323. MontyContext *mc = snew(MontyContext);
  1324. mc->rw = modulus->nw;
  1325. mc->rbits = mc->rw * BIGNUM_INT_BITS;
  1326. mc->pw = mc->rw * 2 + 1;
  1327. mc->m = mp_copy(modulus);
  1328. mc->minus_minv_mod_r = mp_invert_mod_2to(mc->m, mc->rbits);
  1329. mp_neg_into(mc->minus_minv_mod_r, mc->minus_minv_mod_r);
  1330. { // WINSCP
  1331. size_t j; // WINSCP
  1332. mp_int *r = mp_make_sized(mc->rw + 1);
  1333. r->w[mc->rw] = 1;
  1334. mc->powers_of_r_mod_m[0] = mp_mod(r, mc->m);
  1335. mp_free(r);
  1336. for (j = 1; j < lenof(mc->powers_of_r_mod_m); j++)
  1337. mc->powers_of_r_mod_m[j] = mp_modmul(
  1338. mc->powers_of_r_mod_m[0], mc->powers_of_r_mod_m[j-1], mc->m);
  1339. mc->scratch = mp_make_sized(monty_scratch_size(mc));
  1340. return mc;
  1341. } // WINSCP
  1342. }
  1343. void monty_free(MontyContext *mc)
  1344. {
  1345. size_t j; // WINSCP
  1346. mp_free(mc->m);
  1347. for (j = 0; j < 3; j++)
  1348. mp_free(mc->powers_of_r_mod_m[j]);
  1349. mp_free(mc->minus_minv_mod_r);
  1350. mp_free(mc->scratch);
  1351. smemclr(mc, sizeof(*mc));
  1352. sfree(mc);
  1353. }
  1354. /*
  1355. * The main Montgomery reduction step.
  1356. */
  1357. static mp_int monty_reduce_internal(MontyContext *mc, mp_int *x, mp_int scratch)
  1358. {
  1359. /*
  1360. * The trick with Montgomery reduction is that on the one hand we
  1361. * want to reduce the size of the input by a factor of about r,
  1362. * and on the other hand, the two numbers we just multiplied were
  1363. * both stored with an extra factor of r multiplied in. So we
  1364. * computed ar*br = ab r^2, but we want to return abr, so we need
  1365. * to divide by r - and if we can do that by _actually dividing_
  1366. * by r then this also reduces the size of the number.
  1367. *
  1368. * But we can only do that if the number we're dividing by r is a
  1369. * multiple of r. So first we must add an adjustment to it which
  1370. * clears its bottom 'rbits' bits. That adjustment must be a
  1371. * multiple of m in order to leave the residue mod n unchanged, so
  1372. * the question is, what multiple of m can we add to x to make it
  1373. * congruent to 0 mod r? And the answer is, x * (-m)^{-1} mod r.
  1374. */
  1375. /* x mod r */
  1376. mp_int x_lo = mp_make_alias(x, 0, mc->rbits);
  1377. /* x * (-m)^{-1}, i.e. the number we want to multiply by m */
  1378. mp_int k = mp_alloc_from_scratch(&scratch, mc->rw);
  1379. mp_mul_internal(&k, &x_lo, mc->minus_minv_mod_r, scratch);
  1380. /* m times that, i.e. the number we want to add to x */
  1381. { // WINSCP
  1382. mp_int mk = mp_alloc_from_scratch(&scratch, mc->pw);
  1383. mp_mul_internal(&mk, mc->m, &k, scratch);
  1384. /* Add it to x */
  1385. mp_add_into(&mk, x, &mk);
  1386. /* Reduce mod r, by simply making an alias to the upper words of x */
  1387. { // WINSCP
  1388. mp_int toret = mp_make_alias(&mk, mc->rw, mk.nw - mc->rw);
  1389. /*
  1390. * We'll generally be doing this after a multiplication of two
  1391. * fully reduced values. So our input could be anything up to m^2,
  1392. * and then we added up to rm to it. Hence, the maximum value is
  1393. * rm+m^2, and after dividing by r, that becomes r + m(m/r) < 2r.
  1394. * So a single trial-subtraction will finish reducing to the
  1395. * interval [0,m).
  1396. */
  1397. mp_cond_sub_into(&toret, &toret, mc->m, mp_cmp_hs(&toret, mc->m));
  1398. return toret;
  1399. } // WINSCP
  1400. } // WINSCP
  1401. }
  1402. void monty_mul_into(MontyContext *mc, mp_int *r, mp_int *x, mp_int *y)
  1403. {
  1404. assert(x->nw <= mc->rw);
  1405. assert(y->nw <= mc->rw);
  1406. { // WINSCP
  1407. mp_int scratch = *mc->scratch;
  1408. mp_int tmp = mp_alloc_from_scratch(&scratch, 2*mc->rw);
  1409. mp_mul_into(&tmp, x, y);
  1410. { // WINSCP
  1411. mp_int reduced = monty_reduce_internal(mc, &tmp, scratch);
  1412. mp_copy_into(r, &reduced);
  1413. mp_clear(mc->scratch);
  1414. } // WINSCP
  1415. } // WINSCP
  1416. }
  1417. mp_int *monty_mul(MontyContext *mc, mp_int *x, mp_int *y)
  1418. {
  1419. mp_int *toret = mp_make_sized(mc->rw);
  1420. monty_mul_into(mc, toret, x, y);
  1421. return toret;
  1422. }
  1423. mp_int *monty_modulus(MontyContext *mc)
  1424. {
  1425. return mc->m;
  1426. }
  1427. mp_int *monty_identity(MontyContext *mc)
  1428. {
  1429. return mc->powers_of_r_mod_m[0];
  1430. }
  1431. mp_int *monty_invert(MontyContext *mc, mp_int *x)
  1432. {
  1433. /* Given xr, we want to return x^{-1}r = (xr)^{-1} r^2 =
  1434. * monty_reduce((xr)^{-1} r^3) */
  1435. mp_int *tmp = mp_invert(x, mc->m);
  1436. mp_int *toret = monty_mul(mc, tmp, mc->powers_of_r_mod_m[2]);
  1437. mp_free(tmp);
  1438. return toret;
  1439. }
  1440. /*
  1441. * Importing a number into Montgomery representation involves
  1442. * multiplying it by r and reducing mod m. We use the general-purpose
  1443. * mp_modmul for this, in case the input number is out of range.
  1444. */
  1445. mp_int *monty_import(MontyContext *mc, mp_int *x)
  1446. {
  1447. return mp_modmul(x, mc->powers_of_r_mod_m[0], mc->m);
  1448. }
  1449. void monty_import_into(MontyContext *mc, mp_int *r, mp_int *x)
  1450. {
  1451. mp_int *imported = monty_import(mc, x);
  1452. mp_copy_into(r, imported);
  1453. mp_free(imported);
  1454. }
  1455. /*
  1456. * Exporting a number means multiplying it by r^{-1}, which is exactly
  1457. * what monty_reduce does anyway, so we just do that.
  1458. */
  1459. void monty_export_into(MontyContext *mc, mp_int *r, mp_int *x)
  1460. {
  1461. pinitassert(x->nw <= 2*mc->rw);
  1462. mp_int reduced = monty_reduce_internal(mc, x, *mc->scratch);
  1463. mp_copy_into(r, &reduced);
  1464. mp_clear(mc->scratch);
  1465. }
  1466. mp_int *monty_export(MontyContext *mc, mp_int *x)
  1467. {
  1468. mp_int *toret = mp_make_sized(mc->rw);
  1469. monty_export_into(mc, toret, x);
  1470. return toret;
  1471. }
  1472. #define MODPOW_LOG2_WINDOW_SIZE 5
  1473. #define MODPOW_WINDOW_SIZE (1 << MODPOW_LOG2_WINDOW_SIZE)
  1474. mp_int *monty_pow(MontyContext *mc, mp_int *base, mp_int *exponent)
  1475. {
  1476. /*
  1477. * Modular exponentiation is done from the top down, using a
  1478. * fixed-window technique.
  1479. *
  1480. * We have a table storing every power of the base from base^0 up
  1481. * to base^{w-1}, where w is a small power of 2, say 2^k. (k is
  1482. * defined above as MODPOW_LOG2_WINDOW_SIZE, and w = 2^k is
  1483. * defined as MODPOW_WINDOW_SIZE.)
  1484. *
  1485. * We break the exponent up into k-bit chunks, from the bottom up,
  1486. * that is
  1487. *
  1488. * exponent = c_0 + 2^k c_1 + 2^{2k} c_2 + ... + 2^{nk} c_n
  1489. *
  1490. * and we compute base^exponent by computing in turn
  1491. *
  1492. * base^{c_n}
  1493. * base^{2^k c_n + c_{n-1}}
  1494. * base^{2^{2k} c_n + 2^k c_{n-1} + c_{n-2}}
  1495. * ...
  1496. *
  1497. * where each line is obtained by raising the previous line to the
  1498. * power 2^k (i.e. squaring it k times) and then multiplying in
  1499. * a value base^{c_i}, which we can look up in our table.
  1500. *
  1501. * Side-channel considerations: the exponent is secret, so
  1502. * actually doing a single table lookup by using a chunk of
  1503. * exponent bits as an array index would be an obvious leak of
  1504. * secret information into the cache. So instead, in each
  1505. * iteration, we read _all_ the table entries, and do a sequence
  1506. * of mp_select operations to leave just the one we wanted in the
  1507. * variable that will go into the multiplication. In other
  1508. * contexts (like software AES) that technique is so prohibitively
  1509. * slow that it makes you choose a strategy that doesn't use table
  1510. * lookups at all (we do bitslicing in preference); but here, this
  1511. * iteration through 2^k table elements is replacing k-1 bignum
  1512. * _multiplications_ that you'd have to use instead if you did
  1513. * simple square-and-multiply, and that makes it still a win.
  1514. */
  1515. /* Table that holds base^0, ..., base^{w-1} */
  1516. mp_int *table[MODPOW_WINDOW_SIZE];
  1517. table[0] = mp_copy(monty_identity(mc));
  1518. { // WINSCP
  1519. size_t i;
  1520. for (i = 1; i < MODPOW_WINDOW_SIZE; i++)
  1521. table[i] = monty_mul(mc, table[i-1], base);
  1522. /* out accumulates the output value */
  1523. { // WINSCP
  1524. mp_int *out = mp_make_sized(mc->rw);
  1525. mp_copy_into(out, monty_identity(mc));
  1526. /* table_entry will hold each value we get out of the table */
  1527. { // WINSCP
  1528. mp_int *table_entry = mp_make_sized(mc->rw);
  1529. /* Bit index of the chunk of bits we're working on. Start with the
  1530. * highest multiple of k strictly less than the size of our
  1531. * bignum, i.e. the highest-index chunk of bits that might
  1532. * conceivably contain any nonzero bit. */
  1533. { // WINSCP
  1534. size_t i = (exponent->nw * BIGNUM_INT_BITS) - 1;
  1535. i -= i % MODPOW_LOG2_WINDOW_SIZE;
  1536. { // WINSCP
  1537. bool first_iteration = true;
  1538. while (true) {
  1539. /* Construct the table index */
  1540. unsigned table_index = 0;
  1541. { // WINSCP
  1542. size_t j;
  1543. for (j = 0; j < MODPOW_LOG2_WINDOW_SIZE; j++)
  1544. table_index |= mp_get_bit(exponent, i+j) << j;
  1545. /* Iterate through the table to do a side-channel-safe lookup,
  1546. * ending up with table_entry = table[table_index] */
  1547. mp_copy_into(table_entry, table[0]);
  1548. { // WINSCP
  1549. size_t j;
  1550. for (j = 1; j < MODPOW_WINDOW_SIZE; j++) {
  1551. unsigned not_this_one =
  1552. ((table_index ^ j) + MODPOW_WINDOW_SIZE - 1)
  1553. >> MODPOW_LOG2_WINDOW_SIZE;
  1554. mp_select_into(table_entry, table[j], table_entry, not_this_one);
  1555. }
  1556. if (!first_iteration) {
  1557. /* Multiply into the output */
  1558. monty_mul_into(mc, out, out, table_entry);
  1559. } else {
  1560. /* On the first iteration, we can save one multiplication
  1561. * by just copying */
  1562. mp_copy_into(out, table_entry);
  1563. first_iteration = false;
  1564. }
  1565. /* If that was the bottommost chunk of bits, we're done */
  1566. if (i == 0)
  1567. break;
  1568. /* Otherwise, square k times and go round again. */
  1569. { // WINSCP
  1570. size_t j;
  1571. for (j = 0; j < MODPOW_LOG2_WINDOW_SIZE; j++)
  1572. monty_mul_into(mc, out, out, out);
  1573. i-= MODPOW_LOG2_WINDOW_SIZE;
  1574. } // WINSCP
  1575. } // WINSCP
  1576. } // WINSCP
  1577. }
  1578. { // WINSCP
  1579. size_t i;
  1580. for (i = 0; i < MODPOW_WINDOW_SIZE; i++)
  1581. mp_free(table[i]);
  1582. mp_free(table_entry);
  1583. mp_clear(mc->scratch);
  1584. return out;
  1585. } // WINSCP
  1586. } // WINSCP
  1587. } // WINSCP
  1588. } // WINSCP
  1589. } // WINSCP
  1590. } // WINSCP
  1591. }
  1592. mp_int *mp_modpow(mp_int *base, mp_int *exponent, mp_int *modulus)
  1593. {
  1594. assert(modulus->nw > 0);
  1595. assert(modulus->w[0] & 1);
  1596. { // WINSCP
  1597. MontyContext *mc = monty_new(modulus);
  1598. mp_int *m_base = monty_import(mc, base);
  1599. mp_int *m_out = monty_pow(mc, m_base, exponent);
  1600. mp_int *out = monty_export(mc, m_out);
  1601. mp_free(m_base);
  1602. mp_free(m_out);
  1603. monty_free(mc);
  1604. return out;
  1605. } // WINSCP
  1606. }
  1607. /*
  1608. * Given two input integers a,b which are not both even, computes d =
  1609. * gcd(a,b) and also two integers A,B such that A*a - B*b = d. A,B
  1610. * will be the minimal non-negative pair satisfying that criterion,
  1611. * which is equivalent to saying that 0 <= A < b/d and 0 <= B < a/d.
  1612. *
  1613. * This algorithm is an adapted form of Stein's algorithm, which
  1614. * computes gcd(a,b) using only addition and bit shifts (i.e. without
  1615. * needing general division), using the following rules:
  1616. *
  1617. * - if both of a,b are even, divide off a common factor of 2
  1618. * - if one of a,b (WLOG a) is even, then gcd(a,b) = gcd(a/2,b), so
  1619. * just divide a by 2
  1620. * - if both of a,b are odd, then WLOG a>b, and gcd(a,b) =
  1621. * gcd(b,(a-b)/2).
  1622. *
  1623. * Sometimes this function is used for modular inversion, in which
  1624. * case we already know we expect the two inputs to be coprime, so to
  1625. * save time the 'both even' initial case is assumed not to arise (or
  1626. * to have been handled already by the caller). So this function just
  1627. * performs a sequence of reductions in the following form:
  1628. *
  1629. * - if a,b are both odd, sort them so that a > b, and replace a with
  1630. * b-a; otherwise sort them so that a is the even one
  1631. * - either way, now a is even and b is odd, so divide a by 2.
  1632. *
  1633. * The big change to Stein's algorithm is that we need the Bezout
  1634. * coefficients as output, not just the gcd. So we need to know how to
  1635. * generate those in each case, based on the coefficients from the
  1636. * reduced pair of numbers:
  1637. *
  1638. * - If a is even, and u,v are such that u*(a/2) + v*b = d:
  1639. * + if u is also even, then this is just (u/2)*a + v*b = d
  1640. * + otherwise, (u+b)*(a/2) + (v-a/2)*b is also equal to d, and
  1641. * since u and b are both odd, (u+b)/2 is an integer, so we have
  1642. * ((u+b)/2)*a + (v-a/2)*b = d.
  1643. *
  1644. * - If a,b are both odd, and u,v are such that u*b + v*(a-b) = d,
  1645. * then v*a + (u-v)*b = d.
  1646. *
  1647. * In the case where we passed from (a,b) to (b,(a-b)/2), we regard it
  1648. * as having first subtracted b from a and then halved a, so both of
  1649. * these transformations must be done in sequence.
  1650. *
  1651. * The code below transforms this from a recursive to an iterative
  1652. * algorithm. We first reduce a,b to 0,1, recording at each stage
  1653. * whether we did the initial subtraction, and whether we had to swap
  1654. * the two values; then we iterate backwards over that record of what
  1655. * we did, applying the above rules for building up the Bezout
  1656. * coefficients as we go. Of course, all the case analysis is done by
  1657. * the usual bit-twiddling conditionalisation to avoid data-dependent
  1658. * control flow.
  1659. *
  1660. * Also, since these mp_ints are generally treated as unsigned, we
  1661. * store the coefficients by absolute value, with the semantics that
  1662. * they always have opposite sign, and in the unwinding loop we keep a
  1663. * bit indicating whether Aa-Bb is currently expected to be +d or -d,
  1664. * so that we can do one final conditional adjustment if it's -d.
  1665. *
  1666. * Once the reduction rules have managed to reduce the input numbers
  1667. * to (0,d), then they are stable (the next reduction will always
  1668. * divide the even one by 2, which maps 0 to 0). So it doesn't matter
  1669. * if we do more steps of the algorithm than necessary; hence, for
  1670. * constant time, we just need to find the maximum number we could
  1671. * _possibly_ require, and do that many.
  1672. *
  1673. * If a,b < 2^n, at most 2n iterations are required. Proof: consider
  1674. * the quantity Q = log_2(a) + log_2(b). Every step halves one of the
  1675. * numbers (and may also reduce one of them further by doing a
  1676. * subtraction beforehand, but in the worst case, not by much or not
  1677. * at all). So Q reduces by at least 1 per iteration, and it starts
  1678. * off with a value at most 2n.
  1679. *
  1680. * The worst case inputs (I think) are where x=2^{n-1} and y=2^n-1
  1681. * (i.e. x is a power of 2 and y is all 1s). In that situation, the
  1682. * first n-1 steps repeatedly halve x until it's 1, and then there are
  1683. * n further steps each of which subtracts 1 from y and halves it.
  1684. */
  1685. static void mp_bezout_into(mp_int *a_coeff_out, mp_int *b_coeff_out,
  1686. mp_int *gcd_out, mp_int *a_in, mp_int *b_in)
  1687. {
  1688. size_t nw = size_t_max(1, size_t_max(a_in->nw, b_in->nw));
  1689. /* Make mutable copies of the input numbers */
  1690. mp_int *a = mp_make_sized(nw), *b = mp_make_sized(nw);
  1691. mp_copy_into(a, a_in);
  1692. mp_copy_into(b, b_in);
  1693. /* Space to build up the output coefficients, with an extra word
  1694. * so that intermediate values can overflow off the top and still
  1695. * right-shift back down to the correct value */
  1696. { // WINSCP
  1697. mp_int *ac = mp_make_sized(nw + 1), *bc = mp_make_sized(nw + 1);
  1698. /* And a general-purpose temp register */
  1699. mp_int *tmp = mp_make_sized(nw);
  1700. /* Space to record the sequence of reduction steps to unwind. We
  1701. * make it a BignumInt for no particular reason except that (a)
  1702. * mp_make_sized conveniently zeroes the allocation and mp_free
  1703. * wipes it, and (b) this way I can use mp_dump() if I have to
  1704. * debug this code. */
  1705. size_t steps = 2 * nw * BIGNUM_INT_BITS;
  1706. mp_int *record = mp_make_sized(
  1707. (steps*2 + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
  1708. size_t step; // WINSCP
  1709. for (step = 0; step < steps; step++) {
  1710. /*
  1711. * If a and b are both odd, we want to sort them so that a is
  1712. * larger. But if one is even, we want to sort them so that a
  1713. * is the even one.
  1714. */
  1715. unsigned swap_if_both_odd = mp_cmp_hs(b, a);
  1716. unsigned swap_if_one_even = a->w[0] & 1;
  1717. unsigned both_odd = a->w[0] & b->w[0] & 1;
  1718. unsigned swap = swap_if_one_even ^ (
  1719. (swap_if_both_odd ^ swap_if_one_even) & both_odd);
  1720. mp_cond_swap(a, b, swap);
  1721. /*
  1722. * If a,b are both odd, then a is the larger number, so
  1723. * subtract the smaller one from it.
  1724. */
  1725. mp_cond_sub_into(a, a, b, both_odd);
  1726. /*
  1727. * Now a is even, so divide it by two.
  1728. */
  1729. mp_rshift_fixed_into(a, a, 1);
  1730. /*
  1731. * Record the two 1-bit values both_odd and swap.
  1732. */
  1733. mp_set_bit(record, step*2, both_odd);
  1734. mp_set_bit(record, step*2+1, swap);
  1735. }
  1736. /*
  1737. * Now we expect to have reduced the two numbers to 0 and d,
  1738. * although we don't know which way round. (But we avoid checking
  1739. * this by assertion; sometimes we'll need to do this computation
  1740. * without giving away that we already know the inputs were bogus.
  1741. * So we'd prefer to just press on and return nonsense.)
  1742. */
  1743. if (gcd_out) {
  1744. /*
  1745. * At this point we can return the actual gcd. Since one of
  1746. * a,b is it and the other is zero, the easiest way to get it
  1747. * is to add them together.
  1748. */
  1749. mp_add_into(gcd_out, a, b);
  1750. }
  1751. /*
  1752. * If the caller _only_ wanted the gcd, and neither Bezout
  1753. * coefficient is even required, we can skip the entire unwind
  1754. * stage.
  1755. */
  1756. if (a_coeff_out || b_coeff_out) {
  1757. /*
  1758. * The Bezout coefficients of a,b at this point are simply 0
  1759. * for whichever of a,b is zero, and 1 for whichever is
  1760. * nonzero. The nonzero number equals gcd(a,b), which by
  1761. * assumption is odd, so we can do this by just taking the low
  1762. * bit of each one.
  1763. */
  1764. ac->w[0] = mp_get_bit(a, 0);
  1765. bc->w[0] = mp_get_bit(b, 0);
  1766. /*
  1767. * Overwrite a,b themselves with those same numbers. This has
  1768. * the effect of dividing both of them by d, which will
  1769. * arrange that during the unwind stage we generate the
  1770. * minimal coefficients instead of a larger pair.
  1771. */
  1772. mp_copy_into(a, ac);
  1773. mp_copy_into(b, bc);
  1774. /*
  1775. * We'll maintain the invariant as we unwind that ac * a - bc
  1776. * * b is either +d or -d (or rather, +1/-1 after scaling by
  1777. * d), and we'll remember which. (We _could_ keep it at +d the
  1778. * whole time, but it would cost more work every time round
  1779. * the loop, so it's cheaper to fix that up once at the end.)
  1780. *
  1781. * Initially, the result is +d if a was the nonzero value after
  1782. * reduction, and -d if b was.
  1783. */
  1784. { // WINSCP
  1785. unsigned minus_d = b->w[0];
  1786. size_t step; // WINSCP
  1787. for (step = steps; step-- > 0 ;) {
  1788. /*
  1789. * Recover the data from the step we're unwinding.
  1790. */
  1791. unsigned both_odd = mp_get_bit(record, step*2);
  1792. unsigned swap = mp_get_bit(record, step*2+1);
  1793. /*
  1794. * Unwind the division: if our coefficient of a is odd, we
  1795. * adjust the coefficients by +b and +a respectively.
  1796. */
  1797. unsigned adjust = ac->w[0] & 1;
  1798. mp_cond_add_into(ac, ac, b, adjust);
  1799. mp_cond_add_into(bc, bc, a, adjust);
  1800. /*
  1801. * Now ac is definitely even, so we divide it by two.
  1802. */
  1803. mp_rshift_fixed_into(ac, ac, 1);
  1804. /*
  1805. * Now unwind the subtraction, if there was one, by adding
  1806. * ac to bc.
  1807. */
  1808. mp_cond_add_into(bc, bc, ac, both_odd);
  1809. /*
  1810. * Undo the transformation of the input numbers, by
  1811. * multiplying a by 2 and then adding b to a (the latter
  1812. * only if both_odd).
  1813. */
  1814. mp_lshift_fixed_into(a, a, 1);
  1815. mp_cond_add_into(a, a, b, both_odd);
  1816. /*
  1817. * Finally, undo the swap. If we do swap, this also
  1818. * reverses the sign of the current result ac*a+bc*b.
  1819. */
  1820. mp_cond_swap(a, b, swap);
  1821. mp_cond_swap(ac, bc, swap);
  1822. minus_d ^= swap;
  1823. }
  1824. /*
  1825. * Now we expect to have recovered the input a,b (or rather,
  1826. * the versions of them divided by d). But we might find that
  1827. * our current result is -d instead of +d, that is, we have
  1828. * A',B' such that A'a - B'b = -d.
  1829. *
  1830. * In that situation, we set A = b-A' and B = a-B', giving us
  1831. * Aa-Bb = ab - A'a - ab + B'b = +1.
  1832. */
  1833. mp_sub_into(tmp, b, ac);
  1834. mp_select_into(ac, ac, tmp, minus_d);
  1835. mp_sub_into(tmp, a, bc);
  1836. mp_select_into(bc, bc, tmp, minus_d);
  1837. /*
  1838. * Now we really are done. Return the outputs.
  1839. */
  1840. if (a_coeff_out)
  1841. mp_copy_into(a_coeff_out, ac);
  1842. if (b_coeff_out)
  1843. mp_copy_into(b_coeff_out, bc);
  1844. } // WINSCP
  1845. }
  1846. mp_free(a);
  1847. mp_free(b);
  1848. mp_free(ac);
  1849. mp_free(bc);
  1850. mp_free(tmp);
  1851. mp_free(record);
  1852. } // WINSCP
  1853. }
  1854. mp_int *mp_invert(mp_int *x, mp_int *m)
  1855. {
  1856. mp_int *result = mp_make_sized(m->nw);
  1857. mp_bezout_into(result, NULL, NULL, x, m);
  1858. return result;
  1859. }
  1860. void mp_gcd_into(mp_int *a, mp_int *b, mp_int *gcd, mp_int *A, mp_int *B)
  1861. {
  1862. /*
  1863. * Identify shared factors of 2. To do this we OR the two numbers
  1864. * to get something whose lowest set bit is in the right place,
  1865. * remove all higher bits by ANDing it with its own negation, and
  1866. * use mp_get_nbits to find the location of the single remaining
  1867. * set bit.
  1868. */
  1869. mp_int *tmp = mp_make_sized(size_t_max(a->nw, b->nw));
  1870. size_t i; // WINSCP
  1871. for (i = 0; i < tmp->nw; i++)
  1872. tmp->w[i] = mp_word(a, i) | mp_word(b, i);
  1873. { // WINSCP
  1874. BignumCarry carry = 1;
  1875. size_t i;
  1876. for (i = 0; i < tmp->nw; i++) {
  1877. BignumInt negw;
  1878. BignumADC(negw, carry, 0, ~tmp->w[i], carry);
  1879. tmp->w[i] &= negw;
  1880. }
  1881. { // WINSCP
  1882. size_t shift = mp_get_nbits(tmp) - 1;
  1883. mp_free(tmp);
  1884. /*
  1885. * Make copies of a,b with those shared factors of 2 divided off,
  1886. * so that at least one is odd (which is the precondition for
  1887. * mp_bezout_into). Compute the gcd of those.
  1888. */
  1889. { // WINSCP
  1890. mp_int *as = mp_rshift_safe(a, shift);
  1891. mp_int *bs = mp_rshift_safe(b, shift);
  1892. mp_bezout_into(A, B, gcd, as, bs);
  1893. mp_free(as);
  1894. mp_free(bs);
  1895. /*
  1896. * And finally shift the gcd back up (unless the caller didn't
  1897. * even ask for it), to put the shared factors of 2 back in.
  1898. */
  1899. if (gcd)
  1900. mp_lshift_safe_in_place(gcd, shift);
  1901. } // WINSCP
  1902. } // WINSCP
  1903. } // WINSCP
  1904. }
  1905. mp_int *mp_gcd(mp_int *a, mp_int *b)
  1906. {
  1907. mp_int *gcd = mp_make_sized(size_t_min(a->nw, b->nw));
  1908. mp_gcd_into(a, b, gcd, NULL, NULL);
  1909. return gcd;
  1910. }
  1911. unsigned mp_coprime(mp_int *a, mp_int *b)
  1912. {
  1913. mp_int *gcd = mp_gcd(a, b);
  1914. unsigned toret = mp_eq_integer(gcd, 1);
  1915. mp_free(gcd);
  1916. return toret;
  1917. }
  1918. static uint32_t recip_approx_32(uint32_t x)
  1919. {
  1920. /*
  1921. * Given an input x in [2^31,2^32), i.e. a uint32_t with its high
  1922. * bit set, this function returns an approximation to 2^63/x,
  1923. * computed using only multiplications and bit shifts just in case
  1924. * the C divide operator has non-constant time (either because the
  1925. * underlying machine instruction does, or because the operator
  1926. * expands to a library function on a CPU without hardware
  1927. * division).
  1928. *
  1929. * The coefficients are derived from those of the degree-9
  1930. * polynomial which is the minimax-optimal approximation to that
  1931. * function on the given interval (generated using the Remez
  1932. * algorithm), converted into integer arithmetic with shifts used
  1933. * to maximise the number of significant bits at every state. (A
  1934. * sort of 'static floating point' - the exponent is statically
  1935. * known at every point in the code, so it never needs to be
  1936. * stored at run time or to influence runtime decisions.)
  1937. *
  1938. * Exhaustive iteration over the whole input space shows the
  1939. * largest possible error to be 1686.54. (The input value
  1940. * attaining that bound is 4226800006 == 0xfbefd986, whose true
  1941. * reciprocal is 2182116973.540... == 0x8210766d.8a6..., whereas
  1942. * this function returns 2182115287 == 0x82106fd7.)
  1943. */
  1944. uint64_t r = 0x92db03d6ULL;
  1945. r = 0xf63e71eaULL - ((r*x) >> 34);
  1946. r = 0xb63721e8ULL - ((r*x) >> 34);
  1947. r = 0x9c2da00eULL - ((r*x) >> 33);
  1948. r = 0xaada0bb8ULL - ((r*x) >> 32);
  1949. r = 0xf75cd403ULL - ((r*x) >> 31);
  1950. r = 0xecf97a41ULL - ((r*x) >> 31);
  1951. r = 0x90d876cdULL - ((r*x) >> 31);
  1952. r = 0x6682799a0ULL - ((r*x) >> 26);
  1953. return r;
  1954. }
  1955. void mp_divmod_into(mp_int *n, mp_int *d, mp_int *q_out, mp_int *r_out)
  1956. {
  1957. pinitassert(!mp_eq_integer(d, 0));
  1958. /*
  1959. * We do division by using Newton-Raphson iteration to converge to
  1960. * the reciprocal of d (or rather, R/d for R a sufficiently large
  1961. * power of 2); then we multiply that reciprocal by n; and we
  1962. * finish up with conditional subtraction.
  1963. *
  1964. * But we have to do it in a fixed number of N-R iterations, so we
  1965. * need some error analysis to know how many we might need.
  1966. *
  1967. * The iteration is derived by defining f(r) = d - R/r.
  1968. * Differentiating gives f'(r) = R/r^2, and the Newton-Raphson
  1969. * formula applied to those functions gives
  1970. *
  1971. * r_{i+1} = r_i - f(r_i) / f'(r_i)
  1972. * = r_i - (d - R/r_i) r_i^2 / R
  1973. * = r_i (2 R - d r_i) / R
  1974. *
  1975. * Now let e_i be the error in a given iteration, in the sense
  1976. * that
  1977. *
  1978. * d r_i = R + e_i
  1979. * i.e. e_i/R = (r_i - r_true) / r_true
  1980. *
  1981. * so e_i is the _relative_ error in r_i.
  1982. *
  1983. * We must also introduce a rounding-error term, because the
  1984. * division by R always gives an integer. This might make the
  1985. * output off by up to 1 (in the negative direction, because
  1986. * right-shifting gives floor of the true quotient). So when we
  1987. * divide by R, we must imagine adding some f in [0,1). Then we
  1988. * have
  1989. *
  1990. * d r_{i+1} = d r_i (2 R - d r_i) / R - d f
  1991. * = (R + e_i) (R - e_i) / R - d f
  1992. * = (R^2 - e_i^2) / R - d f
  1993. * = R - (e_i^2 / R + d f)
  1994. * => e_{i+1} = - (e_i^2 / R + d f)
  1995. *
  1996. * The sum of two positive quantities is bounded above by twice
  1997. * their max, and max |f| = 1, so we can bound this as follows:
  1998. *
  1999. * |e_{i+1}| <= 2 max (e_i^2/R, d)
  2000. * |e_{i+1}/R| <= 2 max ((e_i/R)^2, d/R)
  2001. * log2 |R/e_{i+1}| <= min (2 log2 |R/e_i|, log2 |R/d|) - 1
  2002. *
  2003. * which tells us that the number of 'good' bits - i.e.
  2004. * log2(R/e_i) - very nearly doubles at every iteration (apart
  2005. * from that subtraction of 1), until it gets to the same size as
  2006. * log2(R/d). In other words, the size of R in bits has to be the
  2007. * size of denominator we're putting in, _plus_ the amount of
  2008. * precision we want to get back out.
  2009. *
  2010. * So when we multiply n (the input numerator) by our final
  2011. * reciprocal approximation r, but actually r differs from R/d by
  2012. * up to 2, then it follows that
  2013. *
  2014. * n/d - nr/R = n/d - [ n (R/d + e) ] / R
  2015. * = n/d - [ (n/d) R + n e ] / R
  2016. * = -ne/R
  2017. * => 0 <= n/d - nr/R < 2n/R
  2018. *
  2019. * so our computed quotient can differ from the true n/d by up to
  2020. * 2n/R. Hence, as long as we also choose R large enough that 2n/R
  2021. * is bounded above by a constant, we can guarantee a bounded
  2022. * number of final conditional-subtraction steps.
  2023. */
  2024. /*
  2025. * Get at least 32 of the most significant bits of the input
  2026. * number.
  2027. */
  2028. size_t hiword_index = 0;
  2029. uint64_t hibits = 0, lobits = 0;
  2030. mp_find_highest_nonzero_word_pair(d, 64 - BIGNUM_INT_BITS,
  2031. &hiword_index, &hibits, &lobits);
  2032. /*
  2033. * Make a shifted combination of those two words which puts the
  2034. * topmost bit of the number at bit 63.
  2035. */
  2036. { // WINSCP
  2037. size_t shift_up = 0;
  2038. size_t i; // WINSCP
  2039. for (i = BIGNUM_INT_BITS_BITS; i-- > 0;) {
  2040. size_t sl = (size_t)1 << i; /* left shift count */
  2041. size_t sr = 64 - sl; /* complementary right-shift count */
  2042. /* Should we shift up? */
  2043. unsigned indicator = 1 ^ normalise_to_1_u64(hibits >> sr);
  2044. /* If we do, what will we get? */
  2045. uint64_t new_hibits = (hibits << sl) | (lobits >> sr);
  2046. uint64_t new_lobits = lobits << sl;
  2047. size_t new_shift_up = shift_up + sl;
  2048. /* Conditionally swap those values in. */
  2049. hibits ^= (hibits ^ new_hibits ) & -(uint64_t)indicator;
  2050. lobits ^= (lobits ^ new_lobits ) & -(uint64_t)indicator;
  2051. shift_up ^= (shift_up ^ new_shift_up ) & -(size_t) indicator;
  2052. }
  2053. /*
  2054. * So now we know the most significant 32 bits of d are at the top
  2055. * of hibits. Approximate the reciprocal of those bits.
  2056. */
  2057. lobits = (uint64_t)recip_approx_32(hibits >> 32) << 32;
  2058. hibits = 0;
  2059. /*
  2060. * And shift that up by as many bits as the input was shifted up
  2061. * just now, so that the product of this approximation and the
  2062. * actual input will be close to a fixed power of two regardless
  2063. * of where the MSB was.
  2064. *
  2065. * I do this in another log n individual passes, partly in case
  2066. * the CPU's register-controlled shift operation isn't
  2067. * time-constant, and also in case the compiler code-generates
  2068. * uint64_t shifts out of a variable number of smaller-word shift
  2069. * instructions, e.g. by splitting up into cases.
  2070. */
  2071. for (i = BIGNUM_INT_BITS_BITS; i-- > 0;) {
  2072. size_t sl = (size_t)1 << i; /* left shift count */
  2073. size_t sr = 64 - sl; /* complementary right-shift count */
  2074. /* Should we shift up? */
  2075. unsigned indicator = 1 & (shift_up >> i);
  2076. /* If we do, what will we get? */
  2077. uint64_t new_hibits = (hibits << sl) | (lobits >> sr);
  2078. uint64_t new_lobits = lobits << sl;
  2079. /* Conditionally swap those values in. */
  2080. hibits ^= (hibits ^ new_hibits ) & -(uint64_t)indicator;
  2081. lobits ^= (lobits ^ new_lobits ) & -(uint64_t)indicator;
  2082. }
  2083. /*
  2084. * The product of the 128-bit value now in hibits:lobits with the
  2085. * 128-bit value we originally retrieved in the same variables
  2086. * will be in the vicinity of 2^191. So we'll take log2(R) to be
  2087. * 191, plus a multiple of BIGNUM_INT_BITS large enough to allow R
  2088. * to hold the combined sizes of n and d.
  2089. */
  2090. { // WINSCP
  2091. size_t log2_R;
  2092. {
  2093. size_t max_log2_n = (n->nw + d->nw) * BIGNUM_INT_BITS;
  2094. log2_R = max_log2_n + 3;
  2095. log2_R -= size_t_min(191, log2_R);
  2096. log2_R = (log2_R + BIGNUM_INT_BITS - 1) & ~(BIGNUM_INT_BITS - 1);
  2097. log2_R += 191;
  2098. }
  2099. /* Number of words in a bignum capable of holding numbers the size
  2100. * of twice R. */
  2101. { // WINSCP
  2102. size_t rw = ((log2_R+2) + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS;
  2103. /*
  2104. * Now construct our full-sized starting reciprocal approximation.
  2105. */
  2106. mp_int *r_approx = mp_make_sized(rw);
  2107. size_t output_bit_index;
  2108. {
  2109. /* Where in the input number did the input 128-bit value come from? */
  2110. size_t input_bit_index =
  2111. (hiword_index * BIGNUM_INT_BITS) - (128 - BIGNUM_INT_BITS);
  2112. /* So how far do we need to shift our 64-bit output, if the
  2113. * product of those two fixed-size values is 2^191 and we want
  2114. * to make it 2^log2_R instead? */
  2115. output_bit_index = log2_R - 191 - input_bit_index;
  2116. /* If we've done all that right, it should be a whole number
  2117. * of words. */
  2118. assert(output_bit_index % BIGNUM_INT_BITS == 0);
  2119. { // WINSCP
  2120. size_t output_word_index = output_bit_index / BIGNUM_INT_BITS;
  2121. mp_add_integer_into_shifted_by_words(
  2122. r_approx, r_approx, lobits, output_word_index);
  2123. mp_add_integer_into_shifted_by_words(
  2124. r_approx, r_approx, hibits,
  2125. output_word_index + 64 / BIGNUM_INT_BITS);
  2126. } // WINSCP
  2127. }
  2128. /*
  2129. * Make the constant 2*R, which we'll need in the iteration.
  2130. */
  2131. { // WINSCP
  2132. mp_int *two_R = mp_make_sized(rw);
  2133. BignumInt top_word = (BignumInt)1 << ((log2_R+1) % BIGNUM_INT_BITS);
  2134. mp_add_integer_into_shifted_by_words(
  2135. two_R, two_R, top_word, (log2_R+1) / BIGNUM_INT_BITS);
  2136. /*
  2137. * Scratch space.
  2138. */
  2139. { // WINSCP
  2140. mp_int *dr = mp_make_sized(rw + d->nw);
  2141. mp_int *diff = mp_make_sized(size_t_max(rw, dr->nw));
  2142. mp_int *product = mp_make_sized(rw + diff->nw);
  2143. size_t scratchsize = size_t_max(
  2144. mp_mul_scratchspace(dr->nw, r_approx->nw, d->nw),
  2145. mp_mul_scratchspace(product->nw, r_approx->nw, diff->nw));
  2146. mp_int *scratch = mp_make_sized(scratchsize);
  2147. mp_int product_shifted = mp_make_alias(
  2148. product, log2_R / BIGNUM_INT_BITS, product->nw);
  2149. /*
  2150. * Initial error estimate: the 32-bit output of recip_approx_32
  2151. * differs by less than 2048 (== 2^11) from the true top 32 bits
  2152. * of the reciprocal, so the relative error is at most 2^11
  2153. * divided by the 32-bit reciprocal, which at worst is 2^11/2^31 =
  2154. * 2^-20. So even in the worst case, we have 20 good bits of
  2155. * reciprocal to start with.
  2156. */
  2157. size_t good_bits = 31 - 11;
  2158. size_t good_bits_needed = BIGNUM_INT_BITS * n->nw + 4; /* add a few */
  2159. /*
  2160. * Now do Newton-Raphson iterations until we have reason to think
  2161. * they're not converging any more.
  2162. */
  2163. while (good_bits < good_bits_needed) {
  2164. /*
  2165. * Compute the next iterate.
  2166. */
  2167. mp_mul_internal(dr, r_approx, d, *scratch);
  2168. mp_sub_into(diff, two_R, dr);
  2169. mp_mul_internal(product, r_approx, diff, *scratch);
  2170. mp_rshift_fixed_into(r_approx, &product_shifted,
  2171. log2_R % BIGNUM_INT_BITS);
  2172. /*
  2173. * Adjust the error estimate.
  2174. */
  2175. good_bits = good_bits * 2 - 1;
  2176. }
  2177. mp_free(dr);
  2178. mp_free(diff);
  2179. mp_free(product);
  2180. mp_free(scratch);
  2181. /*
  2182. * Now we've got our reciprocal, we can compute the quotient, by
  2183. * multiplying in n and then shifting down by log2_R bits.
  2184. */
  2185. { // WINSCP
  2186. mp_int *quotient_full = mp_mul(r_approx, n);
  2187. mp_int quotient_alias = mp_make_alias(
  2188. quotient_full, log2_R / BIGNUM_INT_BITS, quotient_full->nw);
  2189. mp_int *quotient = mp_make_sized(n->nw);
  2190. mp_rshift_fixed_into(quotient, &quotient_alias, log2_R % BIGNUM_INT_BITS);
  2191. /*
  2192. * Next, compute the remainder.
  2193. */
  2194. { // WINSCP
  2195. mp_int *remainder = mp_make_sized(d->nw);
  2196. mp_mul_into(remainder, quotient, d);
  2197. mp_sub_into(remainder, n, remainder);
  2198. /*
  2199. * Finally, two conditional subtractions to fix up any remaining
  2200. * rounding error. (I _think_ one should be enough, but this
  2201. * routine isn't time-critical enough to take chances.)
  2202. */
  2203. { // WINSCP
  2204. unsigned q_correction = 0;
  2205. unsigned iter; // WINSCP
  2206. for (iter = 0; iter < 2; iter++) {
  2207. unsigned need_correction = mp_cmp_hs(remainder, d);
  2208. mp_cond_sub_into(remainder, remainder, d, need_correction);
  2209. q_correction += need_correction;
  2210. }
  2211. mp_add_integer_into(quotient, quotient, q_correction);
  2212. /*
  2213. * Now we should have a perfect answer, i.e. 0 <= r < d.
  2214. */
  2215. assert(!mp_cmp_hs(remainder, d));
  2216. if (q_out)
  2217. mp_copy_into(q_out, quotient);
  2218. if (r_out)
  2219. mp_copy_into(r_out, remainder);
  2220. mp_free(r_approx);
  2221. mp_free(two_R);
  2222. mp_free(quotient_full);
  2223. mp_free(quotient);
  2224. mp_free(remainder);
  2225. } // WINSCP
  2226. } // WINSCP
  2227. } // WINSCP
  2228. } // WINSCP
  2229. } // WINSCP
  2230. } // WINSCP
  2231. } // WINSCP
  2232. } // WINSCP
  2233. }
  2234. mp_int *mp_div(mp_int *n, mp_int *d)
  2235. {
  2236. mp_int *q = mp_make_sized(n->nw);
  2237. mp_divmod_into(n, d, q, NULL);
  2238. return q;
  2239. }
  2240. mp_int *mp_mod(mp_int *n, mp_int *d)
  2241. {
  2242. mp_int *r = mp_make_sized(d->nw);
  2243. mp_divmod_into(n, d, NULL, r);
  2244. return r;
  2245. }
  2246. uint32_t mp_mod_known_integer(mp_int *x, uint32_t m)
  2247. {
  2248. uint64_t reciprocal = ((uint64_t)1 << 48) / m;
  2249. uint64_t accumulator = 0;
  2250. { // WINSCP
  2251. size_t i;
  2252. for (i = mp_max_bytes(x); i-- > 0 ;) {
  2253. accumulator = 0x100 * accumulator + mp_get_byte(x, i);
  2254. /*
  2255. * Let A be the value in 'accumulator' at this point, and let
  2256. * R be the value it will have after we subtract quot*m below.
  2257. *
  2258. * Lemma 1: if A < 2^48, then R < 2m.
  2259. *
  2260. * Proof:
  2261. *
  2262. * By construction, we have 2^48/m - 1 < reciprocal <= 2^48/m.
  2263. * Multiplying that by the accumulator gives
  2264. *
  2265. * A/m * 2^48 - A < unshifted_quot <= A/m * 2^48
  2266. * i.e. 0 <= (A/m * 2^48) - unshifted_quot < A
  2267. * i.e. 0 <= A/m - unshifted_quot/2^48 < A/2^48
  2268. *
  2269. * So when we shift this quotient right by 48 bits, i.e. take
  2270. * the floor of (unshifted_quot/2^48), the value we take the
  2271. * floor of is at most A/2^48 less than the true rational
  2272. * value A/m that we _wanted_ to take the floor of.
  2273. *
  2274. * Provided A < 2^48, this is less than 1. So the quotient
  2275. * 'quot' that we've just produced is either the true quotient
  2276. * floor(A/m), or one less than it. Hence, the output value R
  2277. * is less than 2m. []
  2278. *
  2279. * Lemma 2: if A < 2^16 m, then the multiplication of
  2280. * accumulator*reciprocal does not overflow.
  2281. *
  2282. * Proof: as above, we have reciprocal <= 2^48/m. Multiplying
  2283. * by A gives unshifted_quot <= 2^48 * A / m < 2^48 * 2^16 =
  2284. * 2^64. []
  2285. */
  2286. { // WINSCP
  2287. uint64_t unshifted_quot = accumulator * reciprocal;
  2288. uint64_t quot = unshifted_quot >> 48;
  2289. accumulator -= quot * m;
  2290. } // WINSCP
  2291. }
  2292. /*
  2293. * Theorem 1: accumulator < 2m at the end of every iteration of
  2294. * this loop.
  2295. *
  2296. * Proof: induction on the above loop.
  2297. *
  2298. * Base case: at the start of the first loop iteration, the
  2299. * accumulator is 0, which is certainly < 2m.
  2300. *
  2301. * Inductive step: in each loop iteration, we take a value at most
  2302. * 2m-1, multiply it by 2^8, and add another byte less than 2^8 to
  2303. * generate the input value A to the reduction process above. So
  2304. * we have A < 2m * 2^8 - 1. We know m < 2^32 (because it was
  2305. * passed in as a uint32_t), so A < 2^41, which is enough to allow
  2306. * us to apply Lemma 1, showing that the value of 'accumulator' at
  2307. * the end of the loop is still < 2m. []
  2308. *
  2309. * Corollary: we need at most one final subtraction of m to
  2310. * produce the canonical residue of x mod m, i.e. in the range
  2311. * [0,m).
  2312. *
  2313. * Theorem 2: no multiplication in the inner loop overflows.
  2314. *
  2315. * Proof: in Theorem 1 we established A < 2m * 2^8 - 1 in every
  2316. * iteration. That is less than m * 2^16, so Lemma 2 applies.
  2317. *
  2318. * The other multiplication, of quot * m, cannot overflow because
  2319. * quot is at most A/m, so quot*m <= A < 2^64. []
  2320. */
  2321. { // WINSCP
  2322. uint32_t result = accumulator;
  2323. uint32_t reduced = result - m;
  2324. uint32_t select = -(reduced >> 31);
  2325. result = reduced ^ ((result ^ reduced) & select);
  2326. assert(result < m);
  2327. return result;
  2328. } // WINSCP
  2329. } // WINSCP
  2330. }
  2331. mp_int *mp_nthroot(mp_int *y, unsigned n, mp_int *remainder_out)
  2332. {
  2333. /*
  2334. * Allocate scratch space.
  2335. */
  2336. mp_int **alloc, **powers, **newpowers, *scratch;
  2337. size_t nalloc = 2*(n+1)+1;
  2338. alloc = snewn(nalloc, mp_int *);
  2339. { // WINSCP
  2340. size_t i; // WINSCP
  2341. for (i = 0; i < nalloc; i++)
  2342. alloc[i] = mp_make_sized(y->nw + 1);
  2343. powers = alloc;
  2344. newpowers = alloc + (n+1);
  2345. scratch = alloc[2*n+2];
  2346. /*
  2347. * We're computing the rounded-down nth root of y, i.e. the
  2348. * maximal x such that x^n <= y. We try to add 2^i to it for each
  2349. * possible value of i, starting from the largest one that might
  2350. * fit (i.e. such that 2^{n*i} fits in the size of y) downwards to
  2351. * i=0.
  2352. *
  2353. * We track all the smaller powers of x in the array 'powers'. In
  2354. * each iteration, if we update x, we update all of those values
  2355. * to match.
  2356. */
  2357. mp_copy_integer_into(powers[0], 1);
  2358. { // WINSCP
  2359. size_t s; // WINSCP
  2360. for (s = mp_max_bits(y) / n + 1; s-- > 0 ;) {
  2361. /*
  2362. * Let b = 2^s. We need to compute the powers (x+b)^i for each
  2363. * i, starting from our recorded values of x^i.
  2364. */
  2365. size_t i; // WINSCP
  2366. for (i = 0; i < n+1; i++) {
  2367. /*
  2368. * (x+b)^i = x^i
  2369. * + (i choose 1) x^{i-1} b
  2370. * + (i choose 2) x^{i-2} b^2
  2371. * + ...
  2372. * + b^i
  2373. */
  2374. uint16_t binom = 1; /* coefficient of b^i */
  2375. mp_copy_into(newpowers[i], powers[i]);
  2376. { // WINSCP
  2377. size_t j; // WINSCP
  2378. for (j = 0; j < i; j++) {
  2379. /* newpowers[i] += binom * powers[j] * 2^{(i-j)*s} */
  2380. mp_mul_integer_into(scratch, powers[j], binom);
  2381. mp_lshift_fixed_into(scratch, scratch, (i-j) * s);
  2382. mp_add_into(newpowers[i], newpowers[i], scratch);
  2383. { // WINSCP
  2384. uint32_t binom_mul = binom;
  2385. binom_mul *= (i-j);
  2386. binom_mul /= (j+1);
  2387. assert(binom_mul < 0x10000);
  2388. binom = binom_mul;
  2389. } // WINSCP
  2390. }
  2391. } // WINSCP
  2392. }
  2393. /*
  2394. * Now, is the new value of x^n still <= y? If so, update.
  2395. */
  2396. { // WINSCP
  2397. unsigned newbit = mp_cmp_hs(y, newpowers[n]);
  2398. size_t i; // WINSCP
  2399. for (i = 0; i < n+1; i++)
  2400. mp_select_into(powers[i], powers[i], newpowers[i], newbit);
  2401. } // WINSCP
  2402. }
  2403. if (remainder_out)
  2404. mp_sub_into(remainder_out, y, powers[n]);
  2405. { // WINSCP
  2406. mp_int *root = mp_new(mp_max_bits(y) / n);
  2407. mp_copy_into(root, powers[1]);
  2408. { // WINSCP
  2409. size_t i;
  2410. for (i = 0; i < nalloc; i++)
  2411. mp_free(alloc[i]);
  2412. sfree(alloc);
  2413. return root;
  2414. } // WINSCP
  2415. } // WINSCP
  2416. } // WINSCP
  2417. } // WINSCP
  2418. }
  2419. mp_int *mp_modmul(mp_int *x, mp_int *y, mp_int *modulus)
  2420. {
  2421. mp_int *product = mp_mul(x, y);
  2422. mp_int *reduced = mp_mod(product, modulus);
  2423. mp_free(product);
  2424. return reduced;
  2425. }
  2426. mp_int *mp_modadd(mp_int *x, mp_int *y, mp_int *modulus)
  2427. {
  2428. mp_int *sum = mp_add(x, y);
  2429. mp_int *reduced = mp_mod(sum, modulus);
  2430. mp_free(sum);
  2431. return reduced;
  2432. }
  2433. mp_int *mp_modsub(mp_int *x, mp_int *y, mp_int *modulus)
  2434. {
  2435. mp_int *diff = mp_make_sized(size_t_max(x->nw, y->nw));
  2436. mp_sub_into(diff, x, y);
  2437. { // WINSCP
  2438. unsigned negate = mp_cmp_hs(y, x);
  2439. mp_cond_negate(diff, diff, negate);
  2440. { // WINSCP
  2441. mp_int *residue = mp_mod(diff, modulus);
  2442. mp_cond_negate(residue, residue, negate);
  2443. /* If we've just negated the residue, then it will be < 0 and need
  2444. * the modulus adding to it to make it positive - *except* if the
  2445. * residue was zero when we negated it. */
  2446. { // WINSCP
  2447. unsigned make_positive = negate & ~mp_eq_integer(residue, 0);
  2448. mp_cond_add_into(residue, residue, modulus, make_positive);
  2449. mp_free(diff);
  2450. return residue;
  2451. } // WINSCP
  2452. } // WINSCP
  2453. } // WINSCP
  2454. }
  2455. static mp_int *mp_modadd_in_range(mp_int *x, mp_int *y, mp_int *modulus)
  2456. {
  2457. mp_int *sum = mp_make_sized(modulus->nw);
  2458. unsigned carry = mp_add_into_internal(sum, x, y);
  2459. mp_cond_sub_into(sum, sum, modulus, carry | mp_cmp_hs(sum, modulus));
  2460. return sum;
  2461. }
  2462. static mp_int *mp_modsub_in_range(mp_int *x, mp_int *y, mp_int *modulus)
  2463. {
  2464. mp_int *diff = mp_make_sized(modulus->nw);
  2465. mp_sub_into(diff, x, y);
  2466. mp_cond_add_into(diff, diff, modulus, 1 ^ mp_cmp_hs(x, y));
  2467. return diff;
  2468. }
  2469. mp_int *monty_add(MontyContext *mc, mp_int *x, mp_int *y)
  2470. {
  2471. return mp_modadd_in_range(x, y, mc->m);
  2472. }
  2473. mp_int *monty_sub(MontyContext *mc, mp_int *x, mp_int *y)
  2474. {
  2475. return mp_modsub_in_range(x, y, mc->m);
  2476. }
  2477. void mp_min_into(mp_int *r, mp_int *x, mp_int *y)
  2478. {
  2479. mp_select_into(r, x, y, mp_cmp_hs(x, y));
  2480. }
  2481. void mp_max_into(mp_int *r, mp_int *x, mp_int *y)
  2482. {
  2483. mp_select_into(r, y, x, mp_cmp_hs(x, y));
  2484. }
  2485. mp_int *mp_min(mp_int *x, mp_int *y)
  2486. {
  2487. mp_int *r = mp_make_sized(size_t_min(x->nw, y->nw));
  2488. mp_min_into(r, x, y);
  2489. return r;
  2490. }
  2491. mp_int *mp_max(mp_int *x, mp_int *y)
  2492. {
  2493. mp_int *r = mp_make_sized(size_t_max(x->nw, y->nw));
  2494. mp_max_into(r, x, y);
  2495. return r;
  2496. }
  2497. mp_int *mp_power_2(size_t power)
  2498. {
  2499. mp_int *x = mp_new(power + 1);
  2500. mp_set_bit(x, power, 1);
  2501. return x;
  2502. }
  2503. struct ModsqrtContext {
  2504. mp_int *p; /* the prime */
  2505. MontyContext *mc; /* for doing arithmetic mod p */
  2506. /* Decompose p-1 as 2^e k, for positive integer e and odd k */
  2507. size_t e;
  2508. mp_int *k;
  2509. mp_int *km1o2; /* (k-1)/2 */
  2510. /* The user-provided value z which is not a quadratic residue mod
  2511. * p, and its kth power. Both in Montgomery form. */
  2512. mp_int *z, *zk;
  2513. };
  2514. ModsqrtContext *modsqrt_new(mp_int *p, mp_int *any_nonsquare_mod_p)
  2515. {
  2516. ModsqrtContext *sc = snew(ModsqrtContext);
  2517. memset(sc, 0, sizeof(ModsqrtContext));
  2518. sc->p = mp_copy(p);
  2519. sc->mc = monty_new(sc->p);
  2520. sc->z = monty_import(sc->mc, any_nonsquare_mod_p);
  2521. /* Find the lowest set bit in p-1. Since this routine expects p to
  2522. * be non-secret (typically a well-known standard elliptic curve
  2523. * parameter), for once we don't need clever bit tricks. */
  2524. for (sc->e = 1; sc->e < BIGNUM_INT_BITS * p->nw; sc->e++)
  2525. if (mp_get_bit(p, sc->e))
  2526. break;
  2527. sc->k = mp_rshift_fixed(p, sc->e);
  2528. sc->km1o2 = mp_rshift_fixed(sc->k, 1);
  2529. /* Leave zk to be filled in lazily, since it's more expensive to
  2530. * compute. If this context turns out never to be needed, we can
  2531. * save the bulk of the setup time this way. */
  2532. return sc;
  2533. }
  2534. static void modsqrt_lazy_setup(ModsqrtContext *sc)
  2535. {
  2536. if (!sc->zk)
  2537. sc->zk = monty_pow(sc->mc, sc->z, sc->k);
  2538. }
  2539. void modsqrt_free(ModsqrtContext *sc)
  2540. {
  2541. monty_free(sc->mc);
  2542. mp_free(sc->p);
  2543. mp_free(sc->z);
  2544. mp_free(sc->k);
  2545. mp_free(sc->km1o2);
  2546. if (sc->zk)
  2547. mp_free(sc->zk);
  2548. sfree(sc);
  2549. }
  2550. mp_int *mp_modsqrt(ModsqrtContext *sc, mp_int *x, unsigned *success)
  2551. {
  2552. mp_int *mx = monty_import(sc->mc, x);
  2553. mp_int *mroot = monty_modsqrt(sc, mx, success);
  2554. mp_free(mx);
  2555. { // WINSCP
  2556. mp_int *root = monty_export(sc->mc, mroot);
  2557. mp_free(mroot);
  2558. return root;
  2559. } // WINSCP
  2560. }
  2561. /*
  2562. * Modular square root, using an algorithm more or less similar to
  2563. * Tonelli-Shanks but adapted for constant time.
  2564. *
  2565. * The basic idea is to write p-1 = k 2^e, where k is odd and e > 0.
  2566. * Then the multiplicative group mod p (call it G) has a sequence of
  2567. * e+1 nested subgroups G = G_0 > G_1 > G_2 > ... > G_e, where each
  2568. * G_i is exactly half the size of G_{i-1} and consists of all the
  2569. * squares of elements in G_{i-1}. So the innermost group G_e has
  2570. * order k, which is odd, and hence within that group you can take a
  2571. * square root by raising to the power (k+1)/2.
  2572. *
  2573. * Our strategy is to iterate over these groups one by one and make
  2574. * sure the number x we're trying to take the square root of is inside
  2575. * each one, by adjusting it if it isn't.
  2576. *
  2577. * Suppose g is a primitive root of p, i.e. a generator of G_0. (We
  2578. * don't actually need to know what g _is_; we just imagine it for the
  2579. * sake of understanding.) Then G_i consists of precisely the (2^i)th
  2580. * powers of g, and hence, you can tell if a number is in G_i if
  2581. * raising it to the power k 2^{e-i} gives 1. So the conceptual
  2582. * algorithm goes: for each i, test whether x is in G_i by that
  2583. * method. If it isn't, then the previous iteration ensured it's in
  2584. * G_{i-1}, so it will be an odd power of g^{2^{i-1}}, and hence
  2585. * multiplying by any other odd power of g^{2^{i-1}} will give x' in
  2586. * G_i. And we have one of those, because our non-square z is an odd
  2587. * power of g, so z^{2^{i-1}} is an odd power of g^{2^{i-1}}.
  2588. *
  2589. * (There's a special case in the very first iteration, where we don't
  2590. * have a G_{i-1}. If it turns out that x is not even in G_1, that
  2591. * means it's not a square, so we set *success to 0. We still run the
  2592. * rest of the algorithm anyway, for the sake of constant time, but we
  2593. * don't give a hoot what it returns.)
  2594. *
  2595. * When we get to the end and have x in G_e, then we can take its
  2596. * square root by raising to (k+1)/2. But of course that's not the
  2597. * square root of the original input - it's only the square root of
  2598. * the adjusted version we produced during the algorithm. To get the
  2599. * true output answer we also have to multiply by a power of z,
  2600. * namely, z to the power of _half_ whatever we've been multiplying in
  2601. * as we go along. (The power of z we multiplied in must have been
  2602. * even, because the case in which we would have multiplied in an odd
  2603. * power of z is the i=0 case, in which we instead set the failure
  2604. * flag.)
  2605. *
  2606. * The code below is an optimised version of that basic idea, in which
  2607. * we _start_ by computing x^k so as to be able to test membership in
  2608. * G_i by only a few squarings rather than a full from-scratch modpow
  2609. * every time; we also start by computing our candidate output value
  2610. * x^{(k+1)/2}. So when the above description says 'adjust x by z^i'
  2611. * for some i, we have to adjust our running values of x^k and
  2612. * x^{(k+1)/2} by z^{ik} and z^{ik/2} respectively (the latter is safe
  2613. * because, as above, i is always even). And it turns out that we
  2614. * don't actually have to store the adjusted version of x itself at
  2615. * all - we _only_ keep those two powers of it.
  2616. */
  2617. mp_int *monty_modsqrt(ModsqrtContext *sc, mp_int *x, unsigned *success)
  2618. {
  2619. modsqrt_lazy_setup(sc);
  2620. { // WINSCP
  2621. mp_int *scratch_to_free = mp_make_sized(3 * sc->mc->rw);
  2622. mp_int scratch = *scratch_to_free;
  2623. /*
  2624. * Compute toret = x^{(k+1)/2}, our starting point for the output
  2625. * square root, and also xk = x^k which we'll use as we go along
  2626. * for knowing when to apply correction factors. We do this by
  2627. * first computing x^{(k-1)/2}, then multiplying it by x, then
  2628. * multiplying the two together.
  2629. */
  2630. mp_int *toret = monty_pow(sc->mc, x, sc->km1o2);
  2631. mp_int xk = mp_alloc_from_scratch(&scratch, sc->mc->rw);
  2632. mp_copy_into(&xk, toret);
  2633. monty_mul_into(sc->mc, toret, toret, x);
  2634. monty_mul_into(sc->mc, &xk, toret, &xk);
  2635. { // WINSCP
  2636. mp_int tmp = mp_alloc_from_scratch(&scratch, sc->mc->rw);
  2637. mp_int power_of_zk = mp_alloc_from_scratch(&scratch, sc->mc->rw);
  2638. size_t i; // WINSCP
  2639. mp_copy_into(&power_of_zk, sc->zk);
  2640. for (i = 0; i < sc->e; i++) {
  2641. size_t j; // WINSCP
  2642. mp_copy_into(&tmp, &xk);
  2643. for (j = i+1; j < sc->e; j++)
  2644. monty_mul_into(sc->mc, &tmp, &tmp, &tmp);
  2645. { // WINSCP
  2646. unsigned eq1 = mp_cmp_eq(&tmp, monty_identity(sc->mc));
  2647. if (i == 0) {
  2648. /* One special case: if x=0, then no power of x will ever
  2649. * equal 1, but we should still report success on the
  2650. * grounds that 0 does have a square root mod p. */
  2651. *success = eq1 | mp_eq_integer(x, 0);
  2652. } else {
  2653. monty_mul_into(sc->mc, &tmp, toret, &power_of_zk);
  2654. mp_select_into(toret, &tmp, toret, eq1);
  2655. monty_mul_into(sc->mc, &power_of_zk,
  2656. &power_of_zk, &power_of_zk);
  2657. monty_mul_into(sc->mc, &tmp, &xk, &power_of_zk);
  2658. mp_select_into(&xk, &tmp, &xk, eq1);
  2659. }
  2660. } // WINSCP
  2661. }
  2662. mp_free(scratch_to_free);
  2663. return toret;
  2664. } // WINSCP
  2665. } // WINSCP
  2666. }
  2667. mp_int *mp_random_bits_fn(size_t bits, random_read_fn_t random_read)
  2668. {
  2669. size_t bytes = (bits + 7) / 8;
  2670. uint8_t *randbuf = snewn(bytes, uint8_t);
  2671. random_read(randbuf, bytes);
  2672. if (bytes)
  2673. randbuf[0] &= (2 << ((bits-1) & 7)) - 1;
  2674. { // WINSCP
  2675. mp_int *toret = mp_from_bytes_be(make_ptrlen(randbuf, bytes));
  2676. smemclr(randbuf, bytes);
  2677. sfree(randbuf);
  2678. return toret;
  2679. } // WINSCP
  2680. }
  2681. mp_int *mp_random_upto_fn(mp_int *limit, random_read_fn_t rf)
  2682. {
  2683. /*
  2684. * It would be nice to generate our random numbers in such a way
  2685. * as to make every possible outcome literally equiprobable. But
  2686. * we can't do that in constant time, so we have to go for a very
  2687. * close approximation instead. I'm going to take the view that a
  2688. * factor of (1+2^-128) between the probabilities of two outcomes
  2689. * is acceptable on the grounds that you'd have to examine so many
  2690. * outputs to even detect it.
  2691. */
  2692. mp_int *unreduced = mp_random_bits_fn(mp_max_bits(limit) + 128, rf);
  2693. mp_int *reduced = mp_mod(unreduced, limit);
  2694. mp_free(unreduced);
  2695. return reduced;
  2696. }
  2697. mp_int *mp_random_in_range_fn(mp_int *lo, mp_int *hi, random_read_fn_t rf)
  2698. {
  2699. mp_int *n_outcomes = mp_sub(hi, lo);
  2700. mp_int *addend = mp_random_upto_fn(n_outcomes, rf);
  2701. mp_int *result = mp_make_sized(hi->nw);
  2702. mp_add_into(result, addend, lo);
  2703. mp_free(addend);
  2704. mp_free(n_outcomes);
  2705. return result;
  2706. }