mpint.c 100 KB

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