mpint.c 82 KB

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