mpint.c 80 KB

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