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