Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:49

0001 /**
0002  * \file bignum.h
0003  *
0004  * \brief Multi-precision integer library
0005  */
0006 /*
0007  *  Copyright The Mbed TLS Contributors
0008  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
0009  */
0010 #ifndef MBEDTLS_BIGNUM_H
0011 #define MBEDTLS_BIGNUM_H
0012 #include "mbedtls/private_access.h"
0013 
0014 #include "tf-psa-crypto/build_info.h"
0015 #include "psa/crypto_values.h"
0016 
0017 #include <stddef.h>
0018 #include <stdint.h>
0019 
0020 #if defined(MBEDTLS_FS_IO)
0021 #include <stdio.h>
0022 #endif
0023 
0024 /** An error occurred while reading from or writing to a file. */
0025 #define MBEDTLS_ERR_MPI_FILE_IO_ERROR                     -0x0002
0026 /** Bad input parameters to function. */
0027 #define MBEDTLS_ERR_MPI_BAD_INPUT_DATA                    PSA_ERROR_INVALID_ARGUMENT
0028 /** There is an invalid character in the digit string. */
0029 #define MBEDTLS_ERR_MPI_INVALID_CHARACTER                 -0x0006
0030 /** The buffer is too small to write to. */
0031 #define MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL                  PSA_ERROR_BUFFER_TOO_SMALL
0032 /** The input arguments are negative or result in illegal output. */
0033 #define MBEDTLS_ERR_MPI_NEGATIVE_VALUE                    -0x000A
0034 /** The input argument for division is zero, which is not allowed. */
0035 #define MBEDTLS_ERR_MPI_DIVISION_BY_ZERO                  -0x000C
0036 /** The input arguments are not acceptable. */
0037 #define MBEDTLS_ERR_MPI_NOT_ACCEPTABLE                    -0x000E
0038 /** Memory allocation failed. */
0039 #define MBEDTLS_ERR_MPI_ALLOC_FAILED                      PSA_ERROR_INSUFFICIENT_MEMORY
0040 
0041 #define MBEDTLS_MPI_CHK(f)       \
0042     do                           \
0043     {                            \
0044         if ((ret = (f)) != 0) \
0045         goto cleanup;        \
0046     } while (0)
0047 
0048 /*
0049  * Maximum size MPIs are allowed to grow to in number of limbs.
0050  */
0051 #define MBEDTLS_MPI_MAX_LIMBS                             10000
0052 
0053 #if !defined(MBEDTLS_MPI_WINDOW_SIZE)
0054 /*
0055  * Maximum window size used for modular exponentiation. Default: 3
0056  * Minimum value: 1. Maximum value: 6.
0057  *
0058  * Result is an array of ( 2 ** MBEDTLS_MPI_WINDOW_SIZE ) MPIs used
0059  * for the sliding window calculation. (So 8 by default)
0060  *
0061  * Reduction in size, reduces speed.
0062  */
0063 #define MBEDTLS_MPI_WINDOW_SIZE                           3        /**< Maximum window size used. */
0064 #endif /* !MBEDTLS_MPI_WINDOW_SIZE */
0065 
0066 #if !defined(MBEDTLS_MPI_MAX_SIZE)
0067 /*
0068  * Maximum size of MPIs allowed in bits and bytes for user-MPIs.
0069  * ( Default: 512 bytes => 4096 bits, Maximum tested: 2048 bytes => 16384 bits )
0070  *
0071  * Note: Calculations can temporarily result in larger MPIs. So the number
0072  * of limbs required (MBEDTLS_MPI_MAX_LIMBS) is higher.
0073  */
0074 #define MBEDTLS_MPI_MAX_SIZE                              1024     /**< Maximum number of bytes for usable MPIs. */
0075 #endif /* !MBEDTLS_MPI_MAX_SIZE */
0076 
0077 #if defined(MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS)
0078 #define MBEDTLS_MPI_MAX_BITS                              (8 * MBEDTLS_MPI_MAX_SIZE)      /**< Maximum number of bits for usable MPIs. */
0079 
0080 /*
0081  * When reading from files with mbedtls_mpi_read_file() and writing to files with
0082  * mbedtls_mpi_write_file() the buffer should have space
0083  * for a (short) label, the MPI (in the provided radix), the newline
0084  * characters and the '\0'.
0085  *
0086  * By default we assume at least a 10 char label, a minimum radix of 10
0087  * (decimal) and a maximum of 4096 bit numbers (1234 decimal chars).
0088  * Autosized at compile time for at least a 10 char label, a minimum radix
0089  * of 10 (decimal) for a number of MBEDTLS_MPI_MAX_BITS size.
0090  *
0091  * This used to be statically sized to 1250 for a maximum of 4096 bit
0092  * numbers (1234 decimal chars).
0093  *
0094  * Calculate using the formula:
0095  *  MBEDTLS_MPI_RW_BUFFER_SIZE = ceil(MBEDTLS_MPI_MAX_BITS / ln(10) * ln(2)) +
0096  *                                LabelSize + 6
0097  */
0098 #define MBEDTLS_MPI_MAX_BITS_SCALE100          (100 * MBEDTLS_MPI_MAX_BITS)
0099 #define MBEDTLS_LN_2_DIV_LN_10_SCALE100                 332
0100 #define MBEDTLS_MPI_RW_BUFFER_SIZE             (((MBEDTLS_MPI_MAX_BITS_SCALE100 + \
0101                                                   MBEDTLS_LN_2_DIV_LN_10_SCALE100 - 1) / \
0102                                                  MBEDTLS_LN_2_DIV_LN_10_SCALE100) + 10 + 6)
0103 #endif /* MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS */
0104 
0105 /*
0106  * Define the base integer type, architecture-wise.
0107  *
0108  * 32 or 64-bit integer types can be forced regardless of the underlying
0109  * architecture by defining MBEDTLS_HAVE_INT32 or MBEDTLS_HAVE_INT64
0110  * respectively and undefining MBEDTLS_HAVE_ASM.
0111  *
0112  * Double-width integers (e.g. 128-bit in 64-bit architectures) can be
0113  * disabled by defining MBEDTLS_NO_UDBL_DIVISION.
0114  */
0115 #if !defined(MBEDTLS_HAVE_INT32)
0116     #if defined(_MSC_VER) && defined(_M_AMD64)
0117 /* Always choose 64-bit when using MSC */
0118         #if !defined(MBEDTLS_HAVE_INT64)
0119             #define MBEDTLS_HAVE_INT64
0120         #endif /* !MBEDTLS_HAVE_INT64 */
0121 typedef  int64_t mbedtls_mpi_sint;
0122 typedef uint64_t mbedtls_mpi_uint;
0123 #define MBEDTLS_MPI_UINT_MAX                UINT64_MAX
0124     #elif defined(__GNUC__) && (                         \
0125     defined(__amd64__) || defined(__x86_64__)     || \
0126     defined(__ppc64__) || defined(__powerpc64__)  || \
0127     defined(__ia64__)  || defined(__alpha__)      || \
0128     (defined(__sparc__) && defined(__arch64__)) || \
0129     defined(__s390x__) || defined(__mips64)       || \
0130     defined(__aarch64__))
0131         #if !defined(MBEDTLS_HAVE_INT64)
0132             #define MBEDTLS_HAVE_INT64
0133         #endif /* MBEDTLS_HAVE_INT64 */
0134 typedef  int64_t mbedtls_mpi_sint;
0135 typedef uint64_t mbedtls_mpi_uint;
0136 #define MBEDTLS_MPI_UINT_MAX                UINT64_MAX
0137         #if !defined(MBEDTLS_NO_UDBL_DIVISION)
0138 /* mbedtls_t_udbl defined as 128-bit unsigned int */
0139 typedef unsigned int mbedtls_t_udbl __attribute__((mode(TI)));
0140             #define MBEDTLS_HAVE_UDBL
0141         #endif /* !MBEDTLS_NO_UDBL_DIVISION */
0142     #elif defined(__ARMCC_VERSION) && defined(__aarch64__)
0143 /*
0144  * __ARMCC_VERSION is defined for both armcc and armclang and
0145  * __aarch64__ is only defined by armclang when compiling 64-bit code
0146  */
0147         #if !defined(MBEDTLS_HAVE_INT64)
0148             #define MBEDTLS_HAVE_INT64
0149         #endif /* !MBEDTLS_HAVE_INT64 */
0150 typedef  int64_t mbedtls_mpi_sint;
0151 typedef uint64_t mbedtls_mpi_uint;
0152 #define MBEDTLS_MPI_UINT_MAX                UINT64_MAX
0153         #if !defined(MBEDTLS_NO_UDBL_DIVISION)
0154 /* mbedtls_t_udbl defined as 128-bit unsigned int */
0155 typedef __uint128_t mbedtls_t_udbl;
0156             #define MBEDTLS_HAVE_UDBL
0157         #endif /* !MBEDTLS_NO_UDBL_DIVISION */
0158     #elif defined(MBEDTLS_HAVE_INT64)
0159 /* Force 64-bit integers with unknown compiler */
0160 typedef  int64_t mbedtls_mpi_sint;
0161 typedef uint64_t mbedtls_mpi_uint;
0162 #define MBEDTLS_MPI_UINT_MAX                UINT64_MAX
0163     #endif
0164 #endif /* !MBEDTLS_HAVE_INT32 */
0165 
0166 #if !defined(MBEDTLS_HAVE_INT64)
0167 /* Default to 32-bit compilation */
0168     #if !defined(MBEDTLS_HAVE_INT32)
0169         #define MBEDTLS_HAVE_INT32
0170     #endif /* !MBEDTLS_HAVE_INT32 */
0171 typedef  int32_t mbedtls_mpi_sint;
0172 typedef uint32_t mbedtls_mpi_uint;
0173 #define MBEDTLS_MPI_UINT_MAX                UINT32_MAX
0174     #if !defined(MBEDTLS_NO_UDBL_DIVISION)
0175 typedef uint64_t mbedtls_t_udbl;
0176         #define MBEDTLS_HAVE_UDBL
0177     #endif /* !MBEDTLS_NO_UDBL_DIVISION */
0178 #endif /* !MBEDTLS_HAVE_INT64 */
0179 
0180 /*
0181  * Sanity check that exactly one of MBEDTLS_HAVE_INT32 or MBEDTLS_HAVE_INT64 is defined,
0182  * so that code elsewhere doesn't have to check.
0183  */
0184 #if (!(defined(MBEDTLS_HAVE_INT32) || defined(MBEDTLS_HAVE_INT64))) || \
0185     (defined(MBEDTLS_HAVE_INT32) && defined(MBEDTLS_HAVE_INT64))
0186 #error "Only 32-bit or 64-bit limbs are supported in bignum"
0187 #endif
0188 
0189 /** \typedef mbedtls_mpi_uint
0190  * \brief The type of machine digits in a bignum, called _limbs_.
0191  *
0192  * This is always an unsigned integer type with no padding bits. The size
0193  * is platform-dependent.
0194  */
0195 
0196 /** \typedef mbedtls_mpi_sint
0197  * \brief The signed type corresponding to #mbedtls_mpi_uint.
0198  *
0199  * This is always an signed integer type with no padding bits. The size
0200  * is platform-dependent.
0201  */
0202 
0203 #ifdef __cplusplus
0204 extern "C" {
0205 #endif
0206 
0207 /**
0208  * \brief          MPI structure
0209  */
0210 typedef struct mbedtls_mpi {
0211     /** Pointer to limbs.
0212      *
0213      * This may be \c NULL if \c n is 0.
0214      */
0215     mbedtls_mpi_uint *MBEDTLS_PRIVATE(p);
0216 
0217     /** Sign: -1 if the mpi is negative, 1 otherwise.
0218      *
0219      * The number 0 must be represented with `s = +1`. Although many library
0220      * functions treat all-limbs-zero as equivalent to a valid representation
0221      * of 0 regardless of the sign bit, there are exceptions, so bignum
0222      * functions and external callers must always set \c s to +1 for the
0223      * number zero.
0224      *
0225      * Note that this implies that calloc() or `... = {0}` does not create
0226      * a valid MPI representation. You must call mbedtls_mpi_init().
0227      */
0228     signed short MBEDTLS_PRIVATE(s);
0229 
0230     /** Total number of limbs in \c p.  */
0231     unsigned short MBEDTLS_PRIVATE(n);
0232     /* Make sure that MBEDTLS_MPI_MAX_LIMBS fits in n.
0233      * Use the same limit value on all platforms so that we don't have to
0234      * think about different behavior on the rare platforms where
0235      * unsigned short can store values larger than the minimum required by
0236      * the C language, which is 65535.
0237      */
0238 #if MBEDTLS_MPI_MAX_LIMBS > 65535
0239 #error "MBEDTLS_MPI_MAX_LIMBS > 65535 is not supported"
0240 #endif
0241 }
0242 mbedtls_mpi;
0243 
0244 #define MBEDTLS_MPI_INIT { 0, 1, 0 }
0245 
0246 #if defined(MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS)
0247 /**
0248  * \brief           Initialize an MPI context.
0249  *
0250  *                  This makes the MPI ready to be set or freed,
0251  *                  but does not define a value for the MPI.
0252  *
0253  * \param X         The MPI context to initialize. This must not be \c NULL.
0254  */
0255 void mbedtls_mpi_init(mbedtls_mpi *X);
0256 
0257 /**
0258  * \brief          This function frees the components of an MPI context.
0259  *
0260  * \param X        The MPI context to be cleared. This may be \c NULL,
0261  *                 in which case this function is a no-op. If it is
0262  *                 not \c NULL, it must point to an initialized MPI.
0263  */
0264 void mbedtls_mpi_free(mbedtls_mpi *X);
0265 
0266 /**
0267  * \brief          Enlarge an MPI to the specified number of limbs.
0268  *
0269  * \note           This function does nothing if the MPI is
0270  *                 already large enough.
0271  *
0272  * \param X        The MPI to grow. It must be initialized.
0273  * \param nblimbs  The target number of limbs.
0274  *
0275  * \return         \c 0 if successful.
0276  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
0277  * \return         Another negative error code on other kinds of failure.
0278  */
0279 int mbedtls_mpi_grow(mbedtls_mpi *X, size_t nblimbs);
0280 
0281 /**
0282  * \brief          This function resizes an MPI downwards, keeping at least the
0283  *                 specified number of limbs.
0284  *
0285  *                 If \c X is smaller than \c nblimbs, it is resized up
0286  *                 instead.
0287  *
0288  * \param X        The MPI to shrink. This must point to an initialized MPI.
0289  * \param nblimbs  The minimum number of limbs to keep.
0290  *
0291  * \return         \c 0 if successful.
0292  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed
0293  *                 (this can only happen when resizing up).
0294  * \return         Another negative error code on other kinds of failure.
0295  */
0296 int mbedtls_mpi_shrink(mbedtls_mpi *X, size_t nblimbs);
0297 
0298 /**
0299  * \brief          Make a copy of an MPI.
0300  *
0301  * \param X        The destination MPI. This must point to an initialized MPI.
0302  * \param Y        The source MPI. This must point to an initialized MPI.
0303  *
0304  * \note           The limb-buffer in the destination MPI is enlarged
0305  *                 if necessary to hold the value in the source MPI.
0306  *
0307  * \return         \c 0 if successful.
0308  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
0309  * \return         Another negative error code on other kinds of failure.
0310  */
0311 int mbedtls_mpi_copy(mbedtls_mpi *X, const mbedtls_mpi *Y);
0312 
0313 /**
0314  * \brief          Swap the contents of two MPIs.
0315  *
0316  * \param X        The first MPI. It must be initialized.
0317  * \param Y        The second MPI. It must be initialized.
0318  */
0319 void mbedtls_mpi_swap(mbedtls_mpi *X, mbedtls_mpi *Y);
0320 
0321 /**
0322  * \brief          Perform a safe conditional copy of MPI which doesn't
0323  *                 reveal whether the condition was true or not.
0324  *
0325  * \param X        The MPI to conditionally assign to. This must point
0326  *                 to an initialized MPI.
0327  * \param Y        The MPI to be assigned from. This must point to an
0328  *                 initialized MPI.
0329  * \param assign   The condition deciding whether to perform the
0330  *                 assignment or not. Must be either 0 or 1:
0331  *                 * \c 1: Perform the assignment `X = Y`.
0332  *                 * \c 0: Keep the original value of \p X.
0333  *
0334  * \note           This function is equivalent to
0335  *                      `if( assign ) mbedtls_mpi_copy( X, Y );`
0336  *                 except that it avoids leaking any information about whether
0337  *                 the assignment was done or not (the above code may leak
0338  *                 information through branch prediction and/or memory access
0339  *                 patterns analysis).
0340  *
0341  * \warning        If \p assign is neither 0 nor 1, the result of this function
0342  *                 is indeterminate, and the resulting value in \p X might be
0343  *                 neither its original value nor the value in \p Y.
0344  *
0345  * \return         \c 0 if successful.
0346  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
0347  * \return         Another negative error code on other kinds of failure.
0348  */
0349 int mbedtls_mpi_safe_cond_assign(mbedtls_mpi *X, const mbedtls_mpi *Y, unsigned char assign);
0350 
0351 /**
0352  * \brief          Perform a safe conditional swap which doesn't
0353  *                 reveal whether the condition was true or not.
0354  *
0355  * \param X        The first MPI. This must be initialized.
0356  * \param Y        The second MPI. This must be initialized.
0357  * \param swap     The condition deciding whether to perform
0358  *                 the swap or not. Must be either 0 or 1:
0359  *                 * \c 1: Swap the values of \p X and \p Y.
0360  *                 * \c 0: Keep the original values of \p X and \p Y.
0361  *
0362  * \note           This function is equivalent to
0363  *                      if( swap ) mbedtls_mpi_swap( X, Y );
0364  *                 except that it avoids leaking any information about whether
0365  *                 the swap was done or not (the above code may leak
0366  *                 information through branch prediction and/or memory access
0367  *                 patterns analysis).
0368  *
0369  * \warning        If \p swap is neither 0 nor 1, the result of this function
0370  *                 is indeterminate, and both \p X and \p Y might end up with
0371  *                 values different to either of the original ones.
0372  *
0373  * \return         \c 0 if successful.
0374  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
0375  * \return         Another negative error code on other kinds of failure.
0376  *
0377  */
0378 int mbedtls_mpi_safe_cond_swap(mbedtls_mpi *X, mbedtls_mpi *Y, unsigned char swap);
0379 
0380 /**
0381  * \brief          Store integer value in MPI.
0382  *
0383  * \param X        The MPI to set. This must be initialized.
0384  * \param z        The value to use.
0385  *
0386  * \return         \c 0 if successful.
0387  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
0388  * \return         Another negative error code on other kinds of failure.
0389  */
0390 int mbedtls_mpi_lset(mbedtls_mpi *X, mbedtls_mpi_sint z);
0391 
0392 /**
0393  * \brief          Get a specific bit from an MPI.
0394  *
0395  * \param X        The MPI to query. This must be initialized.
0396  * \param pos      Zero-based index of the bit to query.
0397  *
0398  * \return         \c 0 or \c 1 on success, depending on whether bit \c pos
0399  *                 of \c X is unset or set.
0400  * \return         A negative error code on failure.
0401  */
0402 int mbedtls_mpi_get_bit(const mbedtls_mpi *X, size_t pos);
0403 
0404 /**
0405  * \brief          Modify a specific bit in an MPI.
0406  *
0407  * \note           This function will grow the target MPI if necessary to set a
0408  *                 bit to \c 1 in a not yet existing limb. It will not grow if
0409  *                 the bit should be set to \c 0.
0410  *
0411  * \param X        The MPI to modify. This must be initialized.
0412  * \param pos      Zero-based index of the bit to modify.
0413  * \param val      The desired value of bit \c pos: \c 0 or \c 1.
0414  *
0415  * \return         \c 0 if successful.
0416  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
0417  * \return         Another negative error code on other kinds of failure.
0418  */
0419 int mbedtls_mpi_set_bit(mbedtls_mpi *X, size_t pos, unsigned char val);
0420 
0421 /**
0422  * \brief          Return the number of bits of value \c 0 before the
0423  *                 least significant bit of value \c 1.
0424  *
0425  * \note           This is the same as the zero-based index of
0426  *                 the least significant bit of value \c 1.
0427  *
0428  * \param X        The MPI to query.
0429  *
0430  * \return         The number of bits of value \c 0 before the least significant
0431  *                 bit of value \c 1 in \p X.
0432  */
0433 size_t mbedtls_mpi_lsb(const mbedtls_mpi *X);
0434 
0435 /**
0436  * \brief          Return the number of bits up to and including the most
0437  *                 significant bit of value \c 1.
0438  *
0439  * * \note         This is same as the one-based index of the most
0440  *                 significant bit of value \c 1.
0441  *
0442  * \param X        The MPI to query. This must point to an initialized MPI.
0443  *
0444  * \return         The number of bits up to and including the most
0445  *                 significant bit of value \c 1.
0446  */
0447 size_t mbedtls_mpi_bitlen(const mbedtls_mpi *X);
0448 
0449 /**
0450  * \brief          Return the total size of an MPI value in bytes.
0451  *
0452  * \param X        The MPI to use. This must point to an initialized MPI.
0453  *
0454  * \note           The value returned by this function may be less than
0455  *                 the number of bytes used to store \p X internally.
0456  *                 This happens if and only if there are trailing bytes
0457  *                 of value zero.
0458  *
0459  * \return         The least number of bytes capable of storing
0460  *                 the absolute value of \p X.
0461  */
0462 size_t mbedtls_mpi_size(const mbedtls_mpi *X);
0463 
0464 /**
0465  * \brief          Import an MPI from an ASCII string.
0466  *
0467  * \param X        The destination MPI. This must point to an initialized MPI.
0468  * \param radix    The numeric base of the input string.
0469  * \param s        Null-terminated string buffer.
0470  *
0471  * \return         \c 0 if successful.
0472  * \return         A negative error code on failure.
0473  */
0474 int mbedtls_mpi_read_string(mbedtls_mpi *X, int radix, const char *s);
0475 
0476 /**
0477  * \brief          Export an MPI to an ASCII string.
0478  *
0479  * \param X        The source MPI. This must point to an initialized MPI.
0480  * \param radix    The numeric base of the output string.
0481  * \param buf      The buffer to write the string to. This must be writable
0482  *                 buffer of length \p buflen Bytes.
0483  * \param buflen   The available size in Bytes of \p buf.
0484  * \param olen     The address at which to store the length of the string
0485  *                 written, including the  final \c NULL byte. This must
0486  *                 not be \c NULL.
0487  *
0488  * \note           You can call this function with `buflen == 0` to obtain the
0489  *                 minimum required buffer size in `*olen`.
0490  *
0491  * \return         \c 0 if successful.
0492  * \return         #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if the target buffer \p buf
0493  *                 is too small to hold the value of \p X in the desired base.
0494  *                 In this case, `*olen` is nonetheless updated to contain the
0495  *                 size of \p buf required for a successful call.
0496  * \return         Another negative error code on different kinds of failure.
0497  */
0498 int mbedtls_mpi_write_string(const mbedtls_mpi *X, int radix,
0499                              char *buf, size_t buflen, size_t *olen);
0500 
0501 #if defined(MBEDTLS_FS_IO)
0502 /**
0503  * \brief          Read an MPI from a line in an opened file.
0504  *
0505  * \param X        The destination MPI. This must point to an initialized MPI.
0506  * \param radix    The numeric base of the string representation used
0507  *                 in the source line.
0508  * \param fin      The input file handle to use. This must not be \c NULL.
0509  *
0510  * \note           On success, this function advances the file stream
0511  *                 to the end of the current line or to EOF.
0512  *
0513  *                 The function returns \c 0 on an empty line.
0514  *
0515  *                 Leading whitespaces are ignored, as is a
0516  *                 '0x' prefix for radix \c 16.
0517  *
0518  * \return         \c 0 if successful.
0519  * \return         #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if the file read buffer
0520  *                 is too small.
0521  * \return         Another negative error code on failure.
0522  */
0523 int mbedtls_mpi_read_file(mbedtls_mpi *X, int radix, FILE *fin);
0524 
0525 /**
0526  * \brief          Export an MPI into an opened file.
0527  *
0528  * \param p        A string prefix to emit prior to the MPI data.
0529  *                 For example, this might be a label, or "0x" when
0530  *                 printing in base \c 16. This may be \c NULL if no prefix
0531  *                 is needed.
0532  * \param X        The source MPI. This must point to an initialized MPI.
0533  * \param radix    The numeric base to be used in the emitted string.
0534  * \param fout     The output file handle. This may be \c NULL, in which case
0535  *                 the output is written to \c stdout.
0536  *
0537  * \return         \c 0 if successful.
0538  * \return         A negative error code on failure.
0539  */
0540 int mbedtls_mpi_write_file(const char *p, const mbedtls_mpi *X,
0541                            int radix, FILE *fout);
0542 #endif /* MBEDTLS_FS_IO */
0543 
0544 /**
0545  * \brief          Import an MPI from unsigned big endian binary data.
0546  *
0547  * \param X        The destination MPI. This must point to an initialized MPI.
0548  * \param buf      The input buffer. This must be a readable buffer of length
0549  *                 \p buflen Bytes.
0550  * \param buflen   The length of the input buffer \p buf in Bytes.
0551  *
0552  * \return         \c 0 if successful.
0553  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
0554  * \return         Another negative error code on different kinds of failure.
0555  */
0556 int mbedtls_mpi_read_binary(mbedtls_mpi *X, const unsigned char *buf,
0557                             size_t buflen);
0558 
0559 /**
0560  * \brief          Import X from unsigned binary data, little endian
0561  *
0562  * \param X        The destination MPI. This must point to an initialized MPI.
0563  * \param buf      The input buffer. This must be a readable buffer of length
0564  *                 \p buflen Bytes.
0565  * \param buflen   The length of the input buffer \p buf in Bytes.
0566  *
0567  * \return         \c 0 if successful.
0568  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
0569  * \return         Another negative error code on different kinds of failure.
0570  */
0571 int mbedtls_mpi_read_binary_le(mbedtls_mpi *X,
0572                                const unsigned char *buf, size_t buflen);
0573 
0574 /**
0575  * \brief          Export X into unsigned binary data, big endian.
0576  *                 Always fills the whole buffer, which will start with zeros
0577  *                 if the number is smaller.
0578  *
0579  * \param X        The source MPI. This must point to an initialized MPI.
0580  * \param buf      The output buffer. This must be a writable buffer of length
0581  *                 \p buflen Bytes.
0582  * \param buflen   The size of the output buffer \p buf in Bytes.
0583  *
0584  * \return         \c 0 if successful.
0585  * \return         #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p buf isn't
0586  *                 large enough to hold the value of \p X.
0587  * \return         Another negative error code on different kinds of failure.
0588  */
0589 int mbedtls_mpi_write_binary(const mbedtls_mpi *X, unsigned char *buf,
0590                              size_t buflen);
0591 
0592 /**
0593  * \brief          Export X into unsigned binary data, little endian.
0594  *                 Always fills the whole buffer, which will end with zeros
0595  *                 if the number is smaller.
0596  *
0597  * \param X        The source MPI. This must point to an initialized MPI.
0598  * \param buf      The output buffer. This must be a writable buffer of length
0599  *                 \p buflen Bytes.
0600  * \param buflen   The size of the output buffer \p buf in Bytes.
0601  *
0602  * \return         \c 0 if successful.
0603  * \return         #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p buf isn't
0604  *                 large enough to hold the value of \p X.
0605  * \return         Another negative error code on different kinds of failure.
0606  */
0607 int mbedtls_mpi_write_binary_le(const mbedtls_mpi *X,
0608                                 unsigned char *buf, size_t buflen);
0609 
0610 /**
0611  * \brief          Perform a left-shift on an MPI: X <<= count
0612  *
0613  * \param X        The MPI to shift. This must point to an initialized MPI.
0614  *                 The MPI pointed by \p X may be resized to fit
0615  *                 the resulting number.
0616  * \param count    The number of bits to shift by.
0617  *
0618  * \return         \c 0 if successful.
0619  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
0620  * \return         Another negative error code on different kinds of failure.
0621  */
0622 int mbedtls_mpi_shift_l(mbedtls_mpi *X, size_t count);
0623 
0624 /**
0625  * \brief          Perform a right-shift on an MPI: X >>= count
0626  *
0627  * \param X        The MPI to shift. This must point to an initialized MPI.
0628  * \param count    The number of bits to shift by.
0629  *
0630  * \return         \c 0 if successful.
0631  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
0632  * \return         Another negative error code on different kinds of failure.
0633  */
0634 int mbedtls_mpi_shift_r(mbedtls_mpi *X, size_t count);
0635 
0636 /**
0637  * \brief          Compare the absolute values of two MPIs.
0638  *
0639  * \param X        The left-hand MPI. This must point to an initialized MPI.
0640  * \param Y        The right-hand MPI. This must point to an initialized MPI.
0641  *
0642  * \return         \c 1 if `|X|` is greater than `|Y|`.
0643  * \return         \c -1 if `|X|` is lesser than `|Y|`.
0644  * \return         \c 0 if `|X|` is equal to `|Y|`.
0645  */
0646 int mbedtls_mpi_cmp_abs(const mbedtls_mpi *X, const mbedtls_mpi *Y);
0647 
0648 /**
0649  * \brief          Compare two MPIs.
0650  *
0651  * \param X        The left-hand MPI. This must point to an initialized MPI.
0652  * \param Y        The right-hand MPI. This must point to an initialized MPI.
0653  *
0654  * \return         \c 1 if \p X is greater than \p Y.
0655  * \return         \c -1 if \p X is lesser than \p Y.
0656  * \return         \c 0 if \p X is equal to \p Y.
0657  */
0658 int mbedtls_mpi_cmp_mpi(const mbedtls_mpi *X, const mbedtls_mpi *Y);
0659 
0660 /**
0661  * \brief          Check if an MPI is less than the other in constant time.
0662  *
0663  * \param X        The left-hand MPI. This must point to an initialized MPI
0664  *                 with the same allocated length as Y.
0665  * \param Y        The right-hand MPI. This must point to an initialized MPI
0666  *                 with the same allocated length as X.
0667  * \param ret      The result of the comparison:
0668  *                 \c 1 if \p X is less than \p Y.
0669  *                 \c 0 if \p X is greater than or equal to \p Y.
0670  *
0671  * \return         0 on success.
0672  * \return         MBEDTLS_ERR_MPI_BAD_INPUT_DATA if the allocated length of
0673  *                 the two input MPIs is not the same.
0674  */
0675 int mbedtls_mpi_lt_mpi_ct(const mbedtls_mpi *X, const mbedtls_mpi *Y,
0676                           unsigned *ret);
0677 
0678 /**
0679  * \brief          Compare an MPI with an integer.
0680  *
0681  * \param X        The left-hand MPI. This must point to an initialized MPI.
0682  * \param z        The integer value to compare \p X to.
0683  *
0684  * \return         \c 1 if \p X is greater than \p z.
0685  * \return         \c -1 if \p X is lesser than \p z.
0686  * \return         \c 0 if \p X is equal to \p z.
0687  */
0688 int mbedtls_mpi_cmp_int(const mbedtls_mpi *X, mbedtls_mpi_sint z);
0689 
0690 /**
0691  * \brief          Perform an unsigned addition of MPIs: X = |A| + |B|
0692  *
0693  * \param X        The destination MPI. This must point to an initialized MPI.
0694  * \param A        The first summand. This must point to an initialized MPI.
0695  * \param B        The second summand. This must point to an initialized MPI.
0696  *
0697  * \return         \c 0 if successful.
0698  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
0699  * \return         Another negative error code on different kinds of failure.
0700  */
0701 int mbedtls_mpi_add_abs(mbedtls_mpi *X, const mbedtls_mpi *A,
0702                         const mbedtls_mpi *B);
0703 
0704 /**
0705  * \brief          Perform an unsigned subtraction of MPIs: X = |A| - |B|
0706  *
0707  * \param X        The destination MPI. This must point to an initialized MPI.
0708  * \param A        The minuend. This must point to an initialized MPI.
0709  * \param B        The subtrahend. This must point to an initialized MPI.
0710  *
0711  * \return         \c 0 if successful.
0712  * \return         #MBEDTLS_ERR_MPI_NEGATIVE_VALUE if \p B is greater than \p A.
0713  * \return         Another negative error code on different kinds of failure.
0714  *
0715  */
0716 int mbedtls_mpi_sub_abs(mbedtls_mpi *X, const mbedtls_mpi *A,
0717                         const mbedtls_mpi *B);
0718 
0719 /**
0720  * \brief          Perform a signed addition of MPIs: X = A + B
0721  *
0722  * \param X        The destination MPI. This must point to an initialized MPI.
0723  * \param A        The first summand. This must point to an initialized MPI.
0724  * \param B        The second summand. This must point to an initialized MPI.
0725  *
0726  * \return         \c 0 if successful.
0727  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
0728  * \return         Another negative error code on different kinds of failure.
0729  */
0730 int mbedtls_mpi_add_mpi(mbedtls_mpi *X, const mbedtls_mpi *A,
0731                         const mbedtls_mpi *B);
0732 
0733 /**
0734  * \brief          Perform a signed subtraction of MPIs: X = A - B
0735  *
0736  * \param X        The destination MPI. This must point to an initialized MPI.
0737  * \param A        The minuend. This must point to an initialized MPI.
0738  * \param B        The subtrahend. This must point to an initialized MPI.
0739  *
0740  * \return         \c 0 if successful.
0741  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
0742  * \return         Another negative error code on different kinds of failure.
0743  */
0744 int mbedtls_mpi_sub_mpi(mbedtls_mpi *X, const mbedtls_mpi *A,
0745                         const mbedtls_mpi *B);
0746 
0747 /**
0748  * \brief          Perform a signed addition of an MPI and an integer: X = A + b
0749  *
0750  * \param X        The destination MPI. This must point to an initialized MPI.
0751  * \param A        The first summand. This must point to an initialized MPI.
0752  * \param b        The second summand.
0753  *
0754  * \return         \c 0 if successful.
0755  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
0756  * \return         Another negative error code on different kinds of failure.
0757  */
0758 int mbedtls_mpi_add_int(mbedtls_mpi *X, const mbedtls_mpi *A,
0759                         mbedtls_mpi_sint b);
0760 
0761 /**
0762  * \brief          Perform a signed subtraction of an MPI and an integer:
0763  *                 X = A - b
0764  *
0765  * \param X        The destination MPI. This must point to an initialized MPI.
0766  * \param A        The minuend. This must point to an initialized MPI.
0767  * \param b        The subtrahend.
0768  *
0769  * \return         \c 0 if successful.
0770  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
0771  * \return         Another negative error code on different kinds of failure.
0772  */
0773 int mbedtls_mpi_sub_int(mbedtls_mpi *X, const mbedtls_mpi *A,
0774                         mbedtls_mpi_sint b);
0775 
0776 /**
0777  * \brief          Perform a multiplication of two MPIs: X = A * B
0778  *
0779  * \param X        The destination MPI. This must point to an initialized MPI.
0780  * \param A        The first factor. This must point to an initialized MPI.
0781  * \param B        The second factor. This must point to an initialized MPI.
0782  *
0783  * \return         \c 0 if successful.
0784  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
0785  * \return         Another negative error code on different kinds of failure.
0786  *
0787  */
0788 int mbedtls_mpi_mul_mpi(mbedtls_mpi *X, const mbedtls_mpi *A,
0789                         const mbedtls_mpi *B);
0790 
0791 /**
0792  * \brief          Perform a multiplication of an MPI with an unsigned integer:
0793  *                 X = A * b
0794  *
0795  * \param X        The destination MPI. This must point to an initialized MPI.
0796  * \param A        The first factor. This must point to an initialized MPI.
0797  * \param b        The second factor.
0798  *
0799  * \return         \c 0 if successful.
0800  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
0801  * \return         Another negative error code on different kinds of failure.
0802  *
0803  */
0804 int mbedtls_mpi_mul_int(mbedtls_mpi *X, const mbedtls_mpi *A,
0805                         mbedtls_mpi_uint b);
0806 
0807 /**
0808  * \brief          Perform a division with remainder of two MPIs:
0809  *                 A = Q * B + R
0810  *
0811  * \param Q        The destination MPI for the quotient.
0812  *                 This may be \c NULL if the value of the
0813  *                 quotient is not needed. This must not alias A or B.
0814  * \param R        The destination MPI for the remainder value.
0815  *                 This may be \c NULL if the value of the
0816  *                 remainder is not needed. This must not alias A or B.
0817  * \param A        The dividend. This must point to an initialized MPI.
0818  * \param B        The divisor. This must point to an initialized MPI.
0819  *
0820  * \return         \c 0 if successful.
0821  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
0822  * \return         #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p B equals zero.
0823  * \return         Another negative error code on different kinds of failure.
0824  */
0825 int mbedtls_mpi_div_mpi(mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A,
0826                         const mbedtls_mpi *B);
0827 
0828 /**
0829  * \brief          Perform a division with remainder of an MPI by an integer:
0830  *                 A = Q * b + R
0831  *
0832  * \param Q        The destination MPI for the quotient.
0833  *                 This may be \c NULL if the value of the
0834  *                 quotient is not needed.  This must not alias A.
0835  * \param R        The destination MPI for the remainder value.
0836  *                 This may be \c NULL if the value of the
0837  *                 remainder is not needed.  This must not alias A.
0838  * \param A        The dividend. This must point to an initialized MPi.
0839  * \param b        The divisor.
0840  *
0841  * \return         \c 0 if successful.
0842  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
0843  * \return         #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p b equals zero.
0844  * \return         Another negative error code on different kinds of failure.
0845  */
0846 int mbedtls_mpi_div_int(mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A,
0847                         mbedtls_mpi_sint b);
0848 
0849 /**
0850  * \brief          Perform a modular reduction. R = A mod B
0851  *
0852  * \param R        The destination MPI for the residue value.
0853  *                 This must point to an initialized MPI.
0854  * \param A        The MPI to compute the residue of.
0855  *                 This must point to an initialized MPI.
0856  * \param B        The base of the modular reduction.
0857  *                 This must point to an initialized MPI.
0858  *
0859  * \return         \c 0 if successful.
0860  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
0861  * \return         #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p B equals zero.
0862  * \return         #MBEDTLS_ERR_MPI_NEGATIVE_VALUE if \p B is negative.
0863  * \return         Another negative error code on different kinds of failure.
0864  *
0865  */
0866 int mbedtls_mpi_mod_mpi(mbedtls_mpi *R, const mbedtls_mpi *A,
0867                         const mbedtls_mpi *B);
0868 
0869 /**
0870  * \brief          Perform a modular reduction with respect to an integer.
0871  *                 r = A mod b
0872  *
0873  * \param r        The address at which to store the residue.
0874  *                 This must not be \c NULL.
0875  * \param A        The MPI to compute the residue of.
0876  *                 This must point to an initialized MPi.
0877  * \param b        The integer base of the modular reduction.
0878  *
0879  * \return         \c 0 if successful.
0880  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
0881  * \return         #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p b equals zero.
0882  * \return         #MBEDTLS_ERR_MPI_NEGATIVE_VALUE if \p b is negative.
0883  * \return         Another negative error code on different kinds of failure.
0884  */
0885 int mbedtls_mpi_mod_int(mbedtls_mpi_uint *r, const mbedtls_mpi *A,
0886                         mbedtls_mpi_sint b);
0887 
0888 /**
0889  * \brief          Perform a modular exponentiation: X = A^E mod N
0890  *
0891  * \param X        The destination MPI. This must point to an initialized MPI.
0892  *                 This must not alias E or N.
0893  * \param A        The base of the exponentiation.
0894  *                 This must point to an initialized MPI.
0895  * \param E        The exponent MPI. This must point to an initialized MPI.
0896  * \param N        The base for the modular reduction. This must point to an
0897  *                 initialized MPI.
0898  * \param prec_RR  A helper MPI depending solely on \p N which can be used to
0899  *                 speed-up multiple modular exponentiations for the same value
0900  *                 of \p N. This may be \c NULL. If it is not \c NULL, it must
0901  *                 point to an initialized MPI. If it hasn't been used after
0902  *                 the call to mbedtls_mpi_init(), this function will compute
0903  *                 the helper value and store it in \p prec_RR for reuse on
0904  *                 subsequent calls to this function. Otherwise, the function
0905  *                 will assume that \p prec_RR holds the helper value set by a
0906  *                 previous call to mbedtls_mpi_exp_mod(), and reuse it.
0907  *
0908  * \return         \c 0 if successful.
0909  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
0910  * \return         #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \c N is negative or
0911  *                 even, or if \c E is negative.
0912  * \return         Another negative error code on different kinds of failures.
0913  *
0914  */
0915 int mbedtls_mpi_exp_mod(mbedtls_mpi *X, const mbedtls_mpi *A,
0916                         const mbedtls_mpi *E, const mbedtls_mpi *N,
0917                         mbedtls_mpi *prec_RR);
0918 
0919 /**
0920  * \brief          Fill an MPI with a number of random bytes.
0921  *
0922  * \param X        The destination MPI. This must point to an initialized MPI.
0923  * \param size     The number of random bytes to generate.
0924  * \param f_rng    The RNG function to use. This must not be \c NULL.
0925  * \param p_rng    The RNG parameter to be passed to \p f_rng. This may be
0926  *                 \c NULL if \p f_rng doesn't need a context argument.
0927  *
0928  * \return         \c 0 if successful.
0929  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
0930  * \return         Another negative error code on failure.
0931  *
0932  * \note           The bytes obtained from the RNG are interpreted
0933  *                 as a big-endian representation of an MPI; this can
0934  *                 be relevant in applications like deterministic ECDSA.
0935  */
0936 int mbedtls_mpi_fill_random(mbedtls_mpi *X, size_t size,
0937                             int (*f_rng)(void *, unsigned char *, size_t),
0938                             void *p_rng);
0939 
0940 /** Generate a random number uniformly in a range.
0941  *
0942  * This function generates a random number between \p min inclusive and
0943  * \p N exclusive.
0944  *
0945  * The procedure complies with RFC 6979 ยง3.3 (deterministic ECDSA)
0946  * when the RNG is a suitably parametrized instance of HMAC_DRBG
0947  * and \p min is \c 1.
0948  *
0949  * \note           There are `N - min` possible outputs. The lower bound
0950  *                 \p min can be reached, but the upper bound \p N cannot.
0951  *
0952  * \param X        The destination MPI. This must point to an initialized MPI.
0953  * \param min      The minimum value to return.
0954  *                 It must be nonnegative.
0955  * \param N        The upper bound of the range, exclusive.
0956  *                 In other words, this is one plus the maximum value to return.
0957  *                 \p N must be strictly larger than \p min.
0958  * \param f_rng    The RNG function to use. This must not be \c NULL.
0959  * \param p_rng    The RNG parameter to be passed to \p f_rng.
0960  *
0961  * \return         \c 0 if successful.
0962  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
0963  * \return         #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p min or \p N is invalid
0964  *                 or if they are incompatible.
0965  * \return         #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if the implementation was
0966  *                 unable to find a suitable value within a limited number
0967  *                 of attempts. This has a negligible probability if \p N
0968  *                 is significantly larger than \p min, which is the case
0969  *                 for all usual cryptographic applications.
0970  * \return         Another negative error code on failure.
0971  */
0972 int mbedtls_mpi_random(mbedtls_mpi *X,
0973                        mbedtls_mpi_sint min,
0974                        const mbedtls_mpi *N,
0975                        int (*f_rng)(void *, unsigned char *, size_t),
0976                        void *p_rng);
0977 
0978 /**
0979  * \brief          Compute the greatest common divisor: G = gcd(A, B)
0980  *
0981  * \param G        The destination MPI. This must point to an initialized MPI.
0982  *                 This will always be positive or 0.
0983  * \param A        The first operand. This must point to an initialized MPI.
0984  * \param B        The second operand. This must point to an initialized MPI.
0985  *
0986  * \return         \c 0 if successful.
0987  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
0988  * \return         Another negative error code on different kinds of failure.
0989  */
0990 int mbedtls_mpi_gcd(mbedtls_mpi *G, const mbedtls_mpi *A,
0991                     const mbedtls_mpi *B);
0992 
0993 /**
0994  * \brief          Compute the modular inverse: X = A^-1 mod N
0995  *
0996  * \param X        The destination MPI. This must point to an initialized MPI.
0997  *                 The value returned on success will be between [1, N-1].
0998  * \param A        The MPI to calculate the modular inverse of. This must point
0999  *                 to an initialized MPI. This value can be negative, in which
1000  *                 case a positive answer will still be returned in \p X.
1001  * \param N        The base of the modular inversion. This must point to an
1002  *                 initialized MPI and be greater than one.
1003  *
1004  * \return         \c 0 if successful.
1005  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
1006  * \return         #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p N is less than
1007  *                 or equal to one.
1008  * \return         #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if \p A has no modular
1009  *                 inverse with respect to \p N.
1010  */
1011 int mbedtls_mpi_inv_mod(mbedtls_mpi *X, const mbedtls_mpi *A,
1012                         const mbedtls_mpi *N);
1013 
1014 /**
1015  * \brief          Miller-Rabin primality test.
1016  *
1017  * \warning        If \p X is potentially generated by an adversary, for example
1018  *                 when validating cryptographic parameters that you didn't
1019  *                 generate yourself and that are supposed to be prime, then
1020  *                 \p rounds should be at least the half of the security
1021  *                 strength of the cryptographic algorithm. On the other hand,
1022  *                 if \p X is chosen uniformly or non-adversarially (as is the
1023  *                 case when mbedtls_mpi_gen_prime calls this function), then
1024  *                 \p rounds can be much lower.
1025  *
1026  * \param X        The MPI to check for primality.
1027  *                 This must point to an initialized MPI.
1028  * \param rounds   The number of bases to perform the Miller-Rabin primality
1029  *                 test for. The probability of returning 0 on a composite is
1030  *                 at most 2<sup>-2*\p rounds </sup>.
1031  * \param f_rng    The RNG function to use. This must not be \c NULL.
1032  * \param p_rng    The RNG parameter to be passed to \p f_rng.
1033  *                 This may be \c NULL if \p f_rng doesn't use
1034  *                 a context parameter.
1035  *
1036  * \return         \c 0 if successful, i.e. \p X is probably prime.
1037  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
1038  * \return         #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if \p X is not prime.
1039  * \return         Another negative error code on other kinds of failure.
1040  */
1041 int mbedtls_mpi_is_prime_ext(const mbedtls_mpi *X, int rounds,
1042                              int (*f_rng)(void *, unsigned char *, size_t),
1043                              void *p_rng);
1044 /**
1045  * \brief Flags for mbedtls_mpi_gen_prime()
1046  *
1047  * Each of these flags is a constraint on the result X returned by
1048  * mbedtls_mpi_gen_prime().
1049  */
1050 typedef enum {
1051     MBEDTLS_MPI_GEN_PRIME_FLAG_DH =      0x0001, /**< (X-1)/2 is prime too */
1052     MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR = 0x0002, /**< lower error rate from 2<sup>-80</sup> to 2<sup>-128</sup> */
1053 } mbedtls_mpi_gen_prime_flag_t;
1054 
1055 /**
1056  * \brief          Generate a prime number.
1057  *
1058  * \param X        The destination MPI to store the generated prime in.
1059  *                 This must point to an initialized MPi.
1060  * \param nbits    The required size of the destination MPI in bits.
1061  *                 This must be between \c 3 and #MBEDTLS_MPI_MAX_BITS.
1062  * \param flags    A mask of flags of type #mbedtls_mpi_gen_prime_flag_t.
1063  * \param f_rng    The RNG function to use. This must not be \c NULL.
1064  * \param p_rng    The RNG parameter to be passed to \p f_rng.
1065  *                 This may be \c NULL if \p f_rng doesn't use
1066  *                 a context parameter.
1067  *
1068  * \return         \c 0 if successful, in which case \p X holds a
1069  *                 probably prime number.
1070  * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
1071  * \return         #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if `nbits` is not between
1072  *                 \c 3 and #MBEDTLS_MPI_MAX_BITS.
1073  */
1074 int mbedtls_mpi_gen_prime(mbedtls_mpi *X, size_t nbits, int flags,
1075                           int (*f_rng)(void *, unsigned char *, size_t),
1076                           void *p_rng);
1077 
1078 /**
1079  * \brief       Retrieve an integer ASN.1 tag and its value.
1080  *              Updates the pointer to immediately behind the full tag.
1081  *              Legacy function, which is now for internal use only.
1082  *              Please use mbedtls_asn1_get_integer() instead.
1083  *
1084  * \param p     On entry, \c *p points to the start of the ASN.1 element.
1085  *              On successful completion, \c *p points to the first byte
1086  *              beyond the ASN.1 element.
1087  *              On error, the value of \c *p is undefined.
1088  * \param end   End of data.
1089  * \param X     On success, the parsed value.
1090  *
1091  * \return      0 if successful.
1092  * \return      An ASN.1 error code if the input does not start with
1093  *              a valid ASN.1 INTEGER.
1094  * \return      #MBEDTLS_ERR_ASN1_INVALID_LENGTH if the parsed value does
1095  *              not fit in an \c int.
1096  * \return      An MPI error code if the parsed value is too large.
1097  */
1098 int mbedtls_asn1_get_mpi(unsigned char **p,
1099                          const unsigned char *end,
1100                          mbedtls_mpi *X);
1101 
1102 #if defined(MBEDTLS_SELF_TEST)
1103 
1104 /**
1105  * \brief          Checkup routine
1106  *
1107  * \return         0 if successful, or 1 if the test failed
1108  */
1109 int mbedtls_mpi_self_test(int verbose);
1110 
1111 #endif /* MBEDTLS_SELF_TEST */
1112 
1113 #endif /* MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS */
1114 /**
1115  * \brief           Write an arbitrary-precision number (#MBEDTLS_ASN1_INTEGER)
1116  *                  in ASN.1 format.
1117  *
1118  * \note            This function works backwards in data buffer.
1119  *
1120  * \param p         The reference to the current position pointer.
1121  * \param start     The start of the buffer, for bounds-checking.
1122  * \param X         The MPI to write.
1123  *                  It must be non-negative.
1124  *
1125  * \return          The number of bytes written to \p p on success.
1126  * \return          A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
1127  */
1128 int mbedtls_asn1_write_mpi(unsigned char **p, const unsigned char *start,
1129                            const mbedtls_mpi *X);
1130 
1131 #ifdef __cplusplus
1132 }
1133 #endif
1134 
1135 #endif /* bignum.h */