bignum_mod.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. /**
  2. * Modular bignum functions
  3. *
  4. * This module implements operations on integers modulo some fixed modulus.
  5. *
  6. * The functions in this module obey the following conventions unless
  7. * explicitly indicated otherwise:
  8. *
  9. * - **Modulus parameters**: the modulus is passed as a pointer to a structure
  10. * of type #mbedtls_mpi_mod_modulus. The structure must be set up with an
  11. * array of limbs storing the bignum value of the modulus. The modulus must
  12. * be odd and is assumed to have no leading zeroes. The modulus is usually
  13. * named \c N and is usually input-only. Functions which take a parameter
  14. * of type \c const #mbedtls_mpi_mod_modulus* must not modify its value.
  15. * - **Bignum parameters**: Bignums are passed as pointers to an array of
  16. * limbs or to a #mbedtls_mpi_mod_residue structure. A limb has the type
  17. * #mbedtls_mpi_uint. Residues must be initialized before use, and must be
  18. * associated with the modulus \c N. Unless otherwise specified:
  19. * - Bignum parameters called \c A, \c B, ... are inputs and are not
  20. * modified by the function. Functions which take a parameter of
  21. * type \c const #mbedtls_mpi_mod_residue* must not modify its value.
  22. * - Bignum parameters called \c X, \c Y, ... are outputs or input-output.
  23. * The initial bignum value of output-only parameters is ignored, but
  24. * they must be set up and associated with the modulus \c N. Some
  25. * functions (typically constant-flow) require that the limbs in an
  26. * output residue are initialized.
  27. * - Bignum parameters called \c p are inputs used to set up a modulus or
  28. * residue. These must be pointers to an array of limbs.
  29. * - \c T is a temporary storage area. The initial content of such a
  30. * parameter is ignored and the final content is unspecified.
  31. * - Some functions use different names, such as \c r for the residue.
  32. * - **Bignum sizes**: bignum sizes are always expressed in limbs. Both
  33. * #mbedtls_mpi_mod_modulus and #mbedtls_mpi_mod_residue have a \c limbs
  34. * member storing its size. All bignum parameters must have the same
  35. * number of limbs as the modulus. All bignum sizes must be at least 1 and
  36. * must be significantly less than #SIZE_MAX. The behavior if a size is 0 is
  37. * undefined.
  38. * - **Bignum representation**: the representation of inputs and outputs is
  39. * specified by the \c int_rep field of the modulus.
  40. * - **Parameter ordering**: for bignum parameters, outputs come before inputs.
  41. * The modulus is passed after residues. Temporaries come last.
  42. * - **Aliasing**: in general, output bignums may be aliased to one or more
  43. * inputs. Modulus values may not be aliased to any other parameter. Outputs
  44. * may not be aliased to one another. Temporaries may not be aliased to any
  45. * other parameter.
  46. * - **Overlap**: apart from aliasing of residue pointers (where two residue
  47. * arguments are equal pointers), overlap is not supported and may result
  48. * in undefined behavior.
  49. * - **Error handling**: functions generally check compatibility of input
  50. * sizes. Most functions will not check that input values are in canonical
  51. * form (i.e. that \c A < \c N), this is only checked during setup of a
  52. * residue structure.
  53. * - **Modular representatives**: all functions expect inputs to be in the
  54. * range [0, \c N - 1] and guarantee outputs in the range [0, \c N - 1].
  55. * Residues are set up with an associated modulus, and operations are only
  56. * guaranteed to work if the modulus is associated with all residue
  57. * parameters. If a residue is passed with a modulus other than the one it
  58. * is associated with, then it may be out of range. If an input is out of
  59. * range, outputs are fully unspecified, though bignum values out of range
  60. * should not cause buffer overflows (beware that this is not extensively
  61. * tested).
  62. */
  63. /*
  64. * Copyright The Mbed TLS Contributors
  65. * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  66. */
  67. #ifndef MBEDTLS_BIGNUM_MOD_H
  68. #define MBEDTLS_BIGNUM_MOD_H
  69. #include "common.h"
  70. #if defined(MBEDTLS_BIGNUM_C)
  71. #include "mbedtls/bignum.h"
  72. #endif
  73. /** How residues associated with a modulus are represented.
  74. *
  75. * This also determines which fields of the modulus structure are valid and
  76. * what their contents are (see #mbedtls_mpi_mod_modulus).
  77. */
  78. typedef enum {
  79. /** Representation not chosen (makes the modulus structure invalid). */
  80. MBEDTLS_MPI_MOD_REP_INVALID = 0,
  81. /* Skip 1 as it is slightly easier to accidentally pass to functions. */
  82. /** Montgomery representation. */
  83. MBEDTLS_MPI_MOD_REP_MONTGOMERY = 2,
  84. /* Optimised reduction available. This indicates a coordinate modulus (P)
  85. * and one or more of the following have been configured:
  86. * - A nist curve (MBEDTLS_ECP_DP_SECPXXXR1_ENABLED) & MBEDTLS_ECP_NIST_OPTIM.
  87. * - A Kobliz Curve.
  88. * - A Fast Reduction Curve CURVE25519 or CURVE448. */
  89. MBEDTLS_MPI_MOD_REP_OPT_RED,
  90. } mbedtls_mpi_mod_rep_selector;
  91. /* Make mbedtls_mpi_mod_rep_selector and mbedtls_mpi_mod_ext_rep disjoint to
  92. * make it easier to catch when they are accidentally swapped. */
  93. typedef enum {
  94. MBEDTLS_MPI_MOD_EXT_REP_INVALID = 0,
  95. MBEDTLS_MPI_MOD_EXT_REP_LE = 8,
  96. MBEDTLS_MPI_MOD_EXT_REP_BE
  97. } mbedtls_mpi_mod_ext_rep;
  98. typedef struct {
  99. mbedtls_mpi_uint *p;
  100. size_t limbs;
  101. } mbedtls_mpi_mod_residue;
  102. typedef struct {
  103. mbedtls_mpi_uint const *rr; /* The residue for 2^{2*n*biL} mod N */
  104. mbedtls_mpi_uint mm; /* Montgomery const for -N^{-1} mod 2^{ciL} */
  105. } mbedtls_mpi_mont_struct;
  106. typedef int (*mbedtls_mpi_modp_fn)(mbedtls_mpi_uint *X, size_t X_limbs);
  107. typedef struct {
  108. mbedtls_mpi_modp_fn modp; /* The optimised reduction function pointer */
  109. } mbedtls_mpi_opt_red_struct;
  110. typedef struct {
  111. const mbedtls_mpi_uint *p;
  112. size_t limbs; // number of limbs
  113. size_t bits; // bitlen of p
  114. mbedtls_mpi_mod_rep_selector int_rep; // selector to signal the active member of the union
  115. union rep {
  116. /* if int_rep == #MBEDTLS_MPI_MOD_REP_MONTGOMERY */
  117. mbedtls_mpi_mont_struct mont;
  118. /* if int_rep == #MBEDTLS_MPI_MOD_REP_OPT_RED */
  119. mbedtls_mpi_opt_red_struct ored;
  120. } rep;
  121. } mbedtls_mpi_mod_modulus;
  122. /** Setup a residue structure.
  123. *
  124. * The residue will be set up with the buffer \p p and modulus \p N.
  125. *
  126. * The memory pointed to by \p p will be used by the resulting residue structure.
  127. * The value at the pointed-to memory will be the initial value of \p r and must
  128. * hold a value that is less than the modulus. This value will be used as-is
  129. * and interpreted according to the value of the `N->int_rep` field.
  130. *
  131. * The modulus \p N will be the modulus associated with \p r. The residue \p r
  132. * should only be used in operations where the modulus is \p N.
  133. *
  134. * \param[out] r The address of the residue to setup.
  135. * \param[in] N The address of the modulus related to \p r.
  136. * \param[in] p The address of the limb array containing the value of \p r.
  137. * The memory pointed to by \p p will be used by \p r and must
  138. * not be modified in any way until after
  139. * mbedtls_mpi_mod_residue_release() is called. The data
  140. * pointed to by \p p must be less than the modulus (the value
  141. * pointed to by `N->p`) and already in the representation
  142. * indicated by `N->int_rep`.
  143. * \param p_limbs The number of limbs of \p p. Must be the same as the number
  144. * of limbs in the modulus \p N.
  145. *
  146. * \return \c 0 if successful.
  147. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p p_limbs is less than the
  148. * limbs in \p N or if \p p is not less than \p N.
  149. */
  150. int mbedtls_mpi_mod_residue_setup(mbedtls_mpi_mod_residue *r,
  151. const mbedtls_mpi_mod_modulus *N,
  152. mbedtls_mpi_uint *p,
  153. size_t p_limbs);
  154. /** Unbind elements of a residue structure.
  155. *
  156. * This function removes the reference to the limb array that was passed to
  157. * mbedtls_mpi_mod_residue_setup() to make it safe to free or use again.
  158. *
  159. * This function invalidates \p r and it must not be used until after
  160. * mbedtls_mpi_mod_residue_setup() is called on it again.
  161. *
  162. * \param[out] r The address of residue to release.
  163. */
  164. void mbedtls_mpi_mod_residue_release(mbedtls_mpi_mod_residue *r);
  165. /** Initialize a modulus structure.
  166. *
  167. * \param[out] N The address of the modulus structure to initialize.
  168. */
  169. void mbedtls_mpi_mod_modulus_init(mbedtls_mpi_mod_modulus *N);
  170. /** Setup a modulus structure.
  171. *
  172. * \param[out] N The address of the modulus structure to populate.
  173. * \param[in] p The address of the limb array storing the value of \p N.
  174. * The memory pointed to by \p p will be used by \p N and must
  175. * not be modified in any way until after
  176. * mbedtls_mpi_mod_modulus_free() is called.
  177. * \param p_limbs The number of limbs of \p p.
  178. *
  179. * \return \c 0 if successful.
  180. */
  181. int mbedtls_mpi_mod_modulus_setup(mbedtls_mpi_mod_modulus *N,
  182. const mbedtls_mpi_uint *p,
  183. size_t p_limbs);
  184. /** Setup an optimised-reduction compatible modulus structure.
  185. *
  186. * \param[out] N The address of the modulus structure to populate.
  187. * \param[in] p The address of the limb array storing the value of \p N.
  188. * The memory pointed to by \p p will be used by \p N and must
  189. * not be modified in any way until after
  190. * mbedtls_mpi_mod_modulus_free() is called.
  191. * \param p_limbs The number of limbs of \p p.
  192. * \param modp A pointer to the optimised reduction function to use. \p p.
  193. *
  194. * \return \c 0 if successful.
  195. */
  196. int mbedtls_mpi_mod_optred_modulus_setup(mbedtls_mpi_mod_modulus *N,
  197. const mbedtls_mpi_uint *p,
  198. size_t p_limbs,
  199. mbedtls_mpi_modp_fn modp);
  200. /** Free elements of a modulus structure.
  201. *
  202. * This function frees any memory allocated by mbedtls_mpi_mod_modulus_setup().
  203. *
  204. * \warning This function does not free the limb array passed to
  205. * mbedtls_mpi_mod_modulus_setup() only removes the reference to it,
  206. * making it safe to free or to use it again.
  207. *
  208. * \param[in,out] N The address of the modulus structure to free.
  209. */
  210. void mbedtls_mpi_mod_modulus_free(mbedtls_mpi_mod_modulus *N);
  211. /** \brief Multiply two residues, returning the residue modulo the specified
  212. * modulus.
  213. *
  214. * \note Currently handles the case when `N->int_rep` is
  215. * MBEDTLS_MPI_MOD_REP_MONTGOMERY.
  216. *
  217. * The size of the operation is determined by \p N. \p A, \p B and \p X must
  218. * all be associated with the modulus \p N and must all have the same number
  219. * of limbs as \p N.
  220. *
  221. * \p X may be aliased to \p A or \p B, or even both, but may not overlap
  222. * either otherwise. They may not alias \p N (since they must be in canonical
  223. * form, they cannot == \p N).
  224. *
  225. * \param[out] X The address of the result MPI. Must have the same
  226. * number of limbs as \p N.
  227. * On successful completion, \p X contains the result of
  228. * the multiplication `A * B * R^-1` mod N where
  229. * `R = 2^(biL * N->limbs)`.
  230. * \param[in] A The address of the first MPI.
  231. * \param[in] B The address of the second MPI.
  232. * \param[in] N The address of the modulus. Used to perform a modulo
  233. * operation on the result of the multiplication.
  234. *
  235. * \return \c 0 if successful.
  236. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if all the parameters do not
  237. * have the same number of limbs or \p N is invalid.
  238. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.
  239. */
  240. int mbedtls_mpi_mod_mul(mbedtls_mpi_mod_residue *X,
  241. const mbedtls_mpi_mod_residue *A,
  242. const mbedtls_mpi_mod_residue *B,
  243. const mbedtls_mpi_mod_modulus *N);
  244. /**
  245. * \brief Perform a fixed-size modular subtraction.
  246. *
  247. * Calculate `A - B modulo N`.
  248. *
  249. * \p A, \p B and \p X must all have the same number of limbs as \p N.
  250. *
  251. * \p X may be aliased to \p A or \p B, or even both, but may not overlap
  252. * either otherwise.
  253. *
  254. * \note This function does not check that \p A or \p B are in canonical
  255. * form (that is, are < \p N) - that will have been done by
  256. * mbedtls_mpi_mod_residue_setup().
  257. *
  258. * \param[out] X The address of the result MPI. Must be initialized.
  259. * Must have the same number of limbs as the modulus \p N.
  260. * \param[in] A The address of the first MPI.
  261. * \param[in] B The address of the second MPI.
  262. * \param[in] N The address of the modulus. Used to perform a modulo
  263. * operation on the result of the subtraction.
  264. *
  265. * \return \c 0 if successful.
  266. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if the given MPIs do not
  267. * have the correct number of limbs.
  268. */
  269. int mbedtls_mpi_mod_sub(mbedtls_mpi_mod_residue *X,
  270. const mbedtls_mpi_mod_residue *A,
  271. const mbedtls_mpi_mod_residue *B,
  272. const mbedtls_mpi_mod_modulus *N);
  273. /**
  274. * \brief Perform modular inversion of an MPI with respect to a modulus \p N.
  275. *
  276. * \p A and \p X must be associated with the modulus \p N and will therefore
  277. * have the same number of limbs as \p N.
  278. *
  279. * \p X may be aliased to \p A.
  280. *
  281. * \warning Currently only supports prime moduli, but does not check for them.
  282. *
  283. * \param[out] X The modular inverse of \p A with respect to \p N.
  284. * \param[in] A The number to calculate the modular inverse of.
  285. * Must not be 0.
  286. * \param[in] N The modulus to use.
  287. *
  288. * \return \c 0 if successful.
  289. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p A and \p N do not
  290. * have the same number of limbs.
  291. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p A is zero.
  292. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if couldn't allocate enough
  293. * memory (needed for conversion to and from Mongtomery form
  294. * when not in Montgomery form already, and for temporary use
  295. * by the inversion calculation itself).
  296. */
  297. int mbedtls_mpi_mod_inv(mbedtls_mpi_mod_residue *X,
  298. const mbedtls_mpi_mod_residue *A,
  299. const mbedtls_mpi_mod_modulus *N);
  300. /**
  301. * \brief Perform a fixed-size modular addition.
  302. *
  303. * Calculate `A + B modulo N`.
  304. *
  305. * \p A, \p B and \p X must all be associated with the modulus \p N and must
  306. * all have the same number of limbs as \p N.
  307. *
  308. * \p X may be aliased to \p A or \p B, or even both, but may not overlap
  309. * either otherwise.
  310. *
  311. * \note This function does not check that \p A or \p B are in canonical
  312. * form (that is, are < \p N) - that will have been done by
  313. * mbedtls_mpi_mod_residue_setup().
  314. *
  315. * \param[out] X The address of the result residue. Must be initialized.
  316. * Must have the same number of limbs as the modulus \p N.
  317. * \param[in] A The address of the first input residue.
  318. * \param[in] B The address of the second input residue.
  319. * \param[in] N The address of the modulus. Used to perform a modulo
  320. * operation on the result of the addition.
  321. *
  322. * \return \c 0 if successful.
  323. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if the given MPIs do not
  324. * have the correct number of limbs.
  325. */
  326. int mbedtls_mpi_mod_add(mbedtls_mpi_mod_residue *X,
  327. const mbedtls_mpi_mod_residue *A,
  328. const mbedtls_mpi_mod_residue *B,
  329. const mbedtls_mpi_mod_modulus *N);
  330. /** Generate a random number uniformly in a range.
  331. *
  332. * This function generates a random number between \p min inclusive and
  333. * \p N exclusive.
  334. *
  335. * The procedure complies with RFC 6979 §3.3 (deterministic ECDSA)
  336. * when the RNG is a suitably parametrized instance of HMAC_DRBG
  337. * and \p min is \c 1.
  338. *
  339. * \note There are `N - min` possible outputs. The lower bound
  340. * \p min can be reached, but the upper bound \p N cannot.
  341. *
  342. * \param X The destination residue.
  343. * \param min The minimum value to return. It must be strictly smaller
  344. * than \b N.
  345. * \param N The modulus.
  346. * This is the upper bound of the output range, exclusive.
  347. * \param f_rng The RNG function to use. This must not be \c NULL.
  348. * \param p_rng The RNG parameter to be passed to \p f_rng.
  349. *
  350. * \return \c 0 if successful.
  351. * \return #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if the implementation was
  352. * unable to find a suitable value within a limited number
  353. * of attempts. This has a negligible probability if \p N
  354. * is significantly larger than \p min, which is the case
  355. * for all usual cryptographic applications.
  356. */
  357. int mbedtls_mpi_mod_random(mbedtls_mpi_mod_residue *X,
  358. mbedtls_mpi_uint min,
  359. const mbedtls_mpi_mod_modulus *N,
  360. int (*f_rng)(void *, unsigned char *, size_t),
  361. void *p_rng);
  362. /** Read a residue from a byte buffer.
  363. *
  364. * The residue will be automatically converted to the internal representation
  365. * based on the value of the `N->int_rep` field.
  366. *
  367. * The modulus \p N will be the modulus associated with \p r. The residue \p r
  368. * should only be used in operations where the modulus is \p N or a modulus
  369. * equivalent to \p N (in the sense that all their fields or memory pointed by
  370. * their fields hold the same value).
  371. *
  372. * \param[out] r The address of the residue. It must have exactly the same
  373. * number of limbs as the modulus \p N.
  374. * \param[in] N The address of the modulus.
  375. * \param[in] buf The input buffer to import from.
  376. * \param buflen The length in bytes of \p buf.
  377. * \param ext_rep The endianness of the number in the input buffer.
  378. *
  379. * \return \c 0 if successful.
  380. * \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p r isn't
  381. * large enough to hold the value in \p buf.
  382. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p ext_rep
  383. * is invalid or the value in the buffer is not less than \p N.
  384. */
  385. int mbedtls_mpi_mod_read(mbedtls_mpi_mod_residue *r,
  386. const mbedtls_mpi_mod_modulus *N,
  387. const unsigned char *buf,
  388. size_t buflen,
  389. mbedtls_mpi_mod_ext_rep ext_rep);
  390. /** Write a residue into a byte buffer.
  391. *
  392. * The modulus \p N must be the modulus associated with \p r (see
  393. * mbedtls_mpi_mod_residue_setup() and mbedtls_mpi_mod_read()).
  394. *
  395. * The residue will be automatically converted from the internal representation
  396. * based on the value of `N->int_rep` field.
  397. *
  398. * \warning If the buffer is smaller than `N->bits`, the number of
  399. * leading zeroes is leaked through timing. If \p r is
  400. * secret, the caller must ensure that \p buflen is at least
  401. * (`N->bits`+7)/8.
  402. *
  403. * \param[in] r The address of the residue. It must have the same number of
  404. * limbs as the modulus \p N. (\p r is an input parameter, but
  405. * its value will be modified during execution and restored
  406. * before the function returns.)
  407. * \param[in] N The address of the modulus associated with \p r.
  408. * \param[out] buf The output buffer to export to.
  409. * \param buflen The length in bytes of \p buf.
  410. * \param ext_rep The endianness in which the number should be written into
  411. * the output buffer.
  412. *
  413. * \return \c 0 if successful.
  414. * \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p buf isn't
  415. * large enough to hold the value of \p r (without leading
  416. * zeroes).
  417. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p ext_rep is invalid.
  418. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if couldn't allocate enough
  419. * memory for conversion. Can occur only for moduli with
  420. * MBEDTLS_MPI_MOD_REP_MONTGOMERY.
  421. */
  422. int mbedtls_mpi_mod_write(const mbedtls_mpi_mod_residue *r,
  423. const mbedtls_mpi_mod_modulus *N,
  424. unsigned char *buf,
  425. size_t buflen,
  426. mbedtls_mpi_mod_ext_rep ext_rep);
  427. #endif /* MBEDTLS_BIGNUM_MOD_H */