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