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