bignum_mod.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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
  66. *
  67. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  68. * not use this file except in compliance with the License.
  69. * You may obtain a copy of the License at
  70. *
  71. * http://www.apache.org/licenses/LICENSE-2.0
  72. *
  73. * Unless required by applicable law or agreed to in writing, software
  74. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  75. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  76. * See the License for the specific language governing permissions and
  77. * limitations under the License.
  78. */
  79. #ifndef MBEDTLS_BIGNUM_MOD_H
  80. #define MBEDTLS_BIGNUM_MOD_H
  81. #include "common.h"
  82. #if defined(MBEDTLS_BIGNUM_C)
  83. #include "mbedtls/bignum.h"
  84. #endif
  85. /** How residues associated with a modulus are represented.
  86. *
  87. * This also determines which fields of the modulus structure are valid and
  88. * what their contents are (see #mbedtls_mpi_mod_modulus).
  89. */
  90. typedef enum {
  91. /** Representation not chosen (makes the modulus structure invalid). */
  92. MBEDTLS_MPI_MOD_REP_INVALID = 0,
  93. /* Skip 1 as it is slightly easier to accidentally pass to functions. */
  94. /** Montgomery representation. */
  95. MBEDTLS_MPI_MOD_REP_MONTGOMERY = 2,
  96. /** TODO: document this.
  97. *
  98. * Residues are in canonical representation.
  99. */
  100. MBEDTLS_MPI_MOD_REP_OPT_RED,
  101. } mbedtls_mpi_mod_rep_selector;
  102. /* Make mbedtls_mpi_mod_rep_selector and mbedtls_mpi_mod_ext_rep disjoint to
  103. * make it easier to catch when they are accidentally swapped. */
  104. typedef enum {
  105. MBEDTLS_MPI_MOD_EXT_REP_INVALID = 0,
  106. MBEDTLS_MPI_MOD_EXT_REP_LE = 8,
  107. MBEDTLS_MPI_MOD_EXT_REP_BE
  108. } mbedtls_mpi_mod_ext_rep;
  109. typedef struct {
  110. mbedtls_mpi_uint *p;
  111. size_t limbs;
  112. } mbedtls_mpi_mod_residue;
  113. typedef struct {
  114. mbedtls_mpi_uint const *rr; /* The residue for 2^{2*n*biL} mod N */
  115. mbedtls_mpi_uint mm; /* Montgomery const for -N^{-1} mod 2^{ciL} */
  116. } mbedtls_mpi_mont_struct;
  117. typedef void *mbedtls_mpi_opt_red_struct;
  118. typedef struct {
  119. const mbedtls_mpi_uint *p;
  120. size_t limbs; // number of limbs
  121. size_t bits; // bitlen of p
  122. mbedtls_mpi_mod_rep_selector int_rep; // selector to signal the active member of the union
  123. union rep {
  124. /* if int_rep == #MBEDTLS_MPI_MOD_REP_MONTGOMERY */
  125. mbedtls_mpi_mont_struct mont;
  126. /* if int_rep == #MBEDTLS_MPI_MOD_REP_OPT_RED */
  127. mbedtls_mpi_opt_red_struct ored;
  128. } rep;
  129. } mbedtls_mpi_mod_modulus;
  130. /** Setup a residue structure.
  131. *
  132. * The residue will be set up with the buffer \p p and modulus \p N.
  133. *
  134. * The memory pointed to by \p p will be used by the resulting residue structure.
  135. * The value at the pointed-to memory will be the initial value of \p r and must
  136. * hold a value that is less than the modulus. This value will be used as-is
  137. * and interpreted according to the value of the `N->int_rep` field.
  138. *
  139. * The modulus \p N will be the modulus associated with \p r. The residue \p r
  140. * should only be used in operations where the modulus is \p N.
  141. *
  142. * \param[out] r The address of the residue to setup.
  143. * \param[in] N The address of the modulus related to \p r.
  144. * \param[in] p The address of the limb array containing the value of \p r.
  145. * The memory pointed to by \p p will be used by \p r and must
  146. * not be modified in any way until after
  147. * mbedtls_mpi_mod_residue_release() is called. The data
  148. * pointed to by \p p must be less than the modulus (the value
  149. * pointed to by `N->p`) and already in the representation
  150. * indicated by `N->int_rep`.
  151. * \param p_limbs The number of limbs of \p p. Must be the same as the number
  152. * of limbs in the modulus \p N.
  153. *
  154. * \return \c 0 if successful.
  155. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p p_limbs is less than the
  156. * limbs in \p N or if \p p is not less than \p N.
  157. */
  158. int mbedtls_mpi_mod_residue_setup(mbedtls_mpi_mod_residue *r,
  159. const mbedtls_mpi_mod_modulus *N,
  160. mbedtls_mpi_uint *p,
  161. size_t p_limbs);
  162. /** Unbind elements of a residue structure.
  163. *
  164. * This function removes the reference to the limb array that was passed to
  165. * mbedtls_mpi_mod_residue_setup() to make it safe to free or use again.
  166. *
  167. * This function invalidates \p r and it must not be used until after
  168. * mbedtls_mpi_mod_residue_setup() is called on it again.
  169. *
  170. * \param[out] r The address of residue to release.
  171. */
  172. void mbedtls_mpi_mod_residue_release(mbedtls_mpi_mod_residue *r);
  173. /** Initialize a modulus structure.
  174. *
  175. * \param[out] N The address of the modulus structure to initialize.
  176. */
  177. void mbedtls_mpi_mod_modulus_init(mbedtls_mpi_mod_modulus *N);
  178. /** Setup a modulus structure.
  179. *
  180. * \param[out] N The address of the modulus structure to populate.
  181. * \param[in] p The address of the limb array storing the value of \p N.
  182. * The memory pointed to by \p p will be used by \p N and must
  183. * not be modified in any way until after
  184. * mbedtls_mpi_mod_modulus_free() is called.
  185. * \param p_limbs The number of limbs of \p p.
  186. * \param int_rep The internal representation to be used for residues
  187. * associated with \p N (see #mbedtls_mpi_mod_rep_selector).
  188. *
  189. * \return \c 0 if successful.
  190. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p int_rep is invalid.
  191. */
  192. int mbedtls_mpi_mod_modulus_setup(mbedtls_mpi_mod_modulus *N,
  193. const mbedtls_mpi_uint *p,
  194. size_t p_limbs,
  195. mbedtls_mpi_mod_rep_selector int_rep);
  196. /** Free elements of a modulus structure.
  197. *
  198. * This function frees any memory allocated by mbedtls_mpi_mod_modulus_setup().
  199. *
  200. * \warning This function does not free the limb array passed to
  201. * mbedtls_mpi_mod_modulus_setup() only removes the reference to it,
  202. * making it safe to free or to use it again.
  203. *
  204. * \param[in,out] N The address of the modulus structure to free.
  205. */
  206. void mbedtls_mpi_mod_modulus_free(mbedtls_mpi_mod_modulus *N);
  207. /* BEGIN MERGE SLOT 1 */
  208. /* END MERGE SLOT 1 */
  209. /* BEGIN MERGE SLOT 2 */
  210. /** \brief Multiply two residues, returning the residue modulo the specified
  211. * modulus.
  212. *
  213. * \note Currently handles the case when `N->int_rep` is
  214. * MBEDTLS_MPI_MOD_REP_MONTGOMERY.
  215. *
  216. * The size of the operation is determined by \p N. \p A, \p B and \p X must
  217. * all be associated with the modulus \p N and must all have the same number
  218. * of limbs as \p N.
  219. *
  220. * \p X may be aliased to \p A or \p B, or even both, but may not overlap
  221. * either otherwise. They may not alias \p N (since they must be in canonical
  222. * form, they cannot == \p N).
  223. *
  224. * \param[out] X The address of the result MPI. Must have the same
  225. * number of limbs as \p N.
  226. * On successful completion, \p X contains the result of
  227. * the multiplication `A * B * R^-1` mod N where
  228. * `R = 2^(biL * N->limbs)`.
  229. * \param[in] A The address of the first MPI.
  230. * \param[in] B The address of the second MPI.
  231. * \param[in] N The address of the modulus. Used to perform a modulo
  232. * operation on the result of the multiplication.
  233. *
  234. * \return \c 0 if successful.
  235. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if all the parameters do not
  236. * have the same number of limbs or \p N is invalid.
  237. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.
  238. */
  239. int mbedtls_mpi_mod_mul(mbedtls_mpi_mod_residue *X,
  240. const mbedtls_mpi_mod_residue *A,
  241. const mbedtls_mpi_mod_residue *B,
  242. const mbedtls_mpi_mod_modulus *N);
  243. /* END MERGE SLOT 2 */
  244. /* BEGIN MERGE SLOT 3 */
  245. /**
  246. * \brief Perform a fixed-size modular subtraction.
  247. *
  248. * Calculate `A - B modulo N`.
  249. *
  250. * \p A, \p B and \p X must all have the same number of limbs as \p N.
  251. *
  252. * \p X may be aliased to \p A or \p B, or even both, but may not overlap
  253. * either otherwise.
  254. *
  255. * \note This function does not check that \p A or \p B are in canonical
  256. * form (that is, are < \p N) - that will have been done by
  257. * mbedtls_mpi_mod_residue_setup().
  258. *
  259. * \param[out] X The address of the result MPI. Must be initialized.
  260. * Must have the same number of limbs as the modulus \p N.
  261. * \param[in] A The address of the first MPI.
  262. * \param[in] B The address of the second MPI.
  263. * \param[in] N The address of the modulus. Used to perform a modulo
  264. * operation on the result of the subtraction.
  265. *
  266. * \return \c 0 if successful.
  267. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if the given MPIs do not
  268. * have the correct number of limbs.
  269. */
  270. int mbedtls_mpi_mod_sub(mbedtls_mpi_mod_residue *X,
  271. const mbedtls_mpi_mod_residue *A,
  272. const mbedtls_mpi_mod_residue *B,
  273. const mbedtls_mpi_mod_modulus *N);
  274. /**
  275. * \brief Perform modular inversion of an MPI with respect to a modulus \p N.
  276. *
  277. * \p A and \p X must be associated with the modulus \p N and will therefore
  278. * have the same number of limbs as \p N.
  279. *
  280. * \p X may be aliased to \p A.
  281. *
  282. * \warning Currently only supports prime moduli, but does not check for them.
  283. *
  284. * \param[out] X The modular inverse of \p A with respect to \p N.
  285. * \param[in] A The number to calculate the modular inverse of.
  286. * Must not be 0.
  287. * \param[in] N The modulus to use.
  288. *
  289. * \return \c 0 if successful.
  290. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p A and \p N do not
  291. * have the same number of limbs.
  292. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p A is zero.
  293. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if couldn't allocate enough
  294. * memory (needed for conversion to and from Mongtomery form
  295. * when not in Montgomery form already, and for temporary use
  296. * by the inversion calculation itself).
  297. */
  298. int mbedtls_mpi_mod_inv(mbedtls_mpi_mod_residue *X,
  299. const mbedtls_mpi_mod_residue *A,
  300. const mbedtls_mpi_mod_modulus *N);
  301. /* END MERGE SLOT 3 */
  302. /* BEGIN MERGE SLOT 4 */
  303. /* END MERGE SLOT 4 */
  304. /* BEGIN MERGE SLOT 5 */
  305. /**
  306. * \brief Perform a fixed-size modular addition.
  307. *
  308. * Calculate `A + B modulo N`.
  309. *
  310. * \p A, \p B and \p X must all be associated with the modulus \p N and must
  311. * all have the same number of limbs as \p N.
  312. *
  313. * \p X may be aliased to \p A or \p B, or even both, but may not overlap
  314. * either otherwise.
  315. *
  316. * \note This function does not check that \p A or \p B are in canonical
  317. * form (that is, are < \p N) - that will have been done by
  318. * mbedtls_mpi_mod_residue_setup().
  319. *
  320. * \param[out] X The address of the result residue. Must be initialized.
  321. * Must have the same number of limbs as the modulus \p N.
  322. * \param[in] A The address of the first input residue.
  323. * \param[in] B The address of the second input residue.
  324. * \param[in] N The address of the modulus. Used to perform a modulo
  325. * operation on the result of the addition.
  326. *
  327. * \return \c 0 if successful.
  328. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if the given MPIs do not
  329. * have the correct number of limbs.
  330. */
  331. int mbedtls_mpi_mod_add(mbedtls_mpi_mod_residue *X,
  332. const mbedtls_mpi_mod_residue *A,
  333. const mbedtls_mpi_mod_residue *B,
  334. const mbedtls_mpi_mod_modulus *N);
  335. /* END MERGE SLOT 5 */
  336. /* BEGIN MERGE SLOT 6 */
  337. /** Generate a random number uniformly in a range.
  338. *
  339. * This function generates a random number between \p min inclusive and
  340. * \p N exclusive.
  341. *
  342. * The procedure complies with RFC 6979 §3.3 (deterministic ECDSA)
  343. * when the RNG is a suitably parametrized instance of HMAC_DRBG
  344. * and \p min is \c 1.
  345. *
  346. * \note There are `N - min` possible outputs. The lower bound
  347. * \p min can be reached, but the upper bound \p N cannot.
  348. *
  349. * \param X The destination residue.
  350. * \param min The minimum value to return. It must be strictly smaller
  351. * than \b N.
  352. * \param N The modulus.
  353. * This is the upper bound of the output range, exclusive.
  354. * \param f_rng The RNG function to use. This must not be \c NULL.
  355. * \param p_rng The RNG parameter to be passed to \p f_rng.
  356. *
  357. * \return \c 0 if successful.
  358. * \return #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if the implementation was
  359. * unable to find a suitable value within a limited number
  360. * of attempts. This has a negligible probability if \p N
  361. * is significantly larger than \p min, which is the case
  362. * for all usual cryptographic applications.
  363. */
  364. int mbedtls_mpi_mod_random(mbedtls_mpi_mod_residue *X,
  365. mbedtls_mpi_uint min,
  366. const mbedtls_mpi_mod_modulus *N,
  367. int (*f_rng)(void *, unsigned char *, size_t),
  368. void *p_rng);
  369. /* END MERGE SLOT 6 */
  370. /* BEGIN MERGE SLOT 7 */
  371. /** Read a residue from a byte buffer.
  372. *
  373. * The residue will be automatically converted to the internal representation
  374. * based on the value of the `N->int_rep` field.
  375. *
  376. * The modulus \p N will be the modulus associated with \p r. The residue \p r
  377. * should only be used in operations where the modulus is \p N or a modulus
  378. * equivalent to \p N (in the sense that all their fields or memory pointed by
  379. * their fields hold the same value).
  380. *
  381. * \param[out] r The address of the residue. It must have exactly the same
  382. * number of limbs as the modulus \p N.
  383. * \param[in] N The address of the modulus.
  384. * \param[in] buf The input buffer to import from.
  385. * \param buflen The length in bytes of \p buf.
  386. * \param ext_rep The endianness of the number in the input buffer.
  387. *
  388. * \return \c 0 if successful.
  389. * \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p r isn't
  390. * large enough to hold the value in \p buf.
  391. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p ext_rep
  392. * is invalid or the value in the buffer is not less than \p N.
  393. */
  394. int mbedtls_mpi_mod_read(mbedtls_mpi_mod_residue *r,
  395. const mbedtls_mpi_mod_modulus *N,
  396. const unsigned char *buf,
  397. size_t buflen,
  398. mbedtls_mpi_mod_ext_rep ext_rep);
  399. /** Write a residue into a byte buffer.
  400. *
  401. * The modulus \p N must be the modulus associated with \p r (see
  402. * mbedtls_mpi_mod_residue_setup() and mbedtls_mpi_mod_read()).
  403. *
  404. * The residue will be automatically converted from the internal representation
  405. * based on the value of `N->int_rep` field.
  406. *
  407. * \warning If the buffer is smaller than `N->bits`, the number of
  408. * leading zeroes is leaked through timing. If \p r is
  409. * secret, the caller must ensure that \p buflen is at least
  410. * (`N->bits`+7)/8.
  411. *
  412. * \param[in] r The address of the residue. It must have the same number of
  413. * limbs as the modulus \p N. (\p r is an input parameter, but
  414. * its value will be modified during execution and restored
  415. * before the function returns.)
  416. * \param[in] N The address of the modulus associated with \p r.
  417. * \param[out] buf The output buffer to export to.
  418. * \param buflen The length in bytes of \p buf.
  419. * \param ext_rep The endianness in which the number should be written into
  420. * the output buffer.
  421. *
  422. * \return \c 0 if successful.
  423. * \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p buf isn't
  424. * large enough to hold the value of \p r (without leading
  425. * zeroes).
  426. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p ext_rep is invalid.
  427. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if couldn't allocate enough
  428. * memory for conversion. Can occur only for moduli with
  429. * MBEDTLS_MPI_MOD_REP_MONTGOMERY.
  430. */
  431. int mbedtls_mpi_mod_write(const mbedtls_mpi_mod_residue *r,
  432. const mbedtls_mpi_mod_modulus *N,
  433. unsigned char *buf,
  434. size_t buflen,
  435. mbedtls_mpi_mod_ext_rep ext_rep);
  436. /* END MERGE SLOT 7 */
  437. /* BEGIN MERGE SLOT 8 */
  438. /* END MERGE SLOT 8 */
  439. /* BEGIN MERGE SLOT 9 */
  440. /* END MERGE SLOT 9 */
  441. /* BEGIN MERGE SLOT 10 */
  442. /* END MERGE SLOT 10 */
  443. #endif /* MBEDTLS_BIGNUM_MOD_H */