Fix typos
[TortoiseGit.git] / src / TortoisePlink / mpint.h
bloba101365a21293743c63a28737407c408c734b7a0
1 #ifndef PUTTY_MPINT_H
2 #define PUTTY_MPINT_H
4 /*
5 * PuTTY's multiprecision integer library.
7 * This library is written with the aim of avoiding leaking the input
8 * numbers via timing and cache side channels. This means avoiding
9 * making any control flow change, or deciding the address of any
10 * memory access, based on the value of potentially secret input data.
12 * But in a library that has to handle numbers of arbitrary size, you
13 * can't avoid your control flow depending on the _size_ of the input!
14 * So the rule is that an mp_int has a nominal size that need not be
15 * its mathematical size: i.e. if you call (say) mp_from_bytes_be to
16 * turn an array of 256 bytes into an integer, and all but the last of
17 * those bytes is zero, then you get an mp_int which has space for 256
18 * bytes of data but just happens to store the value 1. So the
19 * _nominal_ sizes of input data - e.g. the size in bits of some
20 * public-key modulus - are not considered secret, and control flow is
21 * allowed to do what it likes based on those sizes. But the same
22 * function, called with the same _nominally sized_ arguments
23 * containing different values, should run in the same length of time.
25 * When a function returns an 'mp_int *', it is newly allocated to an
26 * appropriate nominal size (which, again, depends only on the nominal
27 * sizes of the inputs). Other functions have 'into' in their name,
28 * and they instead overwrite the contents of an existing mp_int.
30 * Functions in this API which return values that are logically
31 * boolean return them as 'unsigned' rather than the C99 bool type.
32 * That's because C99 bool does an implicit test for non-zero-ness
33 * when converting any other integer type to it, which compilers might
34 * well implement using data-dependent control flow.
38 * Create and destroy mp_ints. A newly created one is initialised to
39 * zero. mp_clear also resets an existing number to zero.
41 mp_int *mp_new(size_t maxbits);
42 void mp_free(mp_int *);
43 void mp_clear(mp_int *x);
46 * Resize the physical size of existing mp_int, e.g. so that you have
47 * room to transform it in place to a larger value. Destroys the old
48 * mp_int in the process.
50 mp_int *mp_resize(mp_int *, size_t newmaxbits);
53 * Create mp_ints from various sources: little- and big-endian binary
54 * data, an ordinary C unsigned integer type, a decimal or hex string
55 * (given either as a ptrlen or a C NUL-terminated string), and
56 * another mp_int.
58 * The decimal and hex conversion functions have running time
59 * dependent on the length of the input data, of course.
61 mp_int *mp_from_bytes_le(ptrlen bytes);
62 mp_int *mp_from_bytes_be(ptrlen bytes);
63 mp_int *mp_from_integer(uintmax_t n);
64 mp_int *mp_from_decimal_pl(ptrlen decimal);
65 mp_int *mp_from_decimal(const char *decimal);
66 mp_int *mp_from_hex_pl(ptrlen hex);
67 mp_int *mp_from_hex(const char *hex);
68 mp_int *mp_copy(mp_int *x);
71 * A macro for declaring large fixed numbers in source code (such as
72 * elliptic curve parameters, or standard Diffie-Hellman moduli). The
73 * idea is that you just write something like
75 * mp_int *value = MP_LITERAL(0x19284376283754638745693467245);
77 * and it newly allocates you an mp_int containing that number.
79 * Internally, the macro argument is stringified and passed to
80 * mp_from_hex. That's not as fast as it could be if I had instead set
81 * up some kind of mp_from_array_of_uint64_t() function, but I think
82 * this system is valuable for the fact that the literal integers
83 * appear in a very natural syntax that can be pasted directly out
84 * into, say, Python if you want to cross-check a calculation.
86 static inline mp_int *mp__from_string_literal(const char *lit)
88 /* Don't call this directly; it's not equipped to deal with
89 * hostile data. Use only via the MP_LITERAL macro. */
90 if (lit[0] && (lit[1] == 'x' || lit[1] == 'X'))
91 return mp_from_hex(lit+2);
92 else
93 return mp_from_decimal(lit);
95 #define MP_LITERAL(number) mp__from_string_literal(#number)
98 * Create an mp_int with the value 2^power.
100 mp_int *mp_power_2(size_t power);
103 * Retrieve the value of a particular bit or byte of an mp_int. The
104 * byte / bit index is not considered to be secret data. Out-of-range
105 * byte/bit indices are handled cleanly and return zero.
107 uint8_t mp_get_byte(mp_int *x, size_t byte);
108 unsigned mp_get_bit(mp_int *x, size_t bit);
111 * Retrieve the value of an mp_int as a uintmax_t, assuming it's small
112 * enough to fit.
114 uintmax_t mp_get_integer(mp_int *x);
117 * Set an mp_int bit. Again, the bit index is not considered secret.
118 * Do not pass an out-of-range index, on pain of assertion failure.
120 void mp_set_bit(mp_int *x, size_t bit, unsigned val);
123 * Return the nominal size of an mp_int, in terms of the maximum
124 * number of bytes or bits that can fit in it.
126 size_t mp_max_bytes(mp_int *x);
127 size_t mp_max_bits(mp_int *x);
130 * Return the _mathematical_ bit count of an mp_int (not its nominal
131 * size), i.e. a value n such that 2^{n-1} <= x < 2^n.
133 * This function is supposed to run in constant time for a given
134 * nominal input size. Of course it's likely that clients of this
135 * function will promptly need to use the result as the limit of some
136 * loop (e.g. marshalling an mp_int into an SSH packet, which doesn't
137 * permit extra prefix zero bytes). But that's up to the caller to
138 * decide the safety of.
140 size_t mp_get_nbits(mp_int *x);
143 * Return the value of an mp_int as a decimal or hex string. The
144 * result is dynamically allocated, and the caller is responsible for
145 * freeing it.
147 * These functions should run in constant time for a given nominal
148 * input size, even though the exact number of digits returned is
149 * variable. They always allocate enough space for the largest output
150 * that might be needed, but they don't always fill it.
152 char *mp_get_decimal(mp_int *x);
153 char *mp_get_hex(mp_int *x);
154 char *mp_get_hex_uppercase(mp_int *x);
157 * Compare two mp_ints, or compare one mp_int against a C integer. The
158 * 'eq' functions return 1 if the two inputs are equal, or 0
159 * otherwise; the 'hs' functions return 1 if the first input is >= the
160 * second, and 0 otherwise.
162 unsigned mp_cmp_hs(mp_int *a, mp_int *b);
163 unsigned mp_cmp_eq(mp_int *a, mp_int *b);
164 unsigned mp_hs_integer(mp_int *x, uintmax_t n);
165 unsigned mp_eq_integer(mp_int *x, uintmax_t n);
168 * Take the minimum or maximum of two mp_ints, without using a
169 * conditional branch.
171 void mp_min_into(mp_int *r, mp_int *x, mp_int *y);
172 void mp_max_into(mp_int *r, mp_int *x, mp_int *y);
173 mp_int *mp_min(mp_int *x, mp_int *y);
174 mp_int *mp_max(mp_int *x, mp_int *y);
177 * Diagnostic function. Writes out x in hex to the supplied stdio
178 * stream, preceded by the string 'prefix' and followed by 'suffix'.
180 * This is useful to put temporarily into code, but it's also
181 * potentially useful to call from a debugger.
183 void mp_dump(FILE *fp, const char *prefix, mp_int *x, const char *suffix);
186 * Overwrite one mp_int with another, or with a plain integer.
188 void mp_copy_into(mp_int *dest, mp_int *src);
189 void mp_copy_integer_into(mp_int *dest, uintmax_t n);
192 * Conditional selection. Overwrites dest with either src0 or src1,
193 * according to the value of 'choose_src1'. choose_src1 should be 0 or
194 * 1; if it's 1, then dest is set to src1, otherwise src0.
196 * The value of choose_src1 is considered to be secret data, so
197 * control flow and memory access should not depend on it.
199 void mp_select_into(mp_int *dest, mp_int *src0, mp_int *src1,
200 unsigned choose_src1);
203 * Addition, subtraction and multiplication, either targeting an
204 * existing mp_int or making a new one large enough to hold whatever
205 * the output might be..
207 void mp_add_into(mp_int *r, mp_int *a, mp_int *b);
208 void mp_sub_into(mp_int *r, mp_int *a, mp_int *b);
209 void mp_mul_into(mp_int *r, mp_int *a, mp_int *b);
210 mp_int *mp_add(mp_int *x, mp_int *y);
211 mp_int *mp_sub(mp_int *x, mp_int *y);
212 mp_int *mp_mul(mp_int *x, mp_int *y);
215 * Bitwise operations.
217 void mp_and_into(mp_int *r, mp_int *a, mp_int *b);
218 void mp_or_into(mp_int *r, mp_int *a, mp_int *b);
219 void mp_xor_into(mp_int *r, mp_int *a, mp_int *b);
220 void mp_bic_into(mp_int *r, mp_int *a, mp_int *b);
223 * Addition, subtraction and multiplication with one argument small
224 * enough to fit in a C integer. For mp_mul_integer_into, it has to be
225 * even smaller than that.
227 void mp_add_integer_into(mp_int *r, mp_int *a, uintmax_t n);
228 void mp_sub_integer_into(mp_int *r, mp_int *a, uintmax_t n);
229 void mp_mul_integer_into(mp_int *r, mp_int *a, uint16_t n);
232 * Conditional addition/subtraction. If yes == 1, sets r to a+b or a-b
233 * (respectively). If yes == 0, sets r to just a. 'yes' is considered
234 * secret data.
236 void mp_cond_add_into(mp_int *r, mp_int *a, mp_int *b, unsigned yes);
237 void mp_cond_sub_into(mp_int *r, mp_int *a, mp_int *b, unsigned yes);
240 * Swap x0 and x1 if swap == 1, and not if swap == 0. 'swap' is
241 * considered secret.
243 void mp_cond_swap(mp_int *x0, mp_int *x1, unsigned swap);
246 * Set x to 0 if clear == 1, and otherwise leave it unchanged. 'clear'
247 * is considered secret.
249 void mp_cond_clear(mp_int *x, unsigned clear);
252 * Division. mp_divmod_into divides n by d, and writes the quotient
253 * into q and the remainder into r. You can pass either of q and r as
254 * NULL if you don't need one of the outputs.
256 * mp_div and mp_mod are wrappers that return one or other of those
257 * outputs as a freshly allocated mp_int of the appropriate size.
259 * Division by zero gives no error, and returns a quotient of 0 and a
260 * remainder of n (so as to still satisfy the division identity that
261 * n=qd+r).
263 void mp_divmod_into(mp_int *n, mp_int *d, mp_int *q, mp_int *r);
264 mp_int *mp_div(mp_int *n, mp_int *d);
265 mp_int *mp_mod(mp_int *x, mp_int *modulus);
268 * Compute the residue of x mod m, where m is a small integer. x is
269 * kept secret, but m is not.
271 uint32_t mp_mod_known_integer(mp_int *x, uint32_t m);
274 * Integer nth root. mp_nthroot returns the largest integer x such
275 * that x^n <= y, and if 'remainder' is non-NULL then it fills it with
276 * the residue (y - x^n).
278 * Currently, n has to be small enough that the largest binomial
279 * coefficient (n choose k) fits in 16 bits, which works out to at
280 * most 18.
282 mp_int *mp_nthroot(mp_int *y, unsigned n, mp_int *remainder);
285 * Trivially easy special case of mp_mod: reduce a number mod a power
286 * of two.
288 void mp_reduce_mod_2to(mp_int *x, size_t p);
291 * Modular inverses. mp_invert computes the inverse of x mod modulus
292 * (and will expect the two to be coprime). mp_invert_mod_2to computes
293 * the inverse of x mod 2^p, and is a great deal faster.
295 mp_int *mp_invert_mod_2to(mp_int *x, size_t p);
296 mp_int *mp_invert(mp_int *x, mp_int *modulus);
299 * Greatest common divisor.
301 * mp_gcd_into also returns a pair of Bezout coefficients, namely A,B
302 * such that a*A - b*B = gcd. (The minus sign is so that both returned
303 * coefficients can be positive.)
305 * You can pass any of mp_gcd_into's output pointers as NULL if you
306 * don't need that output value.
308 * mp_gcd is a wrapper with a less cumbersome API, for the case where
309 * the only output value you need is the gcd itself. mp_coprime is
310 * even easier, if all you care about is whether or not that gcd is 1.
312 mp_int *mp_gcd(mp_int *a, mp_int *b);
313 void mp_gcd_into(mp_int *a, mp_int *b,
314 mp_int *gcd_out, mp_int *A_out, mp_int *B_out);
315 unsigned mp_coprime(mp_int *a, mp_int *b);
318 * System for taking square roots modulo an odd prime.
320 * In order to do this efficiently, you need to provide an extra piece
321 * of information at setup time, namely a number which is not
322 * congruent mod p to any square. Given p and that non-square, you can
323 * use modsqrt_new to make a context containing all the necessary
324 * equipment for actually calculating the square roots, and then you
325 * can call mp_modsqrt as many times as you like on that context
326 * before freeing it.
328 * The output parameter '*success' will be filled in with 1 if the
329 * operation was successful, or 0 if the input number doesn't have a
330 * square root mod p at all. In the latter case, the returned mp_int
331 * will be nonsense and you shouldn't depend on it.
333 * ==== WARNING ====
335 * This function DOES NOT TREAT THE PRIME MODULUS AS SECRET DATA! It
336 * will protect the number you're taking the square root _of_, but not
337 * the number you're taking the root of it _mod_.
339 * (This is because the algorithm requires a number of loop iterations
340 * equal to the number of factors of 2 in p-1. And the expected use of
341 * this function is for elliptic-curve point decompression, in which
342 * the modulus is always a well-known one written down in standards
343 * documents.)
345 typedef struct ModsqrtContext ModsqrtContext;
346 ModsqrtContext *modsqrt_new(mp_int *p, mp_int *any_nonsquare_mod_p);
347 void modsqrt_free(ModsqrtContext *);
348 mp_int *mp_modsqrt(ModsqrtContext *sc, mp_int *x, unsigned *success);
351 * Functions for Montgomery multiplication, a fast technique for doing
352 * a long series of modular multiplications all with the same modulus
353 * (which has to be odd).
355 * You start by calling monty_new to set up a context structure
356 * containing all the precomputed bits and pieces needed by the
357 * algorithm. Then, any numbers you want to work with must first be
358 * transformed into the internal Montgomery representation using
359 * monty_import; having done that, you can use monty_mul and monty_pow
360 * to operate on them efficiently; and finally, monty_export will
361 * convert numbers back out of Montgomery representation to give their
362 * ordinary values.
364 * Addition and subtraction are not optimised by the Montgomery trick,
365 * but monty_add and monty_sub are provided anyway for convenience.
367 * There are also monty_invert and monty_modsqrt, which are analogues
368 * of mp_invert and mp_modsqrt which take their inputs in Montgomery
369 * representation. For mp_modsqrt, the prime modulus of the
370 * ModsqrtContext must be the same as the modulus of the MontyContext.
372 * The query functions monty_modulus and monty_identity return numbers
373 * stored inside the MontyContext, without copying them. The returned
374 * pointers are still owned by the MontyContext, so don't free them!
376 MontyContext *monty_new(mp_int *modulus);
377 void monty_free(MontyContext *mc);
378 mp_int *monty_modulus(MontyContext *mc); /* doesn't transfer ownership */
379 mp_int *monty_identity(MontyContext *mc); /* doesn't transfer ownership */
380 void monty_import_into(MontyContext *mc, mp_int *r, mp_int *x);
381 mp_int *monty_import(MontyContext *mc, mp_int *x);
382 void monty_export_into(MontyContext *mc, mp_int *r, mp_int *x);
383 mp_int *monty_export(MontyContext *mc, mp_int *x);
384 void monty_mul_into(MontyContext *, mp_int *r, mp_int *, mp_int *);
385 mp_int *monty_add(MontyContext *, mp_int *, mp_int *);
386 mp_int *monty_sub(MontyContext *, mp_int *, mp_int *);
387 mp_int *monty_mul(MontyContext *, mp_int *, mp_int *);
388 mp_int *monty_pow(MontyContext *, mp_int *base, mp_int *exponent);
389 mp_int *monty_invert(MontyContext *, mp_int *);
390 mp_int *monty_modsqrt(ModsqrtContext *sc, mp_int *mx, unsigned *success);
393 * Modular arithmetic functions which don't use an explicit
394 * MontyContext. mp_modpow will use one internally (on the assumption
395 * that the exponent is likely to be large enough to make it
396 * worthwhile); the other three will just do ordinary non-Montgomery-
397 * optimised modular reduction. Use mp_modmul if you only have one
398 * product to compute; if you have a lot, consider using a
399 * MontyContext in the client code.
401 mp_int *mp_modpow(mp_int *base, mp_int *exponent, mp_int *modulus);
402 mp_int *mp_modmul(mp_int *x, mp_int *y, mp_int *modulus);
403 mp_int *mp_modadd(mp_int *x, mp_int *y, mp_int *modulus);
404 mp_int *mp_modsub(mp_int *x, mp_int *y, mp_int *modulus);
407 * Shift an mp_int by a given number of bits. The shift count is
408 * considered to be secret data, and as a result, the algorithm takes
409 * O(n log n) time instead of the obvious O(n).
411 * There's no mp_lshift_safe, because the size of mp_int to allocate
412 * would not be able to avoid depending on the shift count. So if you
413 * need to behave independently of the size of a left shift, you have
414 * to know a bound on the space you'll need by some other means.
416 void mp_lshift_safe_into(mp_int *r, mp_int *x, size_t shift);
417 void mp_rshift_safe_into(mp_int *r, mp_int *x, size_t shift);
418 mp_int *mp_rshift_safe(mp_int *x, size_t shift);
421 * Shift an mp_int left or right by a fixed number of bits. The shift
422 * count is NOT considered to be secret data! Use this if you're
423 * always dividing by 2, for example, but don't use it to shift by a
424 * variable amount derived from another secret number.
426 * The upside is that these functions run in sensible linear time.
428 void mp_lshift_fixed_into(mp_int *r, mp_int *a, size_t shift);
429 void mp_rshift_fixed_into(mp_int *r, mp_int *x, size_t shift);
430 mp_int *mp_lshift_fixed(mp_int *x, size_t shift);
431 mp_int *mp_rshift_fixed(mp_int *x, size_t shift);
434 * Generate a random mp_int.
436 * The _function_ definitions here will expect to be given a gen_data
437 * function that provides random data. Normally you'd use this using
438 * random_read() from sshrand.c, and the macro wrappers automate that.
440 * (This is a bit of a dodge to avoid mpint.c having a link-time
441 * dependency on sshrand.c, so that programs can link against one but
442 * not the other: if a client of this header uses one of these macros
443 * then _they_ have link-time dependencies on both modules.)
445 * mp_random_bits[_fn] returns an integer 0 <= n < 2^bits.
446 * mp_random_upto[_fn](limit) returns an integer 0 <= n < limit.
447 * mp_random_in_range[_fn](lo,hi) returns an integer lo <= n < hi.
449 typedef void (*random_read_fn_t)(void *, size_t);
450 mp_int *mp_random_bits_fn(size_t bits, random_read_fn_t randfn);
451 mp_int *mp_random_upto_fn(mp_int *limit, random_read_fn_t randfn);
452 mp_int *mp_random_in_range_fn(
453 mp_int *lo_inclusive, mp_int *hi_exclusive, random_read_fn_t randfn);
454 #define mp_random_bits(bits) mp_random_bits_fn(bits, random_read)
455 #define mp_random_upto(limit) mp_random_upto_fn(limit, random_read)
456 #define mp_random_in_range(lo, hi) mp_random_in_range_fn(lo, hi, random_read)
458 #endif /* PUTTY_MPINT_H */