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