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