bignum_core.h 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. /**
  2. * Core bignum functions
  3. *
  4. * This interface should only be used by the legacy bignum module (bignum.h)
  5. * and the modular bignum modules (bignum_mod.c, bignum_mod_raw.c). All other
  6. * modules should use the high-level modular bignum interface (bignum_mod.h)
  7. * or the legacy bignum interface (bignum.h).
  8. *
  9. * This module is about processing non-negative integers with a fixed upper
  10. * bound that's of the form 2^n-1 where n is a multiple of #biL.
  11. * These can be thought of integers written in base 2^#biL with a fixed
  12. * number of digits. Digits in this base are called *limbs*.
  13. * Many operations treat these numbers as the principal representation of
  14. * a number modulo 2^n or a smaller bound.
  15. *
  16. * The functions in this module obey the following conventions unless
  17. * explicitly indicated otherwise:
  18. *
  19. * - **Overflow**: some functions indicate overflow from the range
  20. * [0, 2^n-1] by returning carry parameters, while others operate
  21. * modulo and so cannot overflow. This should be clear from the function
  22. * documentation.
  23. * - **Bignum parameters**: Bignums are passed as pointers to an array of
  24. * limbs. A limb has the type #mbedtls_mpi_uint. Unless otherwise specified:
  25. * - Bignum parameters called \p A, \p B, ... are inputs, and are
  26. * not modified by the function.
  27. * - For operations modulo some number, the modulus is called \p N
  28. * and is input-only.
  29. * - Bignum parameters called \p X, \p Y are outputs or input-output.
  30. * The initial content of output-only parameters is ignored.
  31. * - Some functions use different names that reflect traditional
  32. * naming of operands of certain operations (e.g.
  33. * divisor/dividend/quotient/remainder).
  34. * - \p T is a temporary storage area. The initial content of such
  35. * parameter is ignored and the final content is unspecified.
  36. * - **Bignum sizes**: bignum sizes are always expressed in limbs.
  37. * Most functions work on bignums of a given size and take a single
  38. * \p limbs parameter that applies to all parameters that are limb arrays.
  39. * All bignum sizes must be at least 1 and must be significantly less than
  40. * #SIZE_MAX. The behavior if a size is 0 is undefined. The behavior if the
  41. * total size of all parameters overflows #SIZE_MAX is undefined.
  42. * - **Parameter ordering**: for bignum parameters, outputs come before inputs.
  43. * Temporaries come last.
  44. * - **Aliasing**: in general, output bignums may be aliased to one or more
  45. * inputs. As an exception, parameters that are documented as a modulus value
  46. * may not be aliased to an output. Outputs may not be aliased to one another.
  47. * Temporaries may not be aliased to any other parameter.
  48. * - **Overlap**: apart from aliasing of limb array pointers (where two
  49. * arguments are equal pointers), overlap is not supported and may result
  50. * in undefined behavior.
  51. * - **Error handling**: This is a low-level module. Functions generally do not
  52. * try to protect against invalid arguments such as nonsensical sizes or
  53. * null pointers. Note that some functions that operate on bignums of
  54. * different sizes have constraints about their size, and violating those
  55. * constraints may lead to buffer overflows.
  56. * - **Modular representatives**: functions that operate modulo \p N expect
  57. * all modular inputs to be in the range [0, \p N - 1] and guarantee outputs
  58. * in the range [0, \p N - 1]. If an input is out of range, outputs are
  59. * fully unspecified, though bignum values out of range should not cause
  60. * buffer overflows (beware that this is not extensively tested).
  61. */
  62. /*
  63. * Copyright The Mbed TLS Contributors
  64. * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  65. */
  66. #ifndef MBEDTLS_BIGNUM_CORE_H
  67. #define MBEDTLS_BIGNUM_CORE_H
  68. #include "common.h"
  69. #if defined(MBEDTLS_BIGNUM_C)
  70. #include "mbedtls/bignum.h"
  71. #endif
  72. #include "constant_time_internal.h"
  73. #define ciL (sizeof(mbedtls_mpi_uint)) /** chars in limb */
  74. #define biL (ciL << 3) /** bits in limb */
  75. #define biH (ciL << 2) /** half limb size */
  76. /*
  77. * Convert between bits/chars and number of limbs
  78. * Divide first in order to avoid potential overflows
  79. */
  80. #define BITS_TO_LIMBS(i) ((i) / biL + ((i) % biL != 0))
  81. #define CHARS_TO_LIMBS(i) ((i) / ciL + ((i) % ciL != 0))
  82. /* Get a specific byte, without range checks. */
  83. #define GET_BYTE(X, i) \
  84. (((X)[(i) / ciL] >> (((i) % ciL) * 8)) & 0xff)
  85. /* Constants to identify whether a value is public or secret. If a parameter is marked as secret by
  86. * this constant, the function must be constant time with respect to the parameter.
  87. *
  88. * This is only needed for functions with the _optionally_safe postfix. All other functions have
  89. * fixed behavior that can't be changed at runtime and are constant time with respect to their
  90. * parameters as prescribed by their documentation or by conventions in their module's documentation.
  91. *
  92. * Parameters should be named X_public where X is the name of the
  93. * corresponding input parameter.
  94. *
  95. * Implementation should always check using
  96. * if (X_public == MBEDTLS_MPI_IS_PUBLIC) {
  97. * // unsafe path
  98. * } else {
  99. * // safe path
  100. * }
  101. * not the other way round, in order to prevent misuse. (This is, if a value
  102. * other than the two below is passed, default to the safe path.) */
  103. #define MBEDTLS_MPI_IS_PUBLIC 0x2a2a2a2a
  104. #define MBEDTLS_MPI_IS_SECRET 0
  105. /** Count leading zero bits in a given integer.
  106. *
  107. * \warning The result is undefined if \p a == 0
  108. *
  109. * \param a Integer to count leading zero bits.
  110. *
  111. * \return The number of leading zero bits in \p a, if \p a != 0.
  112. * If \p a == 0, the result is undefined.
  113. */
  114. size_t mbedtls_mpi_core_clz(mbedtls_mpi_uint a);
  115. /** Return the minimum number of bits required to represent the value held
  116. * in the MPI.
  117. *
  118. * \note This function returns 0 if all the limbs of \p A are 0.
  119. *
  120. * \param[in] A The address of the MPI.
  121. * \param A_limbs The number of limbs of \p A.
  122. *
  123. * \return The number of bits in \p A.
  124. */
  125. size_t mbedtls_mpi_core_bitlen(const mbedtls_mpi_uint *A, size_t A_limbs);
  126. /** Convert a big-endian byte array aligned to the size of mbedtls_mpi_uint
  127. * into the storage form used by mbedtls_mpi.
  128. *
  129. * \param[in,out] A The address of the MPI.
  130. * \param A_limbs The number of limbs of \p A.
  131. */
  132. void mbedtls_mpi_core_bigendian_to_host(mbedtls_mpi_uint *A,
  133. size_t A_limbs);
  134. /** \brief Compare a machine integer with an MPI.
  135. *
  136. * This function operates in constant time with respect
  137. * to the values of \p min and \p A.
  138. *
  139. * \param min A machine integer.
  140. * \param[in] A An MPI.
  141. * \param A_limbs The number of limbs of \p A.
  142. * This must be at least 1.
  143. *
  144. * \return MBEDTLS_CT_TRUE if \p min is less than or equal to \p A, otherwise MBEDTLS_CT_FALSE.
  145. */
  146. mbedtls_ct_condition_t mbedtls_mpi_core_uint_le_mpi(mbedtls_mpi_uint min,
  147. const mbedtls_mpi_uint *A,
  148. size_t A_limbs);
  149. /**
  150. * \brief Check if one unsigned MPI is less than another in constant
  151. * time.
  152. *
  153. * \param A The left-hand MPI. This must point to an array of limbs
  154. * with the same allocated length as \p B.
  155. * \param B The right-hand MPI. This must point to an array of limbs
  156. * with the same allocated length as \p A.
  157. * \param limbs The number of limbs in \p A and \p B.
  158. * This must not be 0.
  159. *
  160. * \return MBEDTLS_CT_TRUE if \p A is less than \p B.
  161. * MBEDTLS_CT_FALSE if \p A is greater than or equal to \p B.
  162. */
  163. mbedtls_ct_condition_t mbedtls_mpi_core_lt_ct(const mbedtls_mpi_uint *A,
  164. const mbedtls_mpi_uint *B,
  165. size_t limbs);
  166. /**
  167. * \brief Perform a safe conditional copy of an MPI which doesn't reveal
  168. * whether assignment was done or not.
  169. *
  170. * \param[out] X The address of the destination MPI.
  171. * This must be initialized. Must have enough limbs to
  172. * store the full value of \p A.
  173. * \param[in] A The address of the source MPI. This must be initialized.
  174. * \param limbs The number of limbs of \p A.
  175. * \param assign The condition deciding whether to perform the
  176. * assignment or not. Callers will need to use
  177. * the constant time interface (e.g. `mbedtls_ct_bool()`)
  178. * to construct this argument.
  179. *
  180. * \note This function avoids leaking any information about whether
  181. * the assignment was done or not.
  182. */
  183. void mbedtls_mpi_core_cond_assign(mbedtls_mpi_uint *X,
  184. const mbedtls_mpi_uint *A,
  185. size_t limbs,
  186. mbedtls_ct_condition_t assign);
  187. /**
  188. * \brief Perform a safe conditional swap of two MPIs which doesn't reveal
  189. * whether the swap was done or not.
  190. *
  191. * \param[in,out] X The address of the first MPI.
  192. * This must be initialized.
  193. * \param[in,out] Y The address of the second MPI.
  194. * This must be initialized.
  195. * \param limbs The number of limbs of \p X and \p Y.
  196. * \param swap The condition deciding whether to perform
  197. * the swap or not.
  198. *
  199. * \note This function avoids leaking any information about whether
  200. * the swap was done or not.
  201. */
  202. void mbedtls_mpi_core_cond_swap(mbedtls_mpi_uint *X,
  203. mbedtls_mpi_uint *Y,
  204. size_t limbs,
  205. mbedtls_ct_condition_t swap);
  206. /** Import X from unsigned binary data, little-endian.
  207. *
  208. * The MPI needs to have enough limbs to store the full value (including any
  209. * most significant zero bytes in the input).
  210. *
  211. * \param[out] X The address of the MPI.
  212. * \param X_limbs The number of limbs of \p X.
  213. * \param[in] input The input buffer to import from.
  214. * \param input_length The length bytes of \p input.
  215. *
  216. * \return \c 0 if successful.
  217. * \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p X isn't
  218. * large enough to hold the value in \p input.
  219. */
  220. int mbedtls_mpi_core_read_le(mbedtls_mpi_uint *X,
  221. size_t X_limbs,
  222. const unsigned char *input,
  223. size_t input_length);
  224. /** Import X from unsigned binary data, big-endian.
  225. *
  226. * The MPI needs to have enough limbs to store the full value (including any
  227. * most significant zero bytes in the input).
  228. *
  229. * \param[out] X The address of the MPI.
  230. * May only be #NULL if \p X_limbs is 0 and \p input_length
  231. * is 0.
  232. * \param X_limbs The number of limbs of \p X.
  233. * \param[in] input The input buffer to import from.
  234. * May only be #NULL if \p input_length is 0.
  235. * \param input_length The length in bytes of \p input.
  236. *
  237. * \return \c 0 if successful.
  238. * \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p X isn't
  239. * large enough to hold the value in \p input.
  240. */
  241. int mbedtls_mpi_core_read_be(mbedtls_mpi_uint *X,
  242. size_t X_limbs,
  243. const unsigned char *input,
  244. size_t input_length);
  245. /** Export A into unsigned binary data, little-endian.
  246. *
  247. * \note If \p output is shorter than \p A the export is still successful if the
  248. * value held in \p A fits in the buffer (that is, if enough of the most
  249. * significant bytes of \p A are 0).
  250. *
  251. * \param[in] A The address of the MPI.
  252. * \param A_limbs The number of limbs of \p A.
  253. * \param[out] output The output buffer to export to.
  254. * \param output_length The length in bytes of \p output.
  255. *
  256. * \return \c 0 if successful.
  257. * \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p output isn't
  258. * large enough to hold the value of \p A.
  259. */
  260. int mbedtls_mpi_core_write_le(const mbedtls_mpi_uint *A,
  261. size_t A_limbs,
  262. unsigned char *output,
  263. size_t output_length);
  264. /** Export A into unsigned binary data, big-endian.
  265. *
  266. * \note If \p output is shorter than \p A the export is still successful if the
  267. * value held in \p A fits in the buffer (that is, if enough of the most
  268. * significant bytes of \p A are 0).
  269. *
  270. * \param[in] A The address of the MPI.
  271. * \param A_limbs The number of limbs of \p A.
  272. * \param[out] output The output buffer to export to.
  273. * \param output_length The length in bytes of \p output.
  274. *
  275. * \return \c 0 if successful.
  276. * \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p output isn't
  277. * large enough to hold the value of \p A.
  278. */
  279. int mbedtls_mpi_core_write_be(const mbedtls_mpi_uint *A,
  280. size_t A_limbs,
  281. unsigned char *output,
  282. size_t output_length);
  283. /** \brief Shift an MPI in-place right by a number of bits.
  284. *
  285. * Shifting by more bits than there are bit positions
  286. * in \p X is valid and results in setting \p X to 0.
  287. *
  288. * This function's execution time depends on the value
  289. * of \p count (and of course \p limbs).
  290. *
  291. * \param[in,out] X The number to shift.
  292. * \param limbs The number of limbs of \p X. This must be at least 1.
  293. * \param count The number of bits to shift by.
  294. */
  295. void mbedtls_mpi_core_shift_r(mbedtls_mpi_uint *X, size_t limbs,
  296. size_t count);
  297. /**
  298. * \brief Shift an MPI in-place left by a number of bits.
  299. *
  300. * Shifting by more bits than there are bit positions
  301. * in \p X will produce an unspecified result.
  302. *
  303. * This function's execution time depends on the value
  304. * of \p count (and of course \p limbs).
  305. * \param[in,out] X The number to shift.
  306. * \param limbs The number of limbs of \p X. This must be at least 1.
  307. * \param count The number of bits to shift by.
  308. */
  309. void mbedtls_mpi_core_shift_l(mbedtls_mpi_uint *X, size_t limbs,
  310. size_t count);
  311. /**
  312. * \brief Add two fixed-size large unsigned integers, returning the carry.
  313. *
  314. * Calculates `A + B` where `A` and `B` have the same size.
  315. *
  316. * This function operates modulo `2^(biL*limbs)` and returns the carry
  317. * (1 if there was a wraparound, and 0 otherwise).
  318. *
  319. * \p X may be aliased to \p A or \p B.
  320. *
  321. * \param[out] X The result of the addition.
  322. * \param[in] A Little-endian presentation of the left operand.
  323. * \param[in] B Little-endian presentation of the right operand.
  324. * \param limbs Number of limbs of \p X, \p A and \p B.
  325. *
  326. * \return 1 if `A + B >= 2^(biL*limbs)`, 0 otherwise.
  327. */
  328. mbedtls_mpi_uint mbedtls_mpi_core_add(mbedtls_mpi_uint *X,
  329. const mbedtls_mpi_uint *A,
  330. const mbedtls_mpi_uint *B,
  331. size_t limbs);
  332. /**
  333. * \brief Conditional addition of two fixed-size large unsigned integers,
  334. * returning the carry.
  335. *
  336. * Functionally equivalent to
  337. *
  338. * ```
  339. * if( cond )
  340. * X += A;
  341. * return carry;
  342. * ```
  343. *
  344. * This function operates modulo `2^(biL*limbs)`.
  345. *
  346. * \param[in,out] X The pointer to the (little-endian) array
  347. * representing the bignum to accumulate onto.
  348. * \param[in] A The pointer to the (little-endian) array
  349. * representing the bignum to conditionally add
  350. * to \p X. This may be aliased to \p X but may not
  351. * overlap otherwise.
  352. * \param limbs Number of limbs of \p X and \p A.
  353. * \param cond Condition bit dictating whether addition should
  354. * happen or not. This must be \c 0 or \c 1.
  355. *
  356. * \warning If \p cond is neither 0 nor 1, the result of this function
  357. * is unspecified, and the resulting value in \p X might be
  358. * neither its original value nor \p X + \p A.
  359. *
  360. * \return 1 if `X + cond * A >= 2^(biL*limbs)`, 0 otherwise.
  361. */
  362. mbedtls_mpi_uint mbedtls_mpi_core_add_if(mbedtls_mpi_uint *X,
  363. const mbedtls_mpi_uint *A,
  364. size_t limbs,
  365. unsigned cond);
  366. /**
  367. * \brief Subtract two fixed-size large unsigned integers, returning the borrow.
  368. *
  369. * Calculate `A - B` where \p A and \p B have the same size.
  370. * This function operates modulo `2^(biL*limbs)` and returns the carry
  371. * (1 if there was a wraparound, i.e. if `A < B`, and 0 otherwise).
  372. *
  373. * \p X may be aliased to \p A or \p B, or even both, but may not overlap
  374. * either otherwise.
  375. *
  376. * \param[out] X The result of the subtraction.
  377. * \param[in] A Little-endian presentation of left operand.
  378. * \param[in] B Little-endian presentation of right operand.
  379. * \param limbs Number of limbs of \p X, \p A and \p B.
  380. *
  381. * \return 1 if `A < B`.
  382. * 0 if `A >= B`.
  383. */
  384. mbedtls_mpi_uint mbedtls_mpi_core_sub(mbedtls_mpi_uint *X,
  385. const mbedtls_mpi_uint *A,
  386. const mbedtls_mpi_uint *B,
  387. size_t limbs);
  388. /**
  389. * \brief Perform a fixed-size multiply accumulate operation: X += b * A
  390. *
  391. * \p X may be aliased to \p A (when \p X_limbs == \p A_limbs), but may not
  392. * otherwise overlap.
  393. *
  394. * This function operates modulo `2^(biL*X_limbs)`.
  395. *
  396. * \param[in,out] X The pointer to the (little-endian) array
  397. * representing the bignum to accumulate onto.
  398. * \param X_limbs The number of limbs of \p X. This must be
  399. * at least \p A_limbs.
  400. * \param[in] A The pointer to the (little-endian) array
  401. * representing the bignum to multiply with.
  402. * This may be aliased to \p X but may not overlap
  403. * otherwise.
  404. * \param A_limbs The number of limbs of \p A.
  405. * \param b X scalar to multiply with.
  406. *
  407. * \return The carry at the end of the operation.
  408. */
  409. mbedtls_mpi_uint mbedtls_mpi_core_mla(mbedtls_mpi_uint *X, size_t X_limbs,
  410. const mbedtls_mpi_uint *A, size_t A_limbs,
  411. mbedtls_mpi_uint b);
  412. /**
  413. * \brief Perform a known-size multiplication
  414. *
  415. * \p X may not be aliased to any of the inputs for this function.
  416. * \p A may be aliased to \p B.
  417. *
  418. * \param[out] X The pointer to the (little-endian) array to receive
  419. * the product of \p A_limbs and \p B_limbs.
  420. * This must be of length \p A_limbs + \p B_limbs.
  421. * \param[in] A The pointer to the (little-endian) array
  422. * representing the first factor.
  423. * \param A_limbs The number of limbs in \p A.
  424. * \param[in] B The pointer to the (little-endian) array
  425. * representing the second factor.
  426. * \param B_limbs The number of limbs in \p B.
  427. */
  428. void mbedtls_mpi_core_mul(mbedtls_mpi_uint *X,
  429. const mbedtls_mpi_uint *A, size_t A_limbs,
  430. const mbedtls_mpi_uint *B, size_t B_limbs);
  431. /**
  432. * \brief Calculate initialisation value for fast Montgomery modular
  433. * multiplication
  434. *
  435. * \param[in] N Little-endian presentation of the modulus. This must have
  436. * at least one limb.
  437. *
  438. * \return The initialisation value for fast Montgomery modular multiplication
  439. */
  440. mbedtls_mpi_uint mbedtls_mpi_core_montmul_init(const mbedtls_mpi_uint *N);
  441. /**
  442. * \brief Montgomery multiplication: X = A * B * R^-1 mod N (HAC 14.36)
  443. *
  444. * \p A and \p B must be in canonical form. That is, < \p N.
  445. *
  446. * \p X may be aliased to \p A or \p N, or even \p B (if \p AN_limbs ==
  447. * \p B_limbs) but may not overlap any parameters otherwise.
  448. *
  449. * \p A and \p B may alias each other, if \p AN_limbs == \p B_limbs. They may
  450. * not alias \p N (since they must be in canonical form, they cannot == \p N).
  451. *
  452. * \param[out] X The destination MPI, as a little-endian array of
  453. * length \p AN_limbs.
  454. * On successful completion, X contains the result of
  455. * the multiplication `A * B * R^-1` mod N where
  456. * `R = 2^(biL*AN_limbs)`.
  457. * \param[in] A Little-endian presentation of first operand.
  458. * Must have the same number of limbs as \p N.
  459. * \param[in] B Little-endian presentation of second operand.
  460. * \param[in] B_limbs The number of limbs in \p B.
  461. * Must be <= \p AN_limbs.
  462. * \param[in] N Little-endian presentation of the modulus.
  463. * This must be odd, and have exactly the same number
  464. * of limbs as \p A.
  465. * It may alias \p X, but must not alias or otherwise
  466. * overlap any of the other parameters.
  467. * \param[in] AN_limbs The number of limbs in \p X, \p A and \p N.
  468. * \param mm The Montgomery constant for \p N: -N^-1 mod 2^biL.
  469. * This can be calculated by `mbedtls_mpi_core_montmul_init()`.
  470. * \param[in,out] T Temporary storage of size at least 2*AN_limbs+1 limbs.
  471. * Its initial content is unused and
  472. * its final content is indeterminate.
  473. * It must not alias or otherwise overlap any of the
  474. * other parameters.
  475. */
  476. void mbedtls_mpi_core_montmul(mbedtls_mpi_uint *X,
  477. const mbedtls_mpi_uint *A,
  478. const mbedtls_mpi_uint *B, size_t B_limbs,
  479. const mbedtls_mpi_uint *N, size_t AN_limbs,
  480. mbedtls_mpi_uint mm, mbedtls_mpi_uint *T);
  481. /**
  482. * \brief Calculate the square of the Montgomery constant. (Needed
  483. * for conversion and operations in Montgomery form.)
  484. *
  485. * \param[out] X A pointer to the result of the calculation of
  486. * the square of the Montgomery constant:
  487. * 2^{2*n*biL} mod N.
  488. * \param[in] N Little-endian presentation of the modulus, which must be odd.
  489. *
  490. * \return 0 if successful.
  491. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if there is not enough space
  492. * to store the value of Montgomery constant squared.
  493. * \return #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p N modulus is zero.
  494. * \return #MBEDTLS_ERR_MPI_NEGATIVE_VALUE if \p N modulus is negative.
  495. */
  496. int mbedtls_mpi_core_get_mont_r2_unsafe(mbedtls_mpi *X,
  497. const mbedtls_mpi *N);
  498. #if defined(MBEDTLS_TEST_HOOKS)
  499. /**
  500. * Copy an MPI from a table without leaking the index.
  501. *
  502. * \param dest The destination buffer. This must point to a writable
  503. * buffer of at least \p limbs limbs.
  504. * \param table The address of the table. This must point to a readable
  505. * array of \p count elements of \p limbs limbs each.
  506. * \param limbs The number of limbs in each table entry.
  507. * \param count The number of entries in \p table.
  508. * \param index The (secret) table index to look up. This must be in the
  509. * range `0 .. count-1`.
  510. */
  511. void mbedtls_mpi_core_ct_uint_table_lookup(mbedtls_mpi_uint *dest,
  512. const mbedtls_mpi_uint *table,
  513. size_t limbs,
  514. size_t count,
  515. size_t index);
  516. #endif /* MBEDTLS_TEST_HOOKS */
  517. /**
  518. * \brief Fill an integer with a number of random bytes.
  519. *
  520. * \param X The destination MPI.
  521. * \param X_limbs The number of limbs of \p X.
  522. * \param bytes The number of random bytes to generate.
  523. * \param f_rng The RNG function to use. This must not be \c NULL.
  524. * \param p_rng The RNG parameter to be passed to \p f_rng. This may be
  525. * \c NULL if \p f_rng doesn't need a context argument.
  526. *
  527. * \return \c 0 if successful.
  528. * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p X does not have
  529. * enough room for \p bytes bytes.
  530. * \return A negative error code on RNG failure.
  531. *
  532. * \note The bytes obtained from the RNG are interpreted
  533. * as a big-endian representation of an MPI; this can
  534. * be relevant in applications like deterministic ECDSA.
  535. */
  536. int mbedtls_mpi_core_fill_random(mbedtls_mpi_uint *X, size_t X_limbs,
  537. size_t bytes,
  538. int (*f_rng)(void *, unsigned char *, size_t),
  539. void *p_rng);
  540. /** Generate a random number uniformly in a range.
  541. *
  542. * This function generates a random number between \p min inclusive and
  543. * \p N exclusive.
  544. *
  545. * The procedure complies with RFC 6979 §3.3 (deterministic ECDSA)
  546. * when the RNG is a suitably parametrized instance of HMAC_DRBG
  547. * and \p min is \c 1.
  548. *
  549. * \note There are `N - min` possible outputs. The lower bound
  550. * \p min can be reached, but the upper bound \p N cannot.
  551. *
  552. * \param X The destination MPI, with \p limbs limbs.
  553. * It must not be aliased with \p N or otherwise overlap it.
  554. * \param min The minimum value to return.
  555. * \param N The upper bound of the range, exclusive, with \p limbs limbs.
  556. * In other words, this is one plus the maximum value to return.
  557. * \p N must be strictly larger than \p min.
  558. * \param limbs The number of limbs of \p N and \p X.
  559. * This must not be 0.
  560. * \param f_rng The RNG function to use. This must not be \c NULL.
  561. * \param p_rng The RNG parameter to be passed to \p f_rng.
  562. *
  563. * \return \c 0 if successful.
  564. * \return #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if the implementation was
  565. * unable to find a suitable value within a limited number
  566. * of attempts. This has a negligible probability if \p N
  567. * is significantly larger than \p min, which is the case
  568. * for all usual cryptographic applications.
  569. */
  570. int mbedtls_mpi_core_random(mbedtls_mpi_uint *X,
  571. mbedtls_mpi_uint min,
  572. const mbedtls_mpi_uint *N,
  573. size_t limbs,
  574. int (*f_rng)(void *, unsigned char *, size_t),
  575. void *p_rng);
  576. /**
  577. * \brief Returns the number of limbs of working memory required for
  578. * a call to `mbedtls_mpi_core_exp_mod()`.
  579. *
  580. * \note This will always be at least
  581. * `mbedtls_mpi_core_montmul_working_limbs(AN_limbs)`,
  582. * i.e. sufficient for a call to `mbedtls_mpi_core_montmul()`.
  583. *
  584. * \param AN_limbs The number of limbs in the input `A` and the modulus `N`
  585. * (they must be the same size) that will be given to
  586. * `mbedtls_mpi_core_exp_mod()`.
  587. * \param E_limbs The number of limbs in the exponent `E` that will be given
  588. * to `mbedtls_mpi_core_exp_mod()`.
  589. *
  590. * \return The number of limbs of working memory required by
  591. * `mbedtls_mpi_core_exp_mod()`.
  592. */
  593. size_t mbedtls_mpi_core_exp_mod_working_limbs(size_t AN_limbs, size_t E_limbs);
  594. /**
  595. * \brief Perform a modular exponentiation with public or secret exponent:
  596. * X = A^E mod N, where \p A is already in Montgomery form.
  597. *
  598. * \warning This function is not constant time with respect to \p E (the exponent).
  599. *
  600. * \p X may be aliased to \p A, but not to \p RR or \p E, even if \p E_limbs ==
  601. * \p AN_limbs.
  602. *
  603. * \param[out] X The destination MPI, as a little endian array of length
  604. * \p AN_limbs.
  605. * \param[in] A The base MPI, as a little endian array of length \p AN_limbs.
  606. * Must be in Montgomery form.
  607. * \param[in] N The modulus, as a little endian array of length \p AN_limbs.
  608. * \param AN_limbs The number of limbs in \p X, \p A, \p N, \p RR.
  609. * \param[in] E The exponent, as a little endian array of length \p E_limbs.
  610. * \param E_limbs The number of limbs in \p E.
  611. * \param[in] RR The precomputed residue of 2^{2*biL} modulo N, as a little
  612. * endian array of length \p AN_limbs.
  613. * \param[in,out] T Temporary storage of at least the number of limbs returned
  614. * by `mbedtls_mpi_core_exp_mod_working_limbs()`.
  615. * Its initial content is unused and its final content is
  616. * indeterminate.
  617. * It must not alias or otherwise overlap any of the other
  618. * parameters.
  619. * It is up to the caller to zeroize \p T when it is no
  620. * longer needed, and before freeing it if it was dynamically
  621. * allocated.
  622. */
  623. void mbedtls_mpi_core_exp_mod_unsafe(mbedtls_mpi_uint *X,
  624. const mbedtls_mpi_uint *A,
  625. const mbedtls_mpi_uint *N, size_t AN_limbs,
  626. const mbedtls_mpi_uint *E, size_t E_limbs,
  627. const mbedtls_mpi_uint *RR,
  628. mbedtls_mpi_uint *T);
  629. /**
  630. * \brief Perform a modular exponentiation with secret exponent:
  631. * X = A^E mod N, where \p A is already in Montgomery form.
  632. *
  633. * \p X may be aliased to \p A, but not to \p RR or \p E, even if \p E_limbs ==
  634. * \p AN_limbs.
  635. *
  636. * \param[out] X The destination MPI, as a little endian array of length
  637. * \p AN_limbs.
  638. * \param[in] A The base MPI, as a little endian array of length \p AN_limbs.
  639. * Must be in Montgomery form.
  640. * \param[in] N The modulus, as a little endian array of length \p AN_limbs.
  641. * \param AN_limbs The number of limbs in \p X, \p A, \p N, \p RR.
  642. * \param[in] E The exponent, as a little endian array of length \p E_limbs.
  643. * \param E_limbs The number of limbs in \p E.
  644. * \param[in] RR The precomputed residue of 2^{2*biL} modulo N, as a little
  645. * endian array of length \p AN_limbs.
  646. * \param[in,out] T Temporary storage of at least the number of limbs returned
  647. * by `mbedtls_mpi_core_exp_mod_working_limbs()`.
  648. * Its initial content is unused and its final content is
  649. * indeterminate.
  650. * It must not alias or otherwise overlap any of the other
  651. * parameters.
  652. * It is up to the caller to zeroize \p T when it is no
  653. * longer needed, and before freeing it if it was dynamically
  654. * allocated.
  655. */
  656. void mbedtls_mpi_core_exp_mod(mbedtls_mpi_uint *X,
  657. const mbedtls_mpi_uint *A,
  658. const mbedtls_mpi_uint *N, size_t AN_limbs,
  659. const mbedtls_mpi_uint *E, size_t E_limbs,
  660. const mbedtls_mpi_uint *RR,
  661. mbedtls_mpi_uint *T);
  662. /**
  663. * \brief Subtract unsigned integer from known-size large unsigned integers.
  664. * Return the borrow.
  665. *
  666. * \param[out] X The result of the subtraction.
  667. * \param[in] A The left operand.
  668. * \param b The unsigned scalar to subtract.
  669. * \param limbs Number of limbs of \p X and \p A.
  670. *
  671. * \return 1 if `A < b`.
  672. * 0 if `A >= b`.
  673. */
  674. mbedtls_mpi_uint mbedtls_mpi_core_sub_int(mbedtls_mpi_uint *X,
  675. const mbedtls_mpi_uint *A,
  676. mbedtls_mpi_uint b,
  677. size_t limbs);
  678. /**
  679. * \brief Determine if a given MPI has the value \c 0 in constant time with
  680. * respect to the value (but not with respect to the number of limbs).
  681. *
  682. * \param[in] A The MPI to test.
  683. * \param limbs Number of limbs in \p A.
  684. *
  685. * \return MBEDTLS_CT_FALSE if `A == 0`
  686. * MBEDTLS_CT_TRUE if `A != 0`.
  687. */
  688. mbedtls_ct_condition_t mbedtls_mpi_core_check_zero_ct(const mbedtls_mpi_uint *A,
  689. size_t limbs);
  690. /**
  691. * \brief Returns the number of limbs of working memory required for
  692. * a call to `mbedtls_mpi_core_montmul()`.
  693. *
  694. * \param AN_limbs The number of limbs in the input `A` and the modulus `N`
  695. * (they must be the same size) that will be given to
  696. * `mbedtls_mpi_core_montmul()` or one of the other functions
  697. * that specifies this as the amount of working memory needed.
  698. *
  699. * \return The number of limbs of working memory required by
  700. * `mbedtls_mpi_core_montmul()` (or other similar function).
  701. */
  702. static inline size_t mbedtls_mpi_core_montmul_working_limbs(size_t AN_limbs)
  703. {
  704. return 2 * AN_limbs + 1;
  705. }
  706. /** Convert an MPI into Montgomery form.
  707. *
  708. * \p X may be aliased to \p A, but may not otherwise overlap it.
  709. *
  710. * \p X may not alias \p N (it is in canonical form, so must be strictly less
  711. * than \p N). Nor may it alias or overlap \p rr (this is unlikely to be
  712. * required in practice.)
  713. *
  714. * This function is a thin wrapper around `mbedtls_mpi_core_montmul()` that is
  715. * an alternative to calling `mbedtls_mpi_mod_raw_to_mont_rep()` when we
  716. * don't want to allocate memory.
  717. *
  718. * \param[out] X The result of the conversion.
  719. * Must have the same number of limbs as \p A.
  720. * \param[in] A The MPI to convert into Montgomery form.
  721. * Must have the same number of limbs as the modulus.
  722. * \param[in] N The address of the modulus, which gives the size of
  723. * the base `R` = 2^(biL*N->limbs).
  724. * \param[in] AN_limbs The number of limbs in \p X, \p A, \p N and \p rr.
  725. * \param mm The Montgomery constant for \p N: -N^-1 mod 2^biL.
  726. * This can be determined by calling
  727. * `mbedtls_mpi_core_montmul_init()`.
  728. * \param[in] rr The residue for `2^{2*n*biL} mod N`.
  729. * \param[in,out] T Temporary storage of size at least
  730. * `mbedtls_mpi_core_montmul_working_limbs(AN_limbs)`
  731. * limbs.
  732. * Its initial content is unused and
  733. * its final content is indeterminate.
  734. * It must not alias or otherwise overlap any of the
  735. * other parameters.
  736. */
  737. void mbedtls_mpi_core_to_mont_rep(mbedtls_mpi_uint *X,
  738. const mbedtls_mpi_uint *A,
  739. const mbedtls_mpi_uint *N,
  740. size_t AN_limbs,
  741. mbedtls_mpi_uint mm,
  742. const mbedtls_mpi_uint *rr,
  743. mbedtls_mpi_uint *T);
  744. /** Convert an MPI from Montgomery form.
  745. *
  746. * \p X may be aliased to \p A, but may not otherwise overlap it.
  747. *
  748. * \p X may not alias \p N (it is in canonical form, so must be strictly less
  749. * than \p N).
  750. *
  751. * This function is a thin wrapper around `mbedtls_mpi_core_montmul()` that is
  752. * an alternative to calling `mbedtls_mpi_mod_raw_from_mont_rep()` when we
  753. * don't want to allocate memory.
  754. *
  755. * \param[out] X The result of the conversion.
  756. * Must have the same number of limbs as \p A.
  757. * \param[in] A The MPI to convert from Montgomery form.
  758. * Must have the same number of limbs as the modulus.
  759. * \param[in] N The address of the modulus, which gives the size of
  760. * the base `R` = 2^(biL*N->limbs).
  761. * \param[in] AN_limbs The number of limbs in \p X, \p A and \p N.
  762. * \param mm The Montgomery constant for \p N: -N^-1 mod 2^biL.
  763. * This can be determined by calling
  764. * `mbedtls_mpi_core_montmul_init()`.
  765. * \param[in,out] T Temporary storage of size at least
  766. * `mbedtls_mpi_core_montmul_working_limbs(AN_limbs)`
  767. * limbs.
  768. * Its initial content is unused and
  769. * its final content is indeterminate.
  770. * It must not alias or otherwise overlap any of the
  771. * other parameters.
  772. */
  773. void mbedtls_mpi_core_from_mont_rep(mbedtls_mpi_uint *X,
  774. const mbedtls_mpi_uint *A,
  775. const mbedtls_mpi_uint *N,
  776. size_t AN_limbs,
  777. mbedtls_mpi_uint mm,
  778. mbedtls_mpi_uint *T);
  779. /*
  780. * Can't define thread local variables with our abstraction layer: do nothing if threading is on.
  781. */
  782. #if defined(MBEDTLS_TEST_HOOKS) && !defined(MBEDTLS_THREADING_C)
  783. extern int mbedtls_mpi_optionally_safe_codepath;
  784. static inline void mbedtls_mpi_optionally_safe_codepath_reset(void)
  785. {
  786. // Set to a default that is neither MBEDTLS_MPI_IS_PUBLIC nor MBEDTLS_MPI_IS_SECRET
  787. mbedtls_mpi_optionally_safe_codepath = MBEDTLS_MPI_IS_PUBLIC + MBEDTLS_MPI_IS_SECRET + 1;
  788. }
  789. #endif
  790. #endif /* MBEDTLS_BIGNUM_CORE_H */