• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * \file bignum.h
3  *
4  * \brief Multi-precision integer library
5  */
6 /*
7  *  Copyright The Mbed TLS Contributors
8  *  SPDX-License-Identifier: Apache-2.0
9  *
10  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
11  *  not use this file except in compliance with the License.
12  *  You may obtain a copy of the License at
13  *
14  *  http://www.apache.org/licenses/LICENSE-2.0
15  *
16  *  Unless required by applicable law or agreed to in writing, software
17  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
18  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  *  See the License for the specific language governing permissions and
20  *  limitations under the License.
21  */
22 #ifndef MBEDTLS_BIGNUM_H
23 #define MBEDTLS_BIGNUM_H
24 #include "mbedtls/private_access.h"
25 
26 #include "mbedtls/build_info.h"
27 
28 #include <stddef.h>
29 #include <stdint.h>
30 
31 #if defined(MBEDTLS_FS_IO)
32 #include <stdio.h>
33 #endif
34 
35 /** An error occurred while reading from or writing to a file. */
36 #define MBEDTLS_ERR_MPI_FILE_IO_ERROR                     -0x0002
37 /** Bad input parameters to function. */
38 #define MBEDTLS_ERR_MPI_BAD_INPUT_DATA                    -0x0004
39 /** There is an invalid character in the digit string. */
40 #define MBEDTLS_ERR_MPI_INVALID_CHARACTER                 -0x0006
41 /** The buffer is too small to write to. */
42 #define MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL                  -0x0008
43 /** The input arguments are negative or result in illegal output. */
44 #define MBEDTLS_ERR_MPI_NEGATIVE_VALUE                    -0x000A
45 /** The input argument for division is zero, which is not allowed. */
46 #define MBEDTLS_ERR_MPI_DIVISION_BY_ZERO                  -0x000C
47 /** The input arguments are not acceptable. */
48 #define MBEDTLS_ERR_MPI_NOT_ACCEPTABLE                    -0x000E
49 /** Memory allocation failed. */
50 #define MBEDTLS_ERR_MPI_ALLOC_FAILED                      -0x0010
51 
52 #define MBEDTLS_MPI_CHK(f)       \
53     do                           \
54     {                            \
55         if ((ret = (f)) != 0) \
56         goto cleanup;        \
57     } while (0)
58 
59 /*
60  * Maximum size MPIs are allowed to grow to in number of limbs.
61  */
62 #define MBEDTLS_MPI_MAX_LIMBS                             10000
63 
64 #if !defined(MBEDTLS_MPI_WINDOW_SIZE)
65 /*
66  * Maximum window size used for modular exponentiation. Default: 2
67  * Minimum value: 1. Maximum value: 6.
68  *
69  * Result is an array of ( 2 ** MBEDTLS_MPI_WINDOW_SIZE ) MPIs used
70  * for the sliding window calculation. (So 64 by default)
71  *
72  * Reduction in size, reduces speed.
73  */
74 #define MBEDTLS_MPI_WINDOW_SIZE                           2        /**< Maximum window size used. */
75 #endif /* !MBEDTLS_MPI_WINDOW_SIZE */
76 
77 #if !defined(MBEDTLS_MPI_MAX_SIZE)
78 /*
79  * Maximum size of MPIs allowed in bits and bytes for user-MPIs.
80  * ( Default: 512 bytes => 4096 bits, Maximum tested: 2048 bytes => 16384 bits )
81  *
82  * Note: Calculations can temporarily result in larger MPIs. So the number
83  * of limbs required (MBEDTLS_MPI_MAX_LIMBS) is higher.
84  */
85 #define MBEDTLS_MPI_MAX_SIZE                              1024     /**< Maximum number of bytes for usable MPIs. */
86 #endif /* !MBEDTLS_MPI_MAX_SIZE */
87 
88 #define MBEDTLS_MPI_MAX_BITS                              (8 * MBEDTLS_MPI_MAX_SIZE)      /**< Maximum number of bits for usable MPIs. */
89 
90 /*
91  * When reading from files with mbedtls_mpi_read_file() and writing to files with
92  * mbedtls_mpi_write_file() the buffer should have space
93  * for a (short) label, the MPI (in the provided radix), the newline
94  * characters and the '\0'.
95  *
96  * By default we assume at least a 10 char label, a minimum radix of 10
97  * (decimal) and a maximum of 4096 bit numbers (1234 decimal chars).
98  * Autosized at compile time for at least a 10 char label, a minimum radix
99  * of 10 (decimal) for a number of MBEDTLS_MPI_MAX_BITS size.
100  *
101  * This used to be statically sized to 1250 for a maximum of 4096 bit
102  * numbers (1234 decimal chars).
103  *
104  * Calculate using the formula:
105  *  MBEDTLS_MPI_RW_BUFFER_SIZE = ceil(MBEDTLS_MPI_MAX_BITS / ln(10) * ln(2)) +
106  *                                LabelSize + 6
107  */
108 #define MBEDTLS_MPI_MAX_BITS_SCALE100          (100 * MBEDTLS_MPI_MAX_BITS)
109 #define MBEDTLS_LN_2_DIV_LN_10_SCALE100                 332
110 #define MBEDTLS_MPI_RW_BUFFER_SIZE             (((MBEDTLS_MPI_MAX_BITS_SCALE100 + \
111                                                   MBEDTLS_LN_2_DIV_LN_10_SCALE100 - 1) / \
112                                                  MBEDTLS_LN_2_DIV_LN_10_SCALE100) + 10 + 6)
113 
114 /*
115  * Define the base integer type, architecture-wise.
116  *
117  * 32 or 64-bit integer types can be forced regardless of the underlying
118  * architecture by defining MBEDTLS_HAVE_INT32 or MBEDTLS_HAVE_INT64
119  * respectively and undefining MBEDTLS_HAVE_ASM.
120  *
121  * Double-width integers (e.g. 128-bit in 64-bit architectures) can be
122  * disabled by defining MBEDTLS_NO_UDBL_DIVISION.
123  */
124 #if !defined(MBEDTLS_HAVE_INT32)
125     #if defined(_MSC_VER) && defined(_M_AMD64)
126 /* Always choose 64-bit when using MSC */
127         #if !defined(MBEDTLS_HAVE_INT64)
128             #define MBEDTLS_HAVE_INT64
129         #endif /* !MBEDTLS_HAVE_INT64 */
130 typedef  int64_t mbedtls_mpi_sint;
131 typedef uint64_t mbedtls_mpi_uint;
132     #elif defined(__GNUC__) && (                         \
133     defined(__amd64__) || defined(__x86_64__)     || \
134     defined(__ppc64__) || defined(__powerpc64__)  || \
135     defined(__ia64__)  || defined(__alpha__)      || \
136     (defined(__sparc__) && defined(__arch64__)) || \
137     defined(__s390x__) || defined(__mips64)       || \
138     defined(__aarch64__))
139         #if !defined(MBEDTLS_HAVE_INT64)
140             #define MBEDTLS_HAVE_INT64
141         #endif /* MBEDTLS_HAVE_INT64 */
142 typedef  int64_t mbedtls_mpi_sint;
143 typedef uint64_t mbedtls_mpi_uint;
144         #if !defined(MBEDTLS_NO_UDBL_DIVISION)
145 /* mbedtls_t_udbl defined as 128-bit unsigned int */
146 typedef unsigned int mbedtls_t_udbl __attribute__((mode(TI)));
147             #define MBEDTLS_HAVE_UDBL
148         #endif /* !MBEDTLS_NO_UDBL_DIVISION */
149     #elif defined(__ARMCC_VERSION) && defined(__aarch64__)
150 /*
151  * __ARMCC_VERSION is defined for both armcc and armclang and
152  * __aarch64__ is only defined by armclang when compiling 64-bit code
153  */
154         #if !defined(MBEDTLS_HAVE_INT64)
155             #define MBEDTLS_HAVE_INT64
156         #endif /* !MBEDTLS_HAVE_INT64 */
157 typedef  int64_t mbedtls_mpi_sint;
158 typedef uint64_t mbedtls_mpi_uint;
159         #if !defined(MBEDTLS_NO_UDBL_DIVISION)
160 /* mbedtls_t_udbl defined as 128-bit unsigned int */
161 typedef __uint128_t mbedtls_t_udbl;
162             #define MBEDTLS_HAVE_UDBL
163         #endif /* !MBEDTLS_NO_UDBL_DIVISION */
164     #elif defined(MBEDTLS_HAVE_INT64)
165 /* Force 64-bit integers with unknown compiler */
166 typedef  int64_t mbedtls_mpi_sint;
167 typedef uint64_t mbedtls_mpi_uint;
168     #endif
169 #endif /* !MBEDTLS_HAVE_INT32 */
170 
171 #if !defined(MBEDTLS_HAVE_INT64)
172 /* Default to 32-bit compilation */
173     #if !defined(MBEDTLS_HAVE_INT32)
174         #define MBEDTLS_HAVE_INT32
175     #endif /* !MBEDTLS_HAVE_INT32 */
176 typedef  int32_t mbedtls_mpi_sint;
177 typedef uint32_t mbedtls_mpi_uint;
178     #if !defined(MBEDTLS_NO_UDBL_DIVISION)
179 typedef uint64_t mbedtls_t_udbl;
180         #define MBEDTLS_HAVE_UDBL
181     #endif /* !MBEDTLS_NO_UDBL_DIVISION */
182 #endif /* !MBEDTLS_HAVE_INT64 */
183 
184 /** \typedef mbedtls_mpi_uint
185  * \brief The type of machine digits in a bignum, called _limbs_.
186  *
187  * This is always an unsigned integer type with no padding bits. The size
188  * is platform-dependent.
189  */
190 
191 /** \typedef mbedtls_mpi_sint
192  * \brief The signed type corresponding to #mbedtls_mpi_uint.
193  *
194  * This is always an signed integer type with no padding bits. The size
195  * is platform-dependent.
196  */
197 
198 #ifdef __cplusplus
199 extern "C" {
200 #endif
201 
202 /**
203  * \brief          MPI structure
204  */
205 typedef struct mbedtls_mpi {
206     /** Sign: -1 if the mpi is negative, 1 otherwise.
207      *
208      * The number 0 must be represented with `s = +1`. Although many library
209      * functions treat all-limbs-zero as equivalent to a valid representation
210      * of 0 regardless of the sign bit, there are exceptions, so bignum
211      * functions and external callers must always set \c s to +1 for the
212      * number zero.
213      *
214      * Note that this implies that calloc() or `... = {0}` does not create
215      * a valid MPI representation. You must call mbedtls_mpi_init().
216      */
217     int MBEDTLS_PRIVATE(s);
218 
219     /** Total number of limbs in \c p.  */
220     size_t MBEDTLS_PRIVATE(n);
221 
222     /** Pointer to limbs.
223      *
224      * This may be \c NULL if \c n is 0.
225      */
226     mbedtls_mpi_uint *MBEDTLS_PRIVATE(p);
227 }
228 mbedtls_mpi;
229 
230 /**
231  * \brief           Initialize an MPI context.
232  *
233  *                  This makes the MPI ready to be set or freed,
234  *                  but does not define a value for the MPI.
235  *
236  * \param X         The MPI context to initialize. This must not be \c NULL.
237  */
238 void mbedtls_mpi_init(mbedtls_mpi *X);
239 
240 /**
241  * \brief          This function frees the components of an MPI context.
242  *
243  * \param X        The MPI context to be cleared. This may be \c NULL,
244  *                 in which case this function is a no-op. If it is
245  *                 not \c NULL, it must point to an initialized MPI.
246  */
247 void mbedtls_mpi_free(mbedtls_mpi *X);
248 
249 /**
250  * \brief          Enlarge an MPI to the specified number of limbs.
251  *
252  * \note           This function does nothing if the MPI is
253  *                 already large enough.
254  *
255  * \param X        The MPI to grow. It must be initialized.
256  * \param nblimbs  The target number of limbs.
257  *
258  * \return         \c 0 if successful.
259  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
260  * \return         Another negative error code on other kinds of failure.
261  */
262 int mbedtls_mpi_grow(mbedtls_mpi *X, size_t nblimbs);
263 
264 /**
265  * \brief          This function resizes an MPI downwards, keeping at least the
266  *                 specified number of limbs.
267  *
268  *                 If \c X is smaller than \c nblimbs, it is resized up
269  *                 instead.
270  *
271  * \param X        The MPI to shrink. This must point to an initialized MPI.
272  * \param nblimbs  The minimum number of limbs to keep.
273  *
274  * \return         \c 0 if successful.
275  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed
276  *                 (this can only happen when resizing up).
277  * \return         Another negative error code on other kinds of failure.
278  */
279 int mbedtls_mpi_shrink(mbedtls_mpi *X, size_t nblimbs);
280 
281 /**
282  * \brief          Make a copy of an MPI.
283  *
284  * \param X        The destination MPI. This must point to an initialized MPI.
285  * \param Y        The source MPI. This must point to an initialized MPI.
286  *
287  * \note           The limb-buffer in the destination MPI is enlarged
288  *                 if necessary to hold the value in the source MPI.
289  *
290  * \return         \c 0 if successful.
291  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
292  * \return         Another negative error code on other kinds of failure.
293  */
294 int mbedtls_mpi_copy(mbedtls_mpi *X, const mbedtls_mpi *Y);
295 
296 /**
297  * \brief          Swap the contents of two MPIs.
298  *
299  * \param X        The first MPI. It must be initialized.
300  * \param Y        The second MPI. It must be initialized.
301  */
302 void mbedtls_mpi_swap(mbedtls_mpi *X, mbedtls_mpi *Y);
303 
304 /**
305  * \brief          Perform a safe conditional copy of MPI which doesn't
306  *                 reveal whether the condition was true or not.
307  *
308  * \param X        The MPI to conditionally assign to. This must point
309  *                 to an initialized MPI.
310  * \param Y        The MPI to be assigned from. This must point to an
311  *                 initialized MPI.
312  * \param assign   The condition deciding whether to perform the
313  *                 assignment or not. Must be either 0 or 1:
314  *                 * \c 1: Perform the assignment `X = Y`.
315  *                 * \c 0: Keep the original value of \p X.
316  *
317  * \note           This function is equivalent to
318  *                      `if( assign ) mbedtls_mpi_copy( X, Y );`
319  *                 except that it avoids leaking any information about whether
320  *                 the assignment was done or not (the above code may leak
321  *                 information through branch prediction and/or memory access
322  *                 patterns analysis).
323  *
324  * \warning        If \p assign is neither 0 nor 1, the result of this function
325  *                 is indeterminate, and the resulting value in \p X might be
326  *                 neither its original value nor the value in \p Y.
327  *
328  * \return         \c 0 if successful.
329  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
330  * \return         Another negative error code on other kinds of failure.
331  */
332 int mbedtls_mpi_safe_cond_assign(mbedtls_mpi *X, const mbedtls_mpi *Y, unsigned char assign);
333 
334 /**
335  * \brief          Perform a safe conditional swap which doesn't
336  *                 reveal whether the condition was true or not.
337  *
338  * \param X        The first MPI. This must be initialized.
339  * \param Y        The second MPI. This must be initialized.
340  * \param swap     The condition deciding whether to perform
341  *                 the swap or not. Must be either 0 or 1:
342  *                 * \c 1: Swap the values of \p X and \p Y.
343  *                 * \c 0: Keep the original values of \p X and \p Y.
344  *
345  * \note           This function is equivalent to
346  *                      if( swap ) mbedtls_mpi_swap( X, Y );
347  *                 except that it avoids leaking any information about whether
348  *                 the swap was done or not (the above code may leak
349  *                 information through branch prediction and/or memory access
350  *                 patterns analysis).
351  *
352  * \warning        If \p swap is neither 0 nor 1, the result of this function
353  *                 is indeterminate, and both \p X and \p Y might end up with
354  *                 values different to either of the original ones.
355  *
356  * \return         \c 0 if successful.
357  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
358  * \return         Another negative error code on other kinds of failure.
359  *
360  */
361 int mbedtls_mpi_safe_cond_swap(mbedtls_mpi *X, mbedtls_mpi *Y, unsigned char swap);
362 
363 /**
364  * \brief          Store integer value in MPI.
365  *
366  * \param X        The MPI to set. This must be initialized.
367  * \param z        The value to use.
368  *
369  * \return         \c 0 if successful.
370  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
371  * \return         Another negative error code on other kinds of failure.
372  */
373 int mbedtls_mpi_lset(mbedtls_mpi *X, mbedtls_mpi_sint z);
374 
375 /**
376  * \brief          Get a specific bit from an MPI.
377  *
378  * \param X        The MPI to query. This must be initialized.
379  * \param pos      Zero-based index of the bit to query.
380  *
381  * \return         \c 0 or \c 1 on success, depending on whether bit \c pos
382  *                 of \c X is unset or set.
383  * \return         A negative error code on failure.
384  */
385 int mbedtls_mpi_get_bit(const mbedtls_mpi *X, size_t pos);
386 
387 /**
388  * \brief          Modify a specific bit in an MPI.
389  *
390  * \note           This function will grow the target MPI if necessary to set a
391  *                 bit to \c 1 in a not yet existing limb. It will not grow if
392  *                 the bit should be set to \c 0.
393  *
394  * \param X        The MPI to modify. This must be initialized.
395  * \param pos      Zero-based index of the bit to modify.
396  * \param val      The desired value of bit \c pos: \c 0 or \c 1.
397  *
398  * \return         \c 0 if successful.
399  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
400  * \return         Another negative error code on other kinds of failure.
401  */
402 int mbedtls_mpi_set_bit(mbedtls_mpi *X, size_t pos, unsigned char val);
403 
404 /**
405  * \brief          Return the number of bits of value \c 0 before the
406  *                 least significant bit of value \c 1.
407  *
408  * \note           This is the same as the zero-based index of
409  *                 the least significant bit of value \c 1.
410  *
411  * \param X        The MPI to query.
412  *
413  * \return         The number of bits of value \c 0 before the least significant
414  *                 bit of value \c 1 in \p X.
415  */
416 size_t mbedtls_mpi_lsb(const mbedtls_mpi *X);
417 
418 /**
419  * \brief          Return the number of bits up to and including the most
420  *                 significant bit of value \c 1.
421  *
422  * * \note         This is same as the one-based index of the most
423  *                 significant bit of value \c 1.
424  *
425  * \param X        The MPI to query. This must point to an initialized MPI.
426  *
427  * \return         The number of bits up to and including the most
428  *                 significant bit of value \c 1.
429  */
430 size_t mbedtls_mpi_bitlen(const mbedtls_mpi *X);
431 
432 /**
433  * \brief          Return the total size of an MPI value in bytes.
434  *
435  * \param X        The MPI to use. This must point to an initialized MPI.
436  *
437  * \note           The value returned by this function may be less than
438  *                 the number of bytes used to store \p X internally.
439  *                 This happens if and only if there are trailing bytes
440  *                 of value zero.
441  *
442  * \return         The least number of bytes capable of storing
443  *                 the absolute value of \p X.
444  */
445 size_t mbedtls_mpi_size(const mbedtls_mpi *X);
446 
447 /**
448  * \brief          Import an MPI from an ASCII string.
449  *
450  * \param X        The destination MPI. This must point to an initialized MPI.
451  * \param radix    The numeric base of the input string.
452  * \param s        Null-terminated string buffer.
453  *
454  * \return         \c 0 if successful.
455  * \return         A negative error code on failure.
456  */
457 int mbedtls_mpi_read_string(mbedtls_mpi *X, int radix, const char *s);
458 
459 /**
460  * \brief          Export an MPI to an ASCII string.
461  *
462  * \param X        The source MPI. This must point to an initialized MPI.
463  * \param radix    The numeric base of the output string.
464  * \param buf      The buffer to write the string to. This must be writable
465  *                 buffer of length \p buflen Bytes.
466  * \param buflen   The available size in Bytes of \p buf.
467  * \param olen     The address at which to store the length of the string
468  *                 written, including the  final \c NULL byte. This must
469  *                 not be \c NULL.
470  *
471  * \note           You can call this function with `buflen == 0` to obtain the
472  *                 minimum required buffer size in `*olen`.
473  *
474  * \return         \c 0 if successful.
475  * \return         #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if the target buffer \p buf
476  *                 is too small to hold the value of \p X in the desired base.
477  *                 In this case, `*olen` is nonetheless updated to contain the
478  *                 size of \p buf required for a successful call.
479  * \return         Another negative error code on different kinds of failure.
480  */
481 int mbedtls_mpi_write_string(const mbedtls_mpi *X, int radix,
482                              char *buf, size_t buflen, size_t *olen);
483 
484 #if defined(MBEDTLS_FS_IO)
485 /**
486  * \brief          Read an MPI from a line in an opened file.
487  *
488  * \param X        The destination MPI. This must point to an initialized MPI.
489  * \param radix    The numeric base of the string representation used
490  *                 in the source line.
491  * \param fin      The input file handle to use. This must not be \c NULL.
492  *
493  * \note           On success, this function advances the file stream
494  *                 to the end of the current line or to EOF.
495  *
496  *                 The function returns \c 0 on an empty line.
497  *
498  *                 Leading whitespaces are ignored, as is a
499  *                 '0x' prefix for radix \c 16.
500  *
501  * \return         \c 0 if successful.
502  * \return         #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if the file read buffer
503  *                 is too small.
504  * \return         Another negative error code on failure.
505  */
506 int mbedtls_mpi_read_file(mbedtls_mpi *X, int radix, FILE *fin);
507 
508 /**
509  * \brief          Export an MPI into an opened file.
510  *
511  * \param p        A string prefix to emit prior to the MPI data.
512  *                 For example, this might be a label, or "0x" when
513  *                 printing in base \c 16. This may be \c NULL if no prefix
514  *                 is needed.
515  * \param X        The source MPI. This must point to an initialized MPI.
516  * \param radix    The numeric base to be used in the emitted string.
517  * \param fout     The output file handle. This may be \c NULL, in which case
518  *                 the output is written to \c stdout.
519  *
520  * \return         \c 0 if successful.
521  * \return         A negative error code on failure.
522  */
523 int mbedtls_mpi_write_file(const char *p, const mbedtls_mpi *X,
524                            int radix, FILE *fout);
525 #endif /* MBEDTLS_FS_IO */
526 
527 /**
528  * \brief          Import an MPI from unsigned big endian binary data.
529  *
530  * \param X        The destination MPI. This must point to an initialized MPI.
531  * \param buf      The input buffer. This must be a readable buffer of length
532  *                 \p buflen Bytes.
533  * \param buflen   The length of the input buffer \p p in Bytes.
534  *
535  * \return         \c 0 if successful.
536  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
537  * \return         Another negative error code on different kinds of failure.
538  */
539 int mbedtls_mpi_read_binary(mbedtls_mpi *X, const unsigned char *buf,
540                             size_t buflen);
541 
542 /**
543  * \brief          Import X from unsigned binary data, little endian
544  *
545  * \param X        The destination MPI. This must point to an initialized MPI.
546  * \param buf      The input buffer. This must be a readable buffer of length
547  *                 \p buflen Bytes.
548  * \param buflen   The length of the input buffer \p p in Bytes.
549  *
550  * \return         \c 0 if successful.
551  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
552  * \return         Another negative error code on different kinds of failure.
553  */
554 int mbedtls_mpi_read_binary_le(mbedtls_mpi *X,
555                                const unsigned char *buf, size_t buflen);
556 
557 /**
558  * \brief          Export X into unsigned binary data, big endian.
559  *                 Always fills the whole buffer, which will start with zeros
560  *                 if the number is smaller.
561  *
562  * \param X        The source MPI. This must point to an initialized MPI.
563  * \param buf      The output buffer. This must be a writable buffer of length
564  *                 \p buflen Bytes.
565  * \param buflen   The size of the output buffer \p buf in Bytes.
566  *
567  * \return         \c 0 if successful.
568  * \return         #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p buf isn't
569  *                 large enough to hold the value of \p X.
570  * \return         Another negative error code on different kinds of failure.
571  */
572 int mbedtls_mpi_write_binary(const mbedtls_mpi *X, unsigned char *buf,
573                              size_t buflen);
574 
575 /**
576  * \brief          Export X into unsigned binary data, little endian.
577  *                 Always fills the whole buffer, which will end with zeros
578  *                 if the number is smaller.
579  *
580  * \param X        The source MPI. This must point to an initialized MPI.
581  * \param buf      The output buffer. This must be a writable buffer of length
582  *                 \p buflen Bytes.
583  * \param buflen   The size of the output buffer \p buf in Bytes.
584  *
585  * \return         \c 0 if successful.
586  * \return         #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p buf isn't
587  *                 large enough to hold the value of \p X.
588  * \return         Another negative error code on different kinds of failure.
589  */
590 int mbedtls_mpi_write_binary_le(const mbedtls_mpi *X,
591                                 unsigned char *buf, size_t buflen);
592 
593 /**
594  * \brief          Perform a left-shift on an MPI: X <<= count
595  *
596  * \param X        The MPI to shift. This must point to an initialized MPI.
597  * \param count    The number of bits to shift by.
598  *
599  * \return         \c 0 if successful.
600  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
601  * \return         Another negative error code on different kinds of failure.
602  */
603 int mbedtls_mpi_shift_l(mbedtls_mpi *X, size_t count);
604 
605 /**
606  * \brief          Perform a right-shift on an MPI: X >>= count
607  *
608  * \param X        The MPI to shift. This must point to an initialized MPI.
609  * \param count    The number of bits to shift by.
610  *
611  * \return         \c 0 if successful.
612  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
613  * \return         Another negative error code on different kinds of failure.
614  */
615 int mbedtls_mpi_shift_r(mbedtls_mpi *X, size_t count);
616 
617 /**
618  * \brief          Compare the absolute values of two MPIs.
619  *
620  * \param X        The left-hand MPI. This must point to an initialized MPI.
621  * \param Y        The right-hand MPI. This must point to an initialized MPI.
622  *
623  * \return         \c 1 if `|X|` is greater than `|Y|`.
624  * \return         \c -1 if `|X|` is lesser than `|Y|`.
625  * \return         \c 0 if `|X|` is equal to `|Y|`.
626  */
627 int mbedtls_mpi_cmp_abs(const mbedtls_mpi *X, const mbedtls_mpi *Y);
628 
629 /**
630  * \brief          Compare two MPIs.
631  *
632  * \param X        The left-hand MPI. This must point to an initialized MPI.
633  * \param Y        The right-hand MPI. This must point to an initialized MPI.
634  *
635  * \return         \c 1 if \p X is greater than \p Y.
636  * \return         \c -1 if \p X is lesser than \p Y.
637  * \return         \c 0 if \p X is equal to \p Y.
638  */
639 int mbedtls_mpi_cmp_mpi(const mbedtls_mpi *X, const mbedtls_mpi *Y);
640 
641 /**
642  * \brief          Check if an MPI is less than the other in constant time.
643  *
644  * \param X        The left-hand MPI. This must point to an initialized MPI
645  *                 with the same allocated length as Y.
646  * \param Y        The right-hand MPI. This must point to an initialized MPI
647  *                 with the same allocated length as X.
648  * \param ret      The result of the comparison:
649  *                 \c 1 if \p X is less than \p Y.
650  *                 \c 0 if \p X is greater than or equal to \p Y.
651  *
652  * \return         0 on success.
653  * \return         MBEDTLS_ERR_MPI_BAD_INPUT_DATA if the allocated length of
654  *                 the two input MPIs is not the same.
655  */
656 int mbedtls_mpi_lt_mpi_ct(const mbedtls_mpi *X, const mbedtls_mpi *Y,
657                           unsigned *ret);
658 
659 /**
660  * \brief          Compare an MPI with an integer.
661  *
662  * \param X        The left-hand MPI. This must point to an initialized MPI.
663  * \param z        The integer value to compare \p X to.
664  *
665  * \return         \c 1 if \p X is greater than \p z.
666  * \return         \c -1 if \p X is lesser than \p z.
667  * \return         \c 0 if \p X is equal to \p z.
668  */
669 int mbedtls_mpi_cmp_int(const mbedtls_mpi *X, mbedtls_mpi_sint z);
670 
671 /**
672  * \brief          Perform an unsigned addition of MPIs: X = |A| + |B|
673  *
674  * \param X        The destination MPI. This must point to an initialized MPI.
675  * \param A        The first summand. This must point to an initialized MPI.
676  * \param B        The second summand. This must point to an initialized MPI.
677  *
678  * \return         \c 0 if successful.
679  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
680  * \return         Another negative error code on different kinds of failure.
681  */
682 int mbedtls_mpi_add_abs(mbedtls_mpi *X, const mbedtls_mpi *A,
683                         const mbedtls_mpi *B);
684 
685 /**
686  * \brief          Perform an unsigned subtraction of MPIs: X = |A| - |B|
687  *
688  * \param X        The destination MPI. This must point to an initialized MPI.
689  * \param A        The minuend. This must point to an initialized MPI.
690  * \param B        The subtrahend. This must point to an initialized MPI.
691  *
692  * \return         \c 0 if successful.
693  * \return         #MBEDTLS_ERR_MPI_NEGATIVE_VALUE if \p B is greater than \p A.
694  * \return         Another negative error code on different kinds of failure.
695  *
696  */
697 int mbedtls_mpi_sub_abs(mbedtls_mpi *X, const mbedtls_mpi *A,
698                         const mbedtls_mpi *B);
699 
700 /**
701  * \brief          Perform a signed addition of MPIs: X = A + B
702  *
703  * \param X        The destination MPI. This must point to an initialized MPI.
704  * \param A        The first summand. This must point to an initialized MPI.
705  * \param B        The second summand. This must point to an initialized MPI.
706  *
707  * \return         \c 0 if successful.
708  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
709  * \return         Another negative error code on different kinds of failure.
710  */
711 int mbedtls_mpi_add_mpi(mbedtls_mpi *X, const mbedtls_mpi *A,
712                         const mbedtls_mpi *B);
713 
714 /**
715  * \brief          Perform a signed subtraction of MPIs: X = A - B
716  *
717  * \param X        The destination MPI. This must point to an initialized MPI.
718  * \param A        The minuend. This must point to an initialized MPI.
719  * \param B        The subtrahend. This must point to an initialized MPI.
720  *
721  * \return         \c 0 if successful.
722  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
723  * \return         Another negative error code on different kinds of failure.
724  */
725 int mbedtls_mpi_sub_mpi(mbedtls_mpi *X, const mbedtls_mpi *A,
726                         const mbedtls_mpi *B);
727 
728 /**
729  * \brief          Perform a signed addition of an MPI and an integer: X = A + b
730  *
731  * \param X        The destination MPI. This must point to an initialized MPI.
732  * \param A        The first summand. This must point to an initialized MPI.
733  * \param b        The second summand.
734  *
735  * \return         \c 0 if successful.
736  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
737  * \return         Another negative error code on different kinds of failure.
738  */
739 int mbedtls_mpi_add_int(mbedtls_mpi *X, const mbedtls_mpi *A,
740                         mbedtls_mpi_sint b);
741 
742 /**
743  * \brief          Perform a signed subtraction of an MPI and an integer:
744  *                 X = A - b
745  *
746  * \param X        The destination MPI. This must point to an initialized MPI.
747  * \param A        The minuend. This must point to an initialized MPI.
748  * \param b        The subtrahend.
749  *
750  * \return         \c 0 if successful.
751  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
752  * \return         Another negative error code on different kinds of failure.
753  */
754 int mbedtls_mpi_sub_int(mbedtls_mpi *X, const mbedtls_mpi *A,
755                         mbedtls_mpi_sint b);
756 
757 /**
758  * \brief          Perform a multiplication of two MPIs: X = A * B
759  *
760  * \param X        The destination MPI. This must point to an initialized MPI.
761  * \param A        The first factor. This must point to an initialized MPI.
762  * \param B        The second factor. This must point to an initialized MPI.
763  *
764  * \return         \c 0 if successful.
765  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
766  * \return         Another negative error code on different kinds of failure.
767  *
768  */
769 int mbedtls_mpi_mul_mpi(mbedtls_mpi *X, const mbedtls_mpi *A,
770                         const mbedtls_mpi *B);
771 
772 /**
773  * \brief          Perform a multiplication of an MPI with an unsigned integer:
774  *                 X = A * b
775  *
776  * \param X        The destination MPI. This must point to an initialized MPI.
777  * \param A        The first factor. This must point to an initialized MPI.
778  * \param b        The second factor.
779  *
780  * \return         \c 0 if successful.
781  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
782  * \return         Another negative error code on different kinds of failure.
783  *
784  */
785 int mbedtls_mpi_mul_int(mbedtls_mpi *X, const mbedtls_mpi *A,
786                         mbedtls_mpi_uint b);
787 
788 /**
789  * \brief          Perform a division with remainder of two MPIs:
790  *                 A = Q * B + R
791  *
792  * \param Q        The destination MPI for the quotient.
793  *                 This may be \c NULL if the value of the
794  *                 quotient is not needed. This must not alias A or B.
795  * \param R        The destination MPI for the remainder value.
796  *                 This may be \c NULL if the value of the
797  *                 remainder is not needed. This must not alias A or B.
798  * \param A        The dividend. This must point to an initialized MPI.
799  * \param B        The divisor. This must point to an initialized MPI.
800  *
801  * \return         \c 0 if successful.
802  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
803  * \return         #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p B equals zero.
804  * \return         Another negative error code on different kinds of failure.
805  */
806 int mbedtls_mpi_div_mpi(mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A,
807                         const mbedtls_mpi *B);
808 
809 /**
810  * \brief          Perform a division with remainder of an MPI by an integer:
811  *                 A = Q * b + R
812  *
813  * \param Q        The destination MPI for the quotient.
814  *                 This may be \c NULL if the value of the
815  *                 quotient is not needed.  This must not alias A.
816  * \param R        The destination MPI for the remainder value.
817  *                 This may be \c NULL if the value of the
818  *                 remainder is not needed.  This must not alias A.
819  * \param A        The dividend. This must point to an initialized MPi.
820  * \param b        The divisor.
821  *
822  * \return         \c 0 if successful.
823  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
824  * \return         #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p b equals zero.
825  * \return         Another negative error code on different kinds of failure.
826  */
827 int mbedtls_mpi_div_int(mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A,
828                         mbedtls_mpi_sint b);
829 
830 /**
831  * \brief          Perform a modular reduction. R = A mod B
832  *
833  * \param R        The destination MPI for the residue value.
834  *                 This must point to an initialized MPI.
835  * \param A        The MPI to compute the residue of.
836  *                 This must point to an initialized MPI.
837  * \param B        The base of the modular reduction.
838  *                 This must point to an initialized MPI.
839  *
840  * \return         \c 0 if successful.
841  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
842  * \return         #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p B equals zero.
843  * \return         #MBEDTLS_ERR_MPI_NEGATIVE_VALUE if \p B is negative.
844  * \return         Another negative error code on different kinds of failure.
845  *
846  */
847 int mbedtls_mpi_mod_mpi(mbedtls_mpi *R, const mbedtls_mpi *A,
848                         const mbedtls_mpi *B);
849 
850 /**
851  * \brief          Perform a modular reduction with respect to an integer.
852  *                 r = A mod b
853  *
854  * \param r        The address at which to store the residue.
855  *                 This must not be \c NULL.
856  * \param A        The MPI to compute the residue of.
857  *                 This must point to an initialized MPi.
858  * \param b        The integer base of the modular reduction.
859  *
860  * \return         \c 0 if successful.
861  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
862  * \return         #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p b equals zero.
863  * \return         #MBEDTLS_ERR_MPI_NEGATIVE_VALUE if \p b is negative.
864  * \return         Another negative error code on different kinds of failure.
865  */
866 int mbedtls_mpi_mod_int(mbedtls_mpi_uint *r, const mbedtls_mpi *A,
867                         mbedtls_mpi_sint b);
868 
869 /**
870  * \brief          Perform a sliding-window exponentiation: X = A^E mod N
871  *
872  * \param X        The destination MPI. This must point to an initialized MPI.
873  *                 This must not alias E or N.
874  * \param A        The base of the exponentiation.
875  *                 This must point to an initialized MPI.
876  * \param E        The exponent MPI. This must point to an initialized MPI.
877  * \param N        The base for the modular reduction. This must point to an
878  *                 initialized MPI.
879  * \param prec_RR  A helper MPI depending solely on \p N which can be used to
880  *                 speed-up multiple modular exponentiations for the same value
881  *                 of \p N. This may be \c NULL. If it is not \c NULL, it must
882  *                 point to an initialized MPI. If it hasn't been used after
883  *                 the call to mbedtls_mpi_init(), this function will compute
884  *                 the helper value and store it in \p prec_RR for reuse on
885  *                 subsequent calls to this function. Otherwise, the function
886  *                 will assume that \p prec_RR holds the helper value set by a
887  *                 previous call to mbedtls_mpi_exp_mod(), and reuse it.
888  *
889  * \return         \c 0 if successful.
890  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
891  * \return         #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \c N is negative or
892  *                 even, or if \c E is negative.
893  * \return         Another negative error code on different kinds of failures.
894  *
895  */
896 int mbedtls_mpi_exp_mod(mbedtls_mpi *X, const mbedtls_mpi *A,
897                         const mbedtls_mpi *E, const mbedtls_mpi *N,
898                         mbedtls_mpi *prec_RR);
899 
900 /**
901  * \brief          Fill an MPI with a number of random bytes.
902  *
903  * \param X        The destination MPI. This must point to an initialized MPI.
904  * \param size     The number of random bytes to generate.
905  * \param f_rng    The RNG function to use. This must not be \c NULL.
906  * \param p_rng    The RNG parameter to be passed to \p f_rng. This may be
907  *                 \c NULL if \p f_rng doesn't need a context argument.
908  *
909  * \return         \c 0 if successful.
910  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
911  * \return         Another negative error code on failure.
912  *
913  * \note           The bytes obtained from the RNG are interpreted
914  *                 as a big-endian representation of an MPI; this can
915  *                 be relevant in applications like deterministic ECDSA.
916  */
917 int mbedtls_mpi_fill_random(mbedtls_mpi *X, size_t size,
918                             int (*f_rng)(void *, unsigned char *, size_t),
919                             void *p_rng);
920 
921 /** Generate a random number uniformly in a range.
922  *
923  * This function generates a random number between \p min inclusive and
924  * \p N exclusive.
925  *
926  * The procedure complies with RFC 6979 §3.3 (deterministic ECDSA)
927  * when the RNG is a suitably parametrized instance of HMAC_DRBG
928  * and \p min is \c 1.
929  *
930  * \note           There are `N - min` possible outputs. The lower bound
931  *                 \p min can be reached, but the upper bound \p N cannot.
932  *
933  * \param X        The destination MPI. This must point to an initialized MPI.
934  * \param min      The minimum value to return.
935  *                 It must be nonnegative.
936  * \param N        The upper bound of the range, exclusive.
937  *                 In other words, this is one plus the maximum value to return.
938  *                 \p N must be strictly larger than \p min.
939  * \param f_rng    The RNG function to use. This must not be \c NULL.
940  * \param p_rng    The RNG parameter to be passed to \p f_rng.
941  *
942  * \return         \c 0 if successful.
943  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
944  * \return         #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p min or \p N is invalid
945  *                 or if they are incompatible.
946  * \return         #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if the implementation was
947  *                 unable to find a suitable value within a limited number
948  *                 of attempts. This has a negligible probability if \p N
949  *                 is significantly larger than \p min, which is the case
950  *                 for all usual cryptographic applications.
951  * \return         Another negative error code on failure.
952  */
953 int mbedtls_mpi_random(mbedtls_mpi *X,
954                        mbedtls_mpi_sint min,
955                        const mbedtls_mpi *N,
956                        int (*f_rng)(void *, unsigned char *, size_t),
957                        void *p_rng);
958 
959 /**
960  * \brief          Compute the greatest common divisor: G = gcd(A, B)
961  *
962  * \param G        The destination MPI. This must point to an initialized MPI.
963  * \param A        The first operand. This must point to an initialized MPI.
964  * \param B        The second operand. This must point to an initialized MPI.
965  *
966  * \return         \c 0 if successful.
967  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
968  * \return         Another negative error code on different kinds of failure.
969  */
970 int mbedtls_mpi_gcd(mbedtls_mpi *G, const mbedtls_mpi *A,
971                     const mbedtls_mpi *B);
972 
973 /**
974  * \brief          Compute the modular inverse: X = A^-1 mod N
975  *
976  * \param X        The destination MPI. This must point to an initialized MPI.
977  * \param A        The MPI to calculate the modular inverse of. This must point
978  *                 to an initialized MPI.
979  * \param N        The base of the modular inversion. This must point to an
980  *                 initialized MPI.
981  *
982  * \return         \c 0 if successful.
983  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
984  * \return         #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p N is less than
985  *                 or equal to one.
986  * \return         #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if \p has no modular inverse
987  *                 with respect to \p N.
988  */
989 int mbedtls_mpi_inv_mod(mbedtls_mpi *X, const mbedtls_mpi *A,
990                         const mbedtls_mpi *N);
991 
992 /**
993  * \brief          Miller-Rabin primality test.
994  *
995  * \warning        If \p X is potentially generated by an adversary, for example
996  *                 when validating cryptographic parameters that you didn't
997  *                 generate yourself and that are supposed to be prime, then
998  *                 \p rounds should be at least the half of the security
999  *                 strength of the cryptographic algorithm. On the other hand,
1000  *                 if \p X is chosen uniformly or non-adversarially (as is the
1001  *                 case when mbedtls_mpi_gen_prime calls this function), then
1002  *                 \p rounds can be much lower.
1003  *
1004  * \param X        The MPI to check for primality.
1005  *                 This must point to an initialized MPI.
1006  * \param rounds   The number of bases to perform the Miller-Rabin primality
1007  *                 test for. The probability of returning 0 on a composite is
1008  *                 at most 2<sup>-2*\p rounds </sup>.
1009  * \param f_rng    The RNG function to use. This must not be \c NULL.
1010  * \param p_rng    The RNG parameter to be passed to \p f_rng.
1011  *                 This may be \c NULL if \p f_rng doesn't use
1012  *                 a context parameter.
1013  *
1014  * \return         \c 0 if successful, i.e. \p X is probably prime.
1015  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
1016  * \return         #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if \p X is not prime.
1017  * \return         Another negative error code on other kinds of failure.
1018  */
1019 int mbedtls_mpi_is_prime_ext(const mbedtls_mpi *X, int rounds,
1020                              int (*f_rng)(void *, unsigned char *, size_t),
1021                              void *p_rng);
1022 /**
1023  * \brief Flags for mbedtls_mpi_gen_prime()
1024  *
1025  * Each of these flags is a constraint on the result X returned by
1026  * mbedtls_mpi_gen_prime().
1027  */
1028 typedef enum {
1029     MBEDTLS_MPI_GEN_PRIME_FLAG_DH =      0x0001, /**< (X-1)/2 is prime too */
1030     MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR = 0x0002, /**< lower error rate from 2<sup>-80</sup> to 2<sup>-128</sup> */
1031 } mbedtls_mpi_gen_prime_flag_t;
1032 
1033 /**
1034  * \brief          Generate a prime number.
1035  *
1036  * \param X        The destination MPI to store the generated prime in.
1037  *                 This must point to an initialized MPi.
1038  * \param nbits    The required size of the destination MPI in bits.
1039  *                 This must be between \c 3 and #MBEDTLS_MPI_MAX_BITS.
1040  * \param flags    A mask of flags of type #mbedtls_mpi_gen_prime_flag_t.
1041  * \param f_rng    The RNG function to use. This must not be \c NULL.
1042  * \param p_rng    The RNG parameter to be passed to \p f_rng.
1043  *                 This may be \c NULL if \p f_rng doesn't use
1044  *                 a context parameter.
1045  *
1046  * \return         \c 0 if successful, in which case \p X holds a
1047  *                 probably prime number.
1048  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
1049  * \return         #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if `nbits` is not between
1050  *                 \c 3 and #MBEDTLS_MPI_MAX_BITS.
1051  */
1052 int mbedtls_mpi_gen_prime(mbedtls_mpi *X, size_t nbits, int flags,
1053                           int (*f_rng)(void *, unsigned char *, size_t),
1054                           void *p_rng);
1055 
1056 #if defined(MBEDTLS_SELF_TEST)
1057 
1058 /**
1059  * \brief          Checkup routine
1060  *
1061  * \return         0 if successful, or 1 if the test failed
1062  */
1063 int mbedtls_mpi_self_test(int verbose);
1064 
1065 #endif /* MBEDTLS_SELF_TEST */
1066 
1067 #ifdef __cplusplus
1068 }
1069 #endif
1070 
1071 #endif /* bignum.h */
1072