mpint.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. #ifndef PUTTY_MPINT_H
  2. #define PUTTY_MPINT_H
  3. /*
  4. * PuTTY's multiprecision integer library.
  5. *
  6. * This library is written with the aim of avoiding leaking the input
  7. * numbers via timing and cache side channels. This means avoiding
  8. * making any control flow change, or deciding the address of any
  9. * memory access, based on the value of potentially secret input data.
  10. *
  11. * But in a library that has to handle numbers of arbitrary size, you
  12. * can't avoid your control flow depending on the _size_ of the input!
  13. * So the rule is that an mp_int has a nominal size that need not be
  14. * its mathematical size: i.e. if you call (say) mp_from_bytes_be to
  15. * turn an array of 256 bytes into an integer, and all but the last of
  16. * those bytes is zero, then you get an mp_int which has space for 256
  17. * bytes of data but just happens to store the value 1. So the
  18. * _nominal_ sizes of input data - e.g. the size in bits of some
  19. * public-key modulus - are not considered secret, and control flow is
  20. * allowed to do what it likes based on those sizes. But the same
  21. * function, called with the same _nominally sized_ arguments
  22. * containing different values, should run in the same length of time.
  23. *
  24. * When a function returns an 'mp_int *', it is newly allocated to an
  25. * appropriate nominal size (which, again, depends only on the nominal
  26. * sizes of the inputs). Other functions have 'into' in their name,
  27. * and they instead overwrite the contents of an existing mp_int.
  28. *
  29. * Functions in this API which return values that are logically
  30. * boolean return them as 'unsigned' rather than the C99 bool type.
  31. * That's because C99 bool does an implicit test for non-zero-ness
  32. * when converting any other integer type to it, which compilers might
  33. * well implement using data-dependent control flow.
  34. */
  35. /*
  36. * Create and destroy mp_ints. A newly created one is initialised to
  37. * zero. mp_clear also resets an existing number to zero.
  38. */
  39. mp_int *mp_new(size_t maxbits);
  40. void mp_free(mp_int *);
  41. void mp_clear(mp_int *x);
  42. /*
  43. * Create mp_ints from various sources: little- and big-endian binary
  44. * data, an ordinary C unsigned integer type, a decimal or hex string
  45. * (given either as a ptrlen or a C NUL-terminated string), and
  46. * another mp_int.
  47. *
  48. * The decimal and hex conversion functions have running time
  49. * dependent on the length of the input data, of course.
  50. */
  51. mp_int *mp_from_bytes_le(ptrlen bytes);
  52. mp_int *mp_from_bytes_be(ptrlen bytes);
  53. mp_int *mp_from_integer(uintmax_t n);
  54. mp_int *mp_from_decimal_pl(ptrlen decimal);
  55. mp_int *mp_from_decimal(const char *decimal);
  56. mp_int *mp_from_hex_pl(ptrlen hex);
  57. mp_int *mp_from_hex(const char *hex);
  58. mp_int *mp_copy(mp_int *x);
  59. /*
  60. * A macro for declaring large fixed numbers in source code (such as
  61. * elliptic curve parameters, or standard Diffie-Hellman moduli). The
  62. * idea is that you just write something like
  63. *
  64. * mp_int *value = MP_LITERAL(0x19284376283754638745693467245);
  65. *
  66. * and it newly allocates you an mp_int containing that number.
  67. *
  68. * Internally, the macro argument is stringified and passed to
  69. * mp_from_hex. That's not as fast as it could be if I had instead set
  70. * up some kind of mp_from_array_of_uint64_t() function, but I think
  71. * this system is valuable for the fact that the literal integers
  72. * appear in a very natural syntax that can be pasted directly out
  73. * into, say, Python if you want to cross-check a calculation.
  74. */
  75. static inline mp_int *mp__from_string_literal(const char *lit)
  76. {
  77. /* Don't call this directly; it's not equipped to deal with
  78. * hostile data. Use only via the MP_LITERAL macro. */
  79. if (lit[0] && (lit[1] == 'x' || lit[1] == 'X'))
  80. return mp_from_hex(lit+2);
  81. else
  82. return mp_from_decimal(lit);
  83. }
  84. // WINSCP
  85. static inline mp_int *mp__from_string_literal_check(const char *lit)
  86. {
  87. // WORKAROUND: C++ Builder seems to limit stringified code to about 256 characters.
  88. // So make sure this is not the case.
  89. // If it is, we need to call mp__from_string_literal directly (MP_LITERAL_WINSCP_STR)
  90. // with a string (as in dh_group*_construct).
  91. assert(strlen(lit) < 200);
  92. return mp__from_string_literal(lit);
  93. }
  94. #define MP_LITERAL(number) mp__from_string_literal_check(#number)
  95. #define MP_LITERAL_WINSCP_STR(number) mp__from_string_literal(number)
  96. /*
  97. * Create an mp_int with the value 2^power.
  98. */
  99. mp_int *mp_power_2(size_t power);
  100. /*
  101. * Retrieve the value of a particular bit or byte of an mp_int. The
  102. * byte / bit index is not considered to be secret data. Out-of-range
  103. * byte/bit indices are handled cleanly and return zero.
  104. */
  105. uint8_t mp_get_byte(mp_int *x, size_t byte);
  106. unsigned mp_get_bit(mp_int *x, size_t bit);
  107. /*
  108. * Retrieve the value of an mp_int as a uintmax_t, assuming it's small
  109. * enough to fit.
  110. */
  111. uintmax_t mp_get_integer(mp_int *x);
  112. /*
  113. * Set an mp_int bit. Again, the bit index is not considered secret.
  114. * Do not pass an out-of-range index, on pain of assertion failure.
  115. */
  116. void mp_set_bit(mp_int *x, size_t bit, unsigned val);
  117. /*
  118. * Return the nominal size of an mp_int, in terms of the maximum
  119. * number of bytes or bits that can fit in it.
  120. */
  121. size_t mp_max_bytes(mp_int *x);
  122. size_t mp_max_bits(mp_int *x);
  123. /*
  124. * Return the _mathematical_ bit count of an mp_int (not its nominal
  125. * size), i.e. a value n such that 2^{n-1} <= x < 2^n.
  126. *
  127. * This function is supposed to run in constant time for a given
  128. * nominal input size. Of course it's likely that clients of this
  129. * function will promptly need to use the result as the limit of some
  130. * loop (e.g. marshalling an mp_int into an SSH packet, which doesn't
  131. * permit extra prefix zero bytes). But that's up to the caller to
  132. * decide the safety of.
  133. */
  134. size_t mp_get_nbits(mp_int *x);
  135. /*
  136. * Return the value of an mp_int as a decimal or hex string. The
  137. * result is dynamically allocated, and the caller is responsible for
  138. * freeing it.
  139. *
  140. * These functions should run in constant time for a given nominal
  141. * input size, even though the exact number of digits returned is
  142. * variable. They always allocate enough space for the largest output
  143. * that might be needed, but they don't always fill it.
  144. */
  145. char *mp_get_decimal(mp_int *x);
  146. char *mp_get_hex(mp_int *x);
  147. char *mp_get_hex_uppercase(mp_int *x);
  148. /*
  149. * Compare two mp_ints, or compare one mp_int against a C integer. The
  150. * 'eq' functions return 1 if the two inputs are equal, or 0
  151. * otherwise; the 'hs' functions return 1 if the first input is >= the
  152. * second, and 0 otherwise.
  153. */
  154. unsigned mp_cmp_hs(mp_int *a, mp_int *b);
  155. unsigned mp_cmp_eq(mp_int *a, mp_int *b);
  156. unsigned mp_hs_integer(mp_int *x, uintmax_t n);
  157. unsigned mp_eq_integer(mp_int *x, uintmax_t n);
  158. /*
  159. * Take the minimum or maximum of two mp_ints, without using a
  160. * conditional branch.
  161. */
  162. void mp_min_into(mp_int *r, mp_int *x, mp_int *y);
  163. void mp_max_into(mp_int *r, mp_int *x, mp_int *y);
  164. mp_int *mp_min(mp_int *x, mp_int *y);
  165. mp_int *mp_max(mp_int *x, mp_int *y);
  166. /*
  167. * Diagnostic function. Writes out x in hex to the supplied stdio
  168. * stream, preceded by the string 'prefix' and followed by 'suffix'.
  169. *
  170. * This is useful to put temporarily into code, but it's also
  171. * potentially useful to call from a debugger.
  172. */
  173. void mp_dump(FILE *fp, const char *prefix, mp_int *x, const char *suffix);
  174. /*
  175. * Overwrite one mp_int with another.
  176. */
  177. void mp_copy_into(mp_int *dest, mp_int *src);
  178. /*
  179. * Conditional selection. Overwrites dest with either src0 or src1,
  180. * according to the value of 'choose_src1'. choose_src1 should be 0 or
  181. * 1; if it's 1, then dest is set to src1, otherwise src0.
  182. *
  183. * The value of choose_src1 is considered to be secret data, so
  184. * control flow and memory access should not depend on it.
  185. */
  186. void mp_select_into(mp_int *dest, mp_int *src0, mp_int *src1,
  187. unsigned choose_src1);
  188. /*
  189. * Addition, subtraction and multiplication, either targeting an
  190. * existing mp_int or making a new one large enough to hold whatever
  191. * the output might be..
  192. */
  193. void mp_add_into(mp_int *r, mp_int *a, mp_int *b);
  194. void mp_sub_into(mp_int *r, mp_int *a, mp_int *b);
  195. void mp_mul_into(mp_int *r, mp_int *a, mp_int *b);
  196. mp_int *mp_add(mp_int *x, mp_int *y);
  197. mp_int *mp_sub(mp_int *x, mp_int *y);
  198. mp_int *mp_mul(mp_int *x, mp_int *y);
  199. /*
  200. * Bitwise operations.
  201. */
  202. void mp_and_into(mp_int *r, mp_int *a, mp_int *b);
  203. void mp_or_into(mp_int *r, mp_int *a, mp_int *b);
  204. void mp_xor_into(mp_int *r, mp_int *a, mp_int *b);
  205. void mp_bic_into(mp_int *r, mp_int *a, mp_int *b);
  206. /*
  207. * Addition, subtraction and multiplication with one argument small
  208. * enough to fit in a C integer. For mp_mul_integer_into, it has to be
  209. * even smaller than that.
  210. */
  211. void mp_add_integer_into(mp_int *r, mp_int *a, uintmax_t n);
  212. void mp_sub_integer_into(mp_int *r, mp_int *a, uintmax_t n);
  213. void mp_mul_integer_into(mp_int *r, mp_int *a, uint16_t n);
  214. /*
  215. * Conditional addition/subtraction. If yes == 1, sets r to a+b or a-b
  216. * (respectively). If yes == 0, sets r to just a. 'yes' is considered
  217. * secret data.
  218. */
  219. void mp_cond_add_into(mp_int *r, mp_int *a, mp_int *b, unsigned yes);
  220. void mp_cond_sub_into(mp_int *r, mp_int *a, mp_int *b, unsigned yes);
  221. /*
  222. * Swap x0 and x1 if swap == 1, and not if swap == 0. 'swap' is
  223. * considered secret.
  224. */
  225. void mp_cond_swap(mp_int *x0, mp_int *x1, unsigned swap);
  226. /*
  227. * Set x to 0 if clear == 1, and otherwise leave it unchanged. 'clear'
  228. * is considered secret.
  229. */
  230. void mp_cond_clear(mp_int *x, unsigned clear);
  231. /*
  232. * Division. mp_divmod_into divides n by d, and writes the quotient
  233. * into q and the remainder into r. You can pass either of q and r as
  234. * NULL if you don't need one of the outputs.
  235. *
  236. * mp_div and mp_mod are wrappers that return one or other of those
  237. * outputs as a freshly allocated mp_int of the appropriate size.
  238. *
  239. * Division by zero gives no error, and returns a quotient of 0 and a
  240. * remainder of n (so as to still satisfy the division identity that
  241. * n=qd+r).
  242. */
  243. void mp_divmod_into(mp_int *n, mp_int *d, mp_int *q, mp_int *r);
  244. mp_int *mp_div(mp_int *n, mp_int *d);
  245. mp_int *mp_mod(mp_int *x, mp_int *modulus);
  246. /*
  247. * Trivially easy special case of mp_mod: reduce a number mod a power
  248. * of two.
  249. */
  250. void mp_reduce_mod_2to(mp_int *x, size_t p);
  251. /*
  252. * Modular inverses. mp_invert computes the inverse of x mod modulus
  253. * (and will expect the two to be coprime). mp_invert_mod_2to computes
  254. * the inverse of x mod 2^p, and is a great deal faster.
  255. */
  256. mp_int *mp_invert_mod_2to(mp_int *x, size_t p);
  257. mp_int *mp_invert(mp_int *x, mp_int *modulus);
  258. /*
  259. * System for taking square roots modulo an odd prime.
  260. *
  261. * In order to do this efficiently, you need to provide an extra piece
  262. * of information at setup time, namely a number which is not
  263. * congruent mod p to any square. Given p and that non-square, you can
  264. * use modsqrt_new to make a context containing all the necessary
  265. * equipment for actually calculating the square roots, and then you
  266. * can call mp_modsqrt as many times as you like on that context
  267. * before freeing it.
  268. *
  269. * The output parameter '*success' will be filled in with 1 if the
  270. * operation was successful, or 0 if the input number doesn't have a
  271. * square root mod p at all. In the latter case, the returned mp_int
  272. * will be nonsense and you shouldn't depend on it.
  273. *
  274. * ==== WARNING ====
  275. *
  276. * This function DOES NOT TREAT THE PRIME MODULUS AS SECRET DATA! It
  277. * will protect the number you're taking the square root _of_, but not
  278. * the number you're taking the root of it _mod_.
  279. *
  280. * (This is because the algorithm requires a number of loop iterations
  281. * equal to the number of factors of 2 in p-1. And the expected use of
  282. * this function is for elliptic-curve point decompression, in which
  283. * the modulus is always a well-known one written down in standards
  284. * documents.)
  285. */
  286. typedef struct ModsqrtContext ModsqrtContext;
  287. ModsqrtContext *modsqrt_new(mp_int *p, mp_int *any_nonsquare_mod_p);
  288. void modsqrt_free(ModsqrtContext *);
  289. mp_int *mp_modsqrt(ModsqrtContext *sc, mp_int *x, unsigned *success);
  290. /*
  291. * Functions for Montgomery multiplication, a fast technique for doing
  292. * a long series of modular multiplications all with the same modulus
  293. * (which has to be odd).
  294. *
  295. * You start by calling monty_new to set up a context structure
  296. * containing all the precomputed bits and pieces needed by the
  297. * algorithm. Then, any numbers you want to work with must first be
  298. * transformed into the internal Montgomery representation using
  299. * monty_import; having done that, you can use monty_mul and monty_pow
  300. * to operate on them efficiently; and finally, monty_export will
  301. * convert numbers back out of Montgomery representation to give their
  302. * ordinary values.
  303. *
  304. * Addition and subtraction are not optimised by the Montgomery trick,
  305. * but monty_add and monty_sub are provided anyway for convenience.
  306. *
  307. * There are also monty_invert and monty_modsqrt, which are analogues
  308. * of mp_invert and mp_modsqrt which take their inputs in Montgomery
  309. * representation. For mp_modsqrt, the prime modulus of the
  310. * ModsqrtContext must be the same as the modulus of the MontyContext.
  311. *
  312. * The query functions monty_modulus and monty_identity return numbers
  313. * stored inside the MontyContext, without copying them. The returned
  314. * pointers are still owned by the MontyContext, so don't free them!
  315. */
  316. MontyContext *monty_new(mp_int *modulus);
  317. void monty_free(MontyContext *mc);
  318. mp_int *monty_modulus(MontyContext *mc); /* doesn't transfer ownership */
  319. mp_int *monty_identity(MontyContext *mc); /* doesn't transfer ownership */
  320. void monty_import_into(MontyContext *mc, mp_int *r, mp_int *x);
  321. mp_int *monty_import(MontyContext *mc, mp_int *x);
  322. void monty_export_into(MontyContext *mc, mp_int *r, mp_int *x);
  323. mp_int *monty_export(MontyContext *mc, mp_int *x);
  324. void monty_mul_into(MontyContext *, mp_int *r, mp_int *, mp_int *);
  325. mp_int *monty_add(MontyContext *, mp_int *, mp_int *);
  326. mp_int *monty_sub(MontyContext *, mp_int *, mp_int *);
  327. mp_int *monty_mul(MontyContext *, mp_int *, mp_int *);
  328. mp_int *monty_pow(MontyContext *, mp_int *base, mp_int *exponent);
  329. mp_int *monty_invert(MontyContext *, mp_int *);
  330. mp_int *monty_modsqrt(ModsqrtContext *sc, mp_int *mx, unsigned *success);
  331. /*
  332. * Modular arithmetic functions which don't use an explicit
  333. * MontyContext. mp_modpow will use one internally (on the assumption
  334. * that the exponent is likely to be large enough to make it
  335. * worthwhile); the other three will just do ordinary non-Montgomery-
  336. * optimised modular reduction. Use mp_modmul if you only have one
  337. * product to compute; if you have a lot, consider using a
  338. * MontyContext in the client code.
  339. */
  340. mp_int *mp_modpow(mp_int *base, mp_int *exponent, mp_int *modulus);
  341. mp_int *mp_modmul(mp_int *x, mp_int *y, mp_int *modulus);
  342. mp_int *mp_modadd(mp_int *x, mp_int *y, mp_int *modulus);
  343. mp_int *mp_modsub(mp_int *x, mp_int *y, mp_int *modulus);
  344. /*
  345. * Shift an mp_int right by a given number of bits. The shift count is
  346. * considered to be secret data, and as a result, the algorithm takes
  347. * O(n log n) time instead of the obvious O(n).
  348. */
  349. mp_int *mp_rshift_safe(mp_int *x, size_t shift);
  350. /*
  351. * Shift an mp_int left or right by a fixed number of bits. The shift
  352. * count is NOT considered to be secret data! Use this if you're
  353. * always dividing by 2, for example, but don't use it to shift by a
  354. * variable amount derived from another secret number.
  355. *
  356. * The upside is that these functions run in sensible linear time.
  357. */
  358. void mp_lshift_fixed_into(mp_int *r, mp_int *a, size_t shift);
  359. void mp_rshift_fixed_into(mp_int *r, mp_int *x, size_t shift);
  360. mp_int *mp_rshift_fixed(mp_int *x, size_t shift);
  361. /*
  362. * Generate a random mp_int.
  363. *
  364. * The _function_ definitions here will expect to be given a gen_data
  365. * function that provides random data. Normally you'd use this using
  366. * random_read() from random.c, and the macro wrappers automate that.
  367. *
  368. * (This is a bit of a dodge to avoid mpint.c having a link-time
  369. * dependency on random.c, so that programs can link against one but
  370. * not the other: if a client of this header uses one of these macros
  371. * then _they_ have link-time dependencies on both modules.)
  372. *
  373. * mp_random_bits[_fn] returns an integer 0 <= n < 2^bits.
  374. * mp_random_in_range[_fn](lo,hi) returns an integer lo <= n < hi.
  375. */
  376. typedef void (*random_read_fn_t)(void *, size_t);
  377. mp_int *mp_random_bits_fn(size_t bits, random_read_fn_t randfn);
  378. mp_int *mp_random_in_range_fn(
  379. mp_int *lo_inclusive, mp_int *hi_exclusive, random_read_fn_t randfn);
  380. #define mp_random_bits(bits) mp_random_bits_fn(bits, random_read)
  381. #define mp_random_in_range(lo, hi) mp_random_in_range_fn(lo, hi, random_read)
  382. #endif /* PUTTY_MPINT_H */