mpint.c 87 KB

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