mpint.c 101 KB

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