mpint.c 85 KB

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