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