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