blob: 20afa22d5d30cef7ff588fc34efd8814470aded6 [file] [log] [blame]
Jens Wiklander817466c2018-05-22 13:49:31 +02001/*
2 * Multi-precision integer library
3 *
Jerome Forissier3602df82021-07-28 10:24:04 +02004 * Copyright The Mbed TLS Contributors
5 * SPDX-License-Identifier: Apache-2.0
Jens Wiklander817466c2018-05-22 13:49:31 +02006 *
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may
8 * not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
Jens Wiklander817466c2018-05-22 13:49:31 +020018 */
19
20/*
21 * The following sources were referenced in the design of this Multi-precision
22 * Integer library:
23 *
24 * [1] Handbook of Applied Cryptography - 1997
25 * Menezes, van Oorschot and Vanstone
26 *
27 * [2] Multi-Precision Math
28 * Tom St Denis
29 * https://github.com/libtom/libtommath/blob/develop/tommath.pdf
30 *
31 * [3] GNU Multi-Precision Arithmetic Library
32 * https://gmplib.org/manual/index.html
33 *
34 */
35
Jerome Forissier3602df82021-07-28 10:24:04 +020036#include "common.h"
Jens Wiklander817466c2018-05-22 13:49:31 +020037
38#if defined(MBEDTLS_BIGNUM_C)
39
40#include "mbedtls/bignum.h"
41#include "mbedtls/bn_mul.h"
Jens Wiklander3d3b0592019-03-20 15:30:29 +010042#include "mbedtls/platform_util.h"
Jerome Forissier11fa71b2020-04-20 17:17:56 +020043#include "mbedtls/error.h"
Jens Wiklander817466c2018-05-22 13:49:31 +020044
45#include <string.h>
46
47#if defined(MBEDTLS_PLATFORM_C)
48#include "mbedtls/platform.h"
49#else
50#include <stdio.h>
51#include <stdlib.h>
52#define mbedtls_printf printf
53#define mbedtls_calloc calloc
54#define mbedtls_free free
55#endif
56
Jens Wiklander3d3b0592019-03-20 15:30:29 +010057#define MPI_VALIDATE_RET( cond ) \
58 MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_MPI_BAD_INPUT_DATA )
59#define MPI_VALIDATE( cond ) \
60 MBEDTLS_INTERNAL_VALIDATE( cond )
Jens Wiklander817466c2018-05-22 13:49:31 +020061
62#define ciL (sizeof(mbedtls_mpi_uint)) /* chars in limb */
63#define biL (ciL << 3) /* bits in limb */
64#define biH (ciL << 2) /* half limb size */
65
66#define MPI_SIZE_T_MAX ( (size_t) -1 ) /* SIZE_T_MAX is not standard */
67
68/*
69 * Convert between bits/chars and number of limbs
70 * Divide first in order to avoid potential overflows
71 */
72#define BITS_TO_LIMBS(i) ( (i) / biL + ( (i) % biL != 0 ) )
73#define CHARS_TO_LIMBS(i) ( (i) / ciL + ( (i) % ciL != 0 ) )
74
Jens Wiklander3d3b0592019-03-20 15:30:29 +010075/* Implementation that should never be optimized out by the compiler */
76static void mbedtls_mpi_zeroize( mbedtls_mpi_uint *v, size_t n )
77{
78 mbedtls_platform_zeroize( v, ciL * n );
79}
80
Jens Wiklander817466c2018-05-22 13:49:31 +020081/*
82 * Initialize one MPI
83 */
Jerome Forissier3602df82021-07-28 10:24:04 +020084void mbedtls_mpi_init( mbedtls_mpi *X )
Jens Wiklander817466c2018-05-22 13:49:31 +020085{
Jens Wiklander3d3b0592019-03-20 15:30:29 +010086 MPI_VALIDATE( X != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +020087
Jens Wiklander3d3b0592019-03-20 15:30:29 +010088 X->s = 1;
Jens Wiklander3d3b0592019-03-20 15:30:29 +010089 X->n = 0;
90 X->p = NULL;
Jens Wiklander817466c2018-05-22 13:49:31 +020091}
92
93/*
94 * Unallocate one MPI
95 */
96void mbedtls_mpi_free( mbedtls_mpi *X )
97{
98 if( X == NULL )
99 return;
100
101 if( X->p != NULL )
102 {
103 mbedtls_mpi_zeroize( X->p, X->n );
Jerome Forissier3602df82021-07-28 10:24:04 +0200104 mbedtls_free( X->p );
Jens Wiklander817466c2018-05-22 13:49:31 +0200105 }
106
107 X->s = 1;
108 X->n = 0;
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100109 X->p = NULL;
Jens Wiklander817466c2018-05-22 13:49:31 +0200110}
111
112/*
113 * Enlarge to the specified number of limbs
114 */
115int mbedtls_mpi_grow( mbedtls_mpi *X, size_t nblimbs )
116{
117 mbedtls_mpi_uint *p;
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100118 MPI_VALIDATE_RET( X != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +0200119
120 if( nblimbs > MBEDTLS_MPI_MAX_LIMBS )
121 return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
122
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100123 if( X->n < nblimbs )
124 {
Jerome Forissier3602df82021-07-28 10:24:04 +0200125 if( ( p = (mbedtls_mpi_uint*)mbedtls_calloc( nblimbs, ciL ) ) == NULL )
126 return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
Jens Wiklander817466c2018-05-22 13:49:31 +0200127
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100128 if( X->p != NULL )
129 {
130 memcpy( p, X->p, X->n * ciL );
131 mbedtls_mpi_zeroize( X->p, X->n );
Jerome Forissier3602df82021-07-28 10:24:04 +0200132 mbedtls_free( X->p );
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100133 }
134
135 X->n = nblimbs;
136 X->p = p;
Jens Wiklander817466c2018-05-22 13:49:31 +0200137 }
138
139 return( 0 );
140}
141
142/*
143 * Resize down as much as possible,
144 * while keeping at least the specified number of limbs
145 */
146int mbedtls_mpi_shrink( mbedtls_mpi *X, size_t nblimbs )
147{
148 mbedtls_mpi_uint *p;
149 size_t i;
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100150 MPI_VALIDATE_RET( X != NULL );
151
152 if( nblimbs > MBEDTLS_MPI_MAX_LIMBS )
153 return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
Jens Wiklander817466c2018-05-22 13:49:31 +0200154
Jerome Forissier5b25c762020-04-07 11:18:49 +0200155 /* Actually resize up if there are currently fewer than nblimbs limbs. */
Jens Wiklander817466c2018-05-22 13:49:31 +0200156 if( X->n <= nblimbs )
157 return( mbedtls_mpi_grow( X, nblimbs ) );
Jerome Forissier5b25c762020-04-07 11:18:49 +0200158 /* After this point, then X->n > nblimbs and in particular X->n > 0. */
Jens Wiklander817466c2018-05-22 13:49:31 +0200159
160 for( i = X->n - 1; i > 0; i-- )
161 if( X->p[i] != 0 )
162 break;
163 i++;
164
165 if( i < nblimbs )
166 i = nblimbs;
167
Jerome Forissier3602df82021-07-28 10:24:04 +0200168 if( ( p = (mbedtls_mpi_uint*)mbedtls_calloc( i, ciL ) ) == NULL )
169 return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
Jens Wiklander817466c2018-05-22 13:49:31 +0200170
171 if( X->p != NULL )
172 {
173 memcpy( p, X->p, i * ciL );
174 mbedtls_mpi_zeroize( X->p, X->n );
Jerome Forissier3602df82021-07-28 10:24:04 +0200175 mbedtls_free( X->p );
Jens Wiklander817466c2018-05-22 13:49:31 +0200176 }
177
Jens Wiklander18c51482018-11-12 13:53:08 +0100178 X->n = i;
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100179 X->p = p;
Jens Wiklander817466c2018-05-22 13:49:31 +0200180
181 return( 0 );
182}
183
Jerome Forissier3602df82021-07-28 10:24:04 +0200184/* Resize X to have exactly n limbs and set it to 0. */
185static int mbedtls_mpi_resize_clear( mbedtls_mpi *X, size_t limbs )
186{
187 if( limbs == 0 )
188 {
189 mbedtls_mpi_free( X );
190 return( 0 );
191 }
192 else if( X->n == limbs )
193 {
194 memset( X->p, 0, limbs * ciL );
195 X->s = 1;
196 return( 0 );
197 }
198 else
199 {
200 mbedtls_mpi_free( X );
201 return( mbedtls_mpi_grow( X, limbs ) );
202 }
203}
204
Jens Wiklander817466c2018-05-22 13:49:31 +0200205/*
Jerome Forissier3602df82021-07-28 10:24:04 +0200206 * Copy the contents of Y into X.
207 *
208 * This function is not constant-time. Leading zeros in Y may be removed.
209 *
210 * Ensure that X does not shrink. This is not guaranteed by the public API,
211 * but some code in the bignum module relies on this property, for example
212 * in mbedtls_mpi_exp_mod().
Jens Wiklander817466c2018-05-22 13:49:31 +0200213 */
214int mbedtls_mpi_copy( mbedtls_mpi *X, const mbedtls_mpi *Y )
215{
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100216 int ret = 0;
Jens Wiklander817466c2018-05-22 13:49:31 +0200217 size_t i;
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100218 MPI_VALIDATE_RET( X != NULL );
219 MPI_VALIDATE_RET( Y != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +0200220
221 if( X == Y )
222 return( 0 );
223
Jerome Forissier5b25c762020-04-07 11:18:49 +0200224 if( Y->n == 0 )
Jens Wiklander817466c2018-05-22 13:49:31 +0200225 {
Jerome Forissier3602df82021-07-28 10:24:04 +0200226 if( X->n != 0 )
227 {
228 X->s = 1;
229 memset( X->p, 0, X->n * ciL );
230 }
Jens Wiklander817466c2018-05-22 13:49:31 +0200231 return( 0 );
232 }
233
234 for( i = Y->n - 1; i > 0; i-- )
235 if( Y->p[i] != 0 )
236 break;
237 i++;
238
239 X->s = Y->s;
240
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100241 if( X->n < i )
242 {
243 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i ) );
244 }
245 else
246 {
247 memset( X->p + i, 0, ( X->n - i ) * ciL );
248 }
Jens Wiklander817466c2018-05-22 13:49:31 +0200249
Jens Wiklander817466c2018-05-22 13:49:31 +0200250 memcpy( X->p, Y->p, i * ciL );
251
252cleanup:
253
254 return( ret );
255}
256
257/*
258 * Swap the contents of X and Y
259 */
260void mbedtls_mpi_swap( mbedtls_mpi *X, mbedtls_mpi *Y )
261{
262 mbedtls_mpi T;
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100263 MPI_VALIDATE( X != NULL );
264 MPI_VALIDATE( Y != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +0200265
266 memcpy( &T, X, sizeof( mbedtls_mpi ) );
267 memcpy( X, Y, sizeof( mbedtls_mpi ) );
268 memcpy( Y, &T, sizeof( mbedtls_mpi ) );
269}
270
Jerome Forissier3602df82021-07-28 10:24:04 +0200271/**
272 * Select between two sign values in constant-time.
273 *
274 * This is functionally equivalent to second ? a : b but uses only bit
275 * operations in order to avoid branches.
276 *
277 * \param[in] a The first sign; must be either +1 or -1.
278 * \param[in] b The second sign; must be either +1 or -1.
279 * \param[in] second Must be either 1 (return b) or 0 (return a).
280 *
281 * \return The selected sign value.
282 */
283static int mpi_safe_cond_select_sign( int a, int b, unsigned char second )
284{
285 /* In order to avoid questions about what we can reasonnably assume about
286 * the representations of signed integers, move everything to unsigned
287 * by taking advantage of the fact that a and b are either +1 or -1. */
288 unsigned ua = a + 1;
289 unsigned ub = b + 1;
290
291 /* second was 0 or 1, mask is 0 or 2 as are ua and ub */
292 const unsigned mask = second << 1;
293
294 /* select ua or ub */
295 unsigned ur = ( ua & ~mask ) | ( ub & mask );
296
297 /* ur is now 0 or 2, convert back to -1 or +1 */
298 return( (int) ur - 1 );
299}
300
301/*
302 * Conditionally assign dest = src, without leaking information
303 * about whether the assignment was made or not.
304 * dest and src must be arrays of limbs of size n.
305 * assign must be 0 or 1.
306 */
307static void mpi_safe_cond_assign( size_t n,
308 mbedtls_mpi_uint *dest,
309 const mbedtls_mpi_uint *src,
310 unsigned char assign )
311{
312 size_t i;
313
314 /* MSVC has a warning about unary minus on unsigned integer types,
315 * but this is well-defined and precisely what we want to do here. */
316#if defined(_MSC_VER)
317#pragma warning( push )
318#pragma warning( disable : 4146 )
319#endif
320
321 /* all-bits 1 if assign is 1, all-bits 0 if assign is 0 */
322 const mbedtls_mpi_uint mask = -assign;
323
324#if defined(_MSC_VER)
325#pragma warning( pop )
326#endif
327
328 for( i = 0; i < n; i++ )
329 dest[i] = ( src[i] & mask ) | ( dest[i] & ~mask );
330}
331
Jens Wiklander817466c2018-05-22 13:49:31 +0200332/*
333 * Conditionally assign X = Y, without leaking information
334 * about whether the assignment was made or not.
335 * (Leaking information about the respective sizes of X and Y is ok however.)
336 */
337int mbedtls_mpi_safe_cond_assign( mbedtls_mpi *X, const mbedtls_mpi *Y, unsigned char assign )
338{
339 int ret = 0;
340 size_t i;
Jerome Forissier3602df82021-07-28 10:24:04 +0200341 mbedtls_mpi_uint limb_mask;
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100342 MPI_VALIDATE_RET( X != NULL );
343 MPI_VALIDATE_RET( Y != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +0200344
Jerome Forissier3602df82021-07-28 10:24:04 +0200345 /* MSVC has a warning about unary minus on unsigned integer types,
346 * but this is well-defined and precisely what we want to do here. */
347#if defined(_MSC_VER)
348#pragma warning( push )
349#pragma warning( disable : 4146 )
350#endif
351
Jens Wiklander817466c2018-05-22 13:49:31 +0200352 /* make sure assign is 0 or 1 in a time-constant manner */
Jerome Forissier3602df82021-07-28 10:24:04 +0200353 assign = (assign | (unsigned char)-assign) >> (sizeof( assign ) * 8 - 1);
354 /* all-bits 1 if assign is 1, all-bits 0 if assign is 0 */
355 limb_mask = -assign;
356
357#if defined(_MSC_VER)
358#pragma warning( pop )
359#endif
Jens Wiklander817466c2018-05-22 13:49:31 +0200360
361 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
362
Jerome Forissier3602df82021-07-28 10:24:04 +0200363 X->s = mpi_safe_cond_select_sign( X->s, Y->s, assign );
Jens Wiklander817466c2018-05-22 13:49:31 +0200364
Jerome Forissier3602df82021-07-28 10:24:04 +0200365 mpi_safe_cond_assign( Y->n, X->p, Y->p, assign );
Jens Wiklander817466c2018-05-22 13:49:31 +0200366
Jerome Forissier3602df82021-07-28 10:24:04 +0200367 for( i = Y->n; i < X->n; i++ )
368 X->p[i] &= ~limb_mask;
Jens Wiklander817466c2018-05-22 13:49:31 +0200369
370cleanup:
371 return( ret );
372}
373
374/*
375 * Conditionally swap X and Y, without leaking information
376 * about whether the swap was made or not.
377 * Here it is not ok to simply swap the pointers, which whould lead to
378 * different memory access patterns when X and Y are used afterwards.
379 */
380int mbedtls_mpi_safe_cond_swap( mbedtls_mpi *X, mbedtls_mpi *Y, unsigned char swap )
381{
382 int ret, s;
383 size_t i;
Jerome Forissier3602df82021-07-28 10:24:04 +0200384 mbedtls_mpi_uint limb_mask;
Jens Wiklander817466c2018-05-22 13:49:31 +0200385 mbedtls_mpi_uint tmp;
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100386 MPI_VALIDATE_RET( X != NULL );
387 MPI_VALIDATE_RET( Y != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +0200388
389 if( X == Y )
390 return( 0 );
391
Jerome Forissier3602df82021-07-28 10:24:04 +0200392 /* MSVC has a warning about unary minus on unsigned integer types,
393 * but this is well-defined and precisely what we want to do here. */
394#if defined(_MSC_VER)
395#pragma warning( push )
396#pragma warning( disable : 4146 )
397#endif
398
Jens Wiklander817466c2018-05-22 13:49:31 +0200399 /* make sure swap is 0 or 1 in a time-constant manner */
Jerome Forissier3602df82021-07-28 10:24:04 +0200400 swap = (swap | (unsigned char)-swap) >> (sizeof( swap ) * 8 - 1);
401 /* all-bits 1 if swap is 1, all-bits 0 if swap is 0 */
402 limb_mask = -swap;
403
404#if defined(_MSC_VER)
405#pragma warning( pop )
406#endif
Jens Wiklander817466c2018-05-22 13:49:31 +0200407
408 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
409 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( Y, X->n ) );
410
411 s = X->s;
Jerome Forissier3602df82021-07-28 10:24:04 +0200412 X->s = mpi_safe_cond_select_sign( X->s, Y->s, swap );
413 Y->s = mpi_safe_cond_select_sign( Y->s, s, swap );
Jens Wiklander817466c2018-05-22 13:49:31 +0200414
415
416 for( i = 0; i < X->n; i++ )
417 {
418 tmp = X->p[i];
Jerome Forissier3602df82021-07-28 10:24:04 +0200419 X->p[i] = ( X->p[i] & ~limb_mask ) | ( Y->p[i] & limb_mask );
420 Y->p[i] = ( Y->p[i] & ~limb_mask ) | ( tmp & limb_mask );
Jens Wiklander817466c2018-05-22 13:49:31 +0200421 }
422
423cleanup:
424 return( ret );
425}
426
427/*
428 * Set value from integer
429 */
430int mbedtls_mpi_lset( mbedtls_mpi *X, mbedtls_mpi_sint z )
431{
Jerome Forissier11fa71b2020-04-20 17:17:56 +0200432 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100433 MPI_VALIDATE_RET( X != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +0200434
435 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, 1 ) );
436 memset( X->p, 0, X->n * ciL );
437
438 X->p[0] = ( z < 0 ) ? -z : z;
439 X->s = ( z < 0 ) ? -1 : 1;
440
441cleanup:
442
443 return( ret );
444}
445
446/*
447 * Get a specific bit
448 */
449int mbedtls_mpi_get_bit( const mbedtls_mpi *X, size_t pos )
450{
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100451 MPI_VALIDATE_RET( X != NULL );
452
Jens Wiklander817466c2018-05-22 13:49:31 +0200453 if( X->n * biL <= pos )
454 return( 0 );
455
456 return( ( X->p[pos / biL] >> ( pos % biL ) ) & 0x01 );
457}
458
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100459/* Get a specific byte, without range checks. */
460#define GET_BYTE( X, i ) \
461 ( ( ( X )->p[( i ) / ciL] >> ( ( ( i ) % ciL ) * 8 ) ) & 0xff )
462
Jens Wiklander817466c2018-05-22 13:49:31 +0200463/*
464 * Set a bit to a specific value of 0 or 1
465 */
466int mbedtls_mpi_set_bit( mbedtls_mpi *X, size_t pos, unsigned char val )
467{
468 int ret = 0;
469 size_t off = pos / biL;
470 size_t idx = pos % biL;
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100471 MPI_VALIDATE_RET( X != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +0200472
473 if( val != 0 && val != 1 )
474 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
475
476 if( X->n * biL <= pos )
477 {
478 if( val == 0 )
479 return( 0 );
480
481 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, off + 1 ) );
482 }
483
484 X->p[off] &= ~( (mbedtls_mpi_uint) 0x01 << idx );
485 X->p[off] |= (mbedtls_mpi_uint) val << idx;
486
487cleanup:
488
489 return( ret );
490}
491
492/*
493 * Return the number of less significant zero-bits
494 */
495size_t mbedtls_mpi_lsb( const mbedtls_mpi *X )
496{
497 size_t i, j, count = 0;
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100498 MBEDTLS_INTERNAL_VALIDATE_RET( X != NULL, 0 );
Jens Wiklander817466c2018-05-22 13:49:31 +0200499
500 for( i = 0; i < X->n; i++ )
501 for( j = 0; j < biL; j++, count++ )
502 if( ( ( X->p[i] >> j ) & 1 ) != 0 )
503 return( count );
504
505 return( 0 );
506}
507
508/*
509 * Count leading zero bits in a given integer
510 */
511static size_t mbedtls_clz( const mbedtls_mpi_uint x )
512{
513 size_t j;
514 mbedtls_mpi_uint mask = (mbedtls_mpi_uint) 1 << (biL - 1);
515
516 for( j = 0; j < biL; j++ )
517 {
518 if( x & mask ) break;
519
520 mask >>= 1;
521 }
522
523 return j;
524}
525
526/*
527 * Return the number of bits
528 */
529size_t mbedtls_mpi_bitlen( const mbedtls_mpi *X )
530{
531 size_t i, j;
532
533 if( X->n == 0 )
534 return( 0 );
535
536 for( i = X->n - 1; i > 0; i-- )
537 if( X->p[i] != 0 )
538 break;
539
540 j = biL - mbedtls_clz( X->p[i] );
541
542 return( ( i * biL ) + j );
543}
544
545/*
546 * Return the total size in bytes
547 */
548size_t mbedtls_mpi_size( const mbedtls_mpi *X )
549{
550 return( ( mbedtls_mpi_bitlen( X ) + 7 ) >> 3 );
551}
552
553/*
554 * Convert an ASCII character to digit value
555 */
556static int mpi_get_digit( mbedtls_mpi_uint *d, int radix, char c )
557{
558 *d = 255;
559
560 if( c >= 0x30 && c <= 0x39 ) *d = c - 0x30;
561 if( c >= 0x41 && c <= 0x46 ) *d = c - 0x37;
562 if( c >= 0x61 && c <= 0x66 ) *d = c - 0x57;
563
564 if( *d >= (mbedtls_mpi_uint) radix )
565 return( MBEDTLS_ERR_MPI_INVALID_CHARACTER );
566
567 return( 0 );
568}
569
570/*
571 * Import from an ASCII string
572 */
573int mbedtls_mpi_read_string( mbedtls_mpi *X, int radix, const char *s )
574{
Jerome Forissier11fa71b2020-04-20 17:17:56 +0200575 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +0200576 size_t i, j, slen, n;
Jerome Forissier3602df82021-07-28 10:24:04 +0200577 int sign = 1;
Jens Wiklander817466c2018-05-22 13:49:31 +0200578 mbedtls_mpi_uint d;
579 mbedtls_mpi T;
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100580 MPI_VALIDATE_RET( X != NULL );
581 MPI_VALIDATE_RET( s != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +0200582
583 if( radix < 2 || radix > 16 )
584 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
585
Jerome Forissier3602df82021-07-28 10:24:04 +0200586 mbedtls_mpi_init( &T );
587
588 if( s[0] == 0 )
589 {
590 mbedtls_mpi_free( X );
591 return( 0 );
592 }
593
594 if( s[0] == '-' )
595 {
596 ++s;
597 sign = -1;
598 }
Jens Wiklander817466c2018-05-22 13:49:31 +0200599
600 slen = strlen( s );
601
602 if( radix == 16 )
603 {
604 if( slen > MPI_SIZE_T_MAX >> 2 )
605 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
606
607 n = BITS_TO_LIMBS( slen << 2 );
608
609 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, n ) );
610 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );
611
612 for( i = slen, j = 0; i > 0; i--, j++ )
613 {
Jens Wiklander817466c2018-05-22 13:49:31 +0200614 MBEDTLS_MPI_CHK( mpi_get_digit( &d, radix, s[i - 1] ) );
615 X->p[j / ( 2 * ciL )] |= d << ( ( j % ( 2 * ciL ) ) << 2 );
616 }
617 }
618 else
619 {
620 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );
621
622 for( i = 0; i < slen; i++ )
623 {
Jens Wiklander817466c2018-05-22 13:49:31 +0200624 MBEDTLS_MPI_CHK( mpi_get_digit( &d, radix, s[i] ) );
625 MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &T, X, radix ) );
Jerome Forissier3602df82021-07-28 10:24:04 +0200626 MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, &T, d ) );
Jens Wiklander817466c2018-05-22 13:49:31 +0200627 }
628 }
629
Jerome Forissier3602df82021-07-28 10:24:04 +0200630 if( sign < 0 && mbedtls_mpi_bitlen( X ) != 0 )
631 X->s = -1;
632
Jens Wiklander817466c2018-05-22 13:49:31 +0200633cleanup:
634
635 mbedtls_mpi_free( &T );
636
637 return( ret );
638}
639
640/*
Jerome Forissier5b25c762020-04-07 11:18:49 +0200641 * Helper to write the digits high-order first.
Jens Wiklander817466c2018-05-22 13:49:31 +0200642 */
Jerome Forissier5b25c762020-04-07 11:18:49 +0200643static int mpi_write_hlp( mbedtls_mpi *X, int radix,
644 char **p, const size_t buflen )
Jens Wiklander817466c2018-05-22 13:49:31 +0200645{
Jerome Forissier11fa71b2020-04-20 17:17:56 +0200646 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +0200647 mbedtls_mpi_uint r;
Jerome Forissier5b25c762020-04-07 11:18:49 +0200648 size_t length = 0;
649 char *p_end = *p + buflen;
Jens Wiklander817466c2018-05-22 13:49:31 +0200650
Jerome Forissier5b25c762020-04-07 11:18:49 +0200651 do
652 {
653 if( length >= buflen )
654 {
655 return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
656 }
Jens Wiklander817466c2018-05-22 13:49:31 +0200657
Jerome Forissier5b25c762020-04-07 11:18:49 +0200658 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, radix ) );
659 MBEDTLS_MPI_CHK( mbedtls_mpi_div_int( X, NULL, X, radix ) );
660 /*
661 * Write the residue in the current position, as an ASCII character.
662 */
663 if( r < 0xA )
664 *(--p_end) = (char)( '0' + r );
665 else
666 *(--p_end) = (char)( 'A' + ( r - 0xA ) );
Jens Wiklander817466c2018-05-22 13:49:31 +0200667
Jerome Forissier5b25c762020-04-07 11:18:49 +0200668 length++;
669 } while( mbedtls_mpi_cmp_int( X, 0 ) != 0 );
Jens Wiklander817466c2018-05-22 13:49:31 +0200670
Jerome Forissier5b25c762020-04-07 11:18:49 +0200671 memmove( *p, p_end, length );
672 *p += length;
Jens Wiklander817466c2018-05-22 13:49:31 +0200673
674cleanup:
675
676 return( ret );
677}
678
679/*
680 * Export into an ASCII string
681 */
682int mbedtls_mpi_write_string( const mbedtls_mpi *X, int radix,
683 char *buf, size_t buflen, size_t *olen )
684{
685 int ret = 0;
686 size_t n;
687 char *p;
688 mbedtls_mpi T;
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100689 MPI_VALIDATE_RET( X != NULL );
690 MPI_VALIDATE_RET( olen != NULL );
691 MPI_VALIDATE_RET( buflen == 0 || buf != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +0200692
693 if( radix < 2 || radix > 16 )
694 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
695
Jerome Forissier5b25c762020-04-07 11:18:49 +0200696 n = mbedtls_mpi_bitlen( X ); /* Number of bits necessary to present `n`. */
697 if( radix >= 4 ) n >>= 1; /* Number of 4-adic digits necessary to present
698 * `n`. If radix > 4, this might be a strict
699 * overapproximation of the number of
700 * radix-adic digits needed to present `n`. */
701 if( radix >= 16 ) n >>= 1; /* Number of hexadecimal digits necessary to
702 * present `n`. */
703
704 n += 1; /* Terminating null byte */
705 n += 1; /* Compensate for the divisions above, which round down `n`
706 * in case it's not even. */
707 n += 1; /* Potential '-'-sign. */
708 n += ( n & 1 ); /* Make n even to have enough space for hexadecimal writing,
709 * which always uses an even number of hex-digits. */
Jens Wiklander817466c2018-05-22 13:49:31 +0200710
711 if( buflen < n )
712 {
713 *olen = n;
714 return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
715 }
716
717 p = buf;
Jerome Forissier3602df82021-07-28 10:24:04 +0200718 mbedtls_mpi_init( &T );
Jens Wiklander817466c2018-05-22 13:49:31 +0200719
720 if( X->s == -1 )
Jerome Forissier5b25c762020-04-07 11:18:49 +0200721 {
Jens Wiklander817466c2018-05-22 13:49:31 +0200722 *p++ = '-';
Jerome Forissier5b25c762020-04-07 11:18:49 +0200723 buflen--;
724 }
Jens Wiklander817466c2018-05-22 13:49:31 +0200725
726 if( radix == 16 )
727 {
728 int c;
729 size_t i, j, k;
730
731 for( i = X->n, k = 0; i > 0; i-- )
732 {
733 for( j = ciL; j > 0; j-- )
734 {
735 c = ( X->p[i - 1] >> ( ( j - 1 ) << 3) ) & 0xFF;
736
737 if( c == 0 && k == 0 && ( i + j ) != 2 )
738 continue;
739
740 *(p++) = "0123456789ABCDEF" [c / 16];
741 *(p++) = "0123456789ABCDEF" [c % 16];
742 k = 1;
743 }
744 }
745 }
746 else
747 {
748 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &T, X ) );
749
750 if( T.s == -1 )
751 T.s = 1;
752
Jerome Forissier5b25c762020-04-07 11:18:49 +0200753 MBEDTLS_MPI_CHK( mpi_write_hlp( &T, radix, &p, buflen ) );
Jens Wiklander817466c2018-05-22 13:49:31 +0200754 }
755
756 *p++ = '\0';
757 *olen = p - buf;
758
759cleanup:
760
761 mbedtls_mpi_free( &T );
762
763 return( ret );
764}
765
766#if defined(MBEDTLS_FS_IO)
767/*
768 * Read X from an opened file
769 */
770int mbedtls_mpi_read_file( mbedtls_mpi *X, int radix, FILE *fin )
771{
772 mbedtls_mpi_uint d;
773 size_t slen;
774 char *p;
775 /*
776 * Buffer should have space for (short) label and decimal formatted MPI,
777 * newline characters and '\0'
778 */
779 char s[ MBEDTLS_MPI_RW_BUFFER_SIZE ];
780
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100781 MPI_VALIDATE_RET( X != NULL );
782 MPI_VALIDATE_RET( fin != NULL );
783
784 if( radix < 2 || radix > 16 )
785 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
786
Jens Wiklander817466c2018-05-22 13:49:31 +0200787 memset( s, 0, sizeof( s ) );
788 if( fgets( s, sizeof( s ) - 1, fin ) == NULL )
789 return( MBEDTLS_ERR_MPI_FILE_IO_ERROR );
790
791 slen = strlen( s );
792 if( slen == sizeof( s ) - 2 )
793 return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
794
795 if( slen > 0 && s[slen - 1] == '\n' ) { slen--; s[slen] = '\0'; }
796 if( slen > 0 && s[slen - 1] == '\r' ) { slen--; s[slen] = '\0'; }
797
798 p = s + slen;
799 while( p-- > s )
800 if( mpi_get_digit( &d, radix, *p ) != 0 )
801 break;
802
803 return( mbedtls_mpi_read_string( X, radix, p + 1 ) );
804}
805
806/*
807 * Write X into an opened file (or stdout if fout == NULL)
808 */
809int mbedtls_mpi_write_file( const char *p, const mbedtls_mpi *X, int radix, FILE *fout )
810{
Jerome Forissier11fa71b2020-04-20 17:17:56 +0200811 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +0200812 size_t n, slen, plen;
813 /*
814 * Buffer should have space for (short) label and decimal formatted MPI,
815 * newline characters and '\0'
816 */
817 char s[ MBEDTLS_MPI_RW_BUFFER_SIZE ];
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100818 MPI_VALIDATE_RET( X != NULL );
819
820 if( radix < 2 || radix > 16 )
821 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
Jens Wiklander817466c2018-05-22 13:49:31 +0200822
823 memset( s, 0, sizeof( s ) );
824
825 MBEDTLS_MPI_CHK( mbedtls_mpi_write_string( X, radix, s, sizeof( s ) - 2, &n ) );
826
827 if( p == NULL ) p = "";
828
829 plen = strlen( p );
830 slen = strlen( s );
831 s[slen++] = '\r';
832 s[slen++] = '\n';
833
834 if( fout != NULL )
835 {
836 if( fwrite( p, 1, plen, fout ) != plen ||
837 fwrite( s, 1, slen, fout ) != slen )
838 return( MBEDTLS_ERR_MPI_FILE_IO_ERROR );
839 }
840 else
841 mbedtls_printf( "%s%s", p, s );
842
843cleanup:
844
845 return( ret );
846}
847#endif /* MBEDTLS_FS_IO */
848
Jerome Forissier5b25c762020-04-07 11:18:49 +0200849
850/* Convert a big-endian byte array aligned to the size of mbedtls_mpi_uint
851 * into the storage form used by mbedtls_mpi. */
852
853static mbedtls_mpi_uint mpi_uint_bigendian_to_host_c( mbedtls_mpi_uint x )
854{
855 uint8_t i;
856 unsigned char *x_ptr;
857 mbedtls_mpi_uint tmp = 0;
858
859 for( i = 0, x_ptr = (unsigned char*) &x; i < ciL; i++, x_ptr++ )
860 {
861 tmp <<= CHAR_BIT;
862 tmp |= (mbedtls_mpi_uint) *x_ptr;
863 }
864
865 return( tmp );
866}
867
868static mbedtls_mpi_uint mpi_uint_bigendian_to_host( mbedtls_mpi_uint x )
869{
870#if defined(__BYTE_ORDER__)
871
872/* Nothing to do on bigendian systems. */
873#if ( __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ )
874 return( x );
875#endif /* __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ */
876
877#if ( __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ )
878
879/* For GCC and Clang, have builtins for byte swapping. */
880#if defined(__GNUC__) && defined(__GNUC_PREREQ)
881#if __GNUC_PREREQ(4,3)
882#define have_bswap
883#endif
884#endif
885
886#if defined(__clang__) && defined(__has_builtin)
887#if __has_builtin(__builtin_bswap32) && \
888 __has_builtin(__builtin_bswap64)
889#define have_bswap
890#endif
891#endif
892
893#if defined(have_bswap)
894 /* The compiler is hopefully able to statically evaluate this! */
895 switch( sizeof(mbedtls_mpi_uint) )
896 {
897 case 4:
898 return( __builtin_bswap32(x) );
899 case 8:
900 return( __builtin_bswap64(x) );
901 }
902#endif
903#endif /* __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ */
904#endif /* __BYTE_ORDER__ */
905
906 /* Fall back to C-based reordering if we don't know the byte order
907 * or we couldn't use a compiler-specific builtin. */
908 return( mpi_uint_bigendian_to_host_c( x ) );
909}
910
911static void mpi_bigendian_to_host( mbedtls_mpi_uint * const p, size_t limbs )
912{
913 mbedtls_mpi_uint *cur_limb_left;
914 mbedtls_mpi_uint *cur_limb_right;
915 if( limbs == 0 )
916 return;
917
918 /*
919 * Traverse limbs and
920 * - adapt byte-order in each limb
921 * - swap the limbs themselves.
922 * For that, simultaneously traverse the limbs from left to right
923 * and from right to left, as long as the left index is not bigger
924 * than the right index (it's not a problem if limbs is odd and the
925 * indices coincide in the last iteration).
926 */
927 for( cur_limb_left = p, cur_limb_right = p + ( limbs - 1 );
928 cur_limb_left <= cur_limb_right;
929 cur_limb_left++, cur_limb_right-- )
930 {
931 mbedtls_mpi_uint tmp;
932 /* Note that if cur_limb_left == cur_limb_right,
933 * this code effectively swaps the bytes only once. */
934 tmp = mpi_uint_bigendian_to_host( *cur_limb_left );
935 *cur_limb_left = mpi_uint_bigendian_to_host( *cur_limb_right );
936 *cur_limb_right = tmp;
937 }
938}
939
Jens Wiklander817466c2018-05-22 13:49:31 +0200940/*
Jerome Forissier11fa71b2020-04-20 17:17:56 +0200941 * Import X from unsigned binary data, little endian
942 */
943int mbedtls_mpi_read_binary_le( mbedtls_mpi *X,
944 const unsigned char *buf, size_t buflen )
945{
946 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
947 size_t i;
948 size_t const limbs = CHARS_TO_LIMBS( buflen );
949
950 /* Ensure that target MPI has exactly the necessary number of limbs */
Jerome Forissier3602df82021-07-28 10:24:04 +0200951 MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, limbs ) );
Jerome Forissier11fa71b2020-04-20 17:17:56 +0200952
953 for( i = 0; i < buflen; i++ )
954 X->p[i / ciL] |= ((mbedtls_mpi_uint) buf[i]) << ((i % ciL) << 3);
955
956cleanup:
957
958 /*
959 * This function is also used to import keys. However, wiping the buffers
960 * upon failure is not necessary because failure only can happen before any
961 * input is copied.
962 */
963 return( ret );
964}
965
966/*
Jens Wiklander817466c2018-05-22 13:49:31 +0200967 * Import X from unsigned binary data, big endian
968 */
969int mbedtls_mpi_read_binary( mbedtls_mpi *X, const unsigned char *buf, size_t buflen )
970{
Jerome Forissier11fa71b2020-04-20 17:17:56 +0200971 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jerome Forissier5b25c762020-04-07 11:18:49 +0200972 size_t const limbs = CHARS_TO_LIMBS( buflen );
973 size_t const overhead = ( limbs * ciL ) - buflen;
974 unsigned char *Xp;
Jens Wiklander817466c2018-05-22 13:49:31 +0200975
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100976 MPI_VALIDATE_RET( X != NULL );
977 MPI_VALIDATE_RET( buflen == 0 || buf != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +0200978
Jens Wiklander3d3b0592019-03-20 15:30:29 +0100979 /* Ensure that target MPI has exactly the necessary number of limbs */
Jerome Forissier3602df82021-07-28 10:24:04 +0200980 MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, limbs ) );
Jens Wiklander29762732019-04-17 12:28:43 +0200981
Jerome Forissier3602df82021-07-28 10:24:04 +0200982 /* Avoid calling `memcpy` with NULL source or destination argument,
Jerome Forissier5b25c762020-04-07 11:18:49 +0200983 * even if buflen is 0. */
Jerome Forissier3602df82021-07-28 10:24:04 +0200984 if( buflen != 0 )
Jerome Forissier5b25c762020-04-07 11:18:49 +0200985 {
986 Xp = (unsigned char*) X->p;
987 memcpy( Xp + overhead, buf, buflen );
988
989 mpi_bigendian_to_host( X->p, limbs );
990 }
Jens Wiklander817466c2018-05-22 13:49:31 +0200991
992cleanup:
993
Jerome Forissier11fa71b2020-04-20 17:17:56 +0200994 /*
995 * This function is also used to import keys. However, wiping the buffers
996 * upon failure is not necessary because failure only can happen before any
997 * input is copied.
998 */
Jens Wiklander817466c2018-05-22 13:49:31 +0200999 return( ret );
1000}
1001
1002/*
Jerome Forissier11fa71b2020-04-20 17:17:56 +02001003 * Export X into unsigned binary data, little endian
1004 */
1005int mbedtls_mpi_write_binary_le( const mbedtls_mpi *X,
1006 unsigned char *buf, size_t buflen )
1007{
1008 size_t stored_bytes = X->n * ciL;
1009 size_t bytes_to_copy;
1010 size_t i;
1011
1012 if( stored_bytes < buflen )
1013 {
1014 bytes_to_copy = stored_bytes;
1015 }
1016 else
1017 {
1018 bytes_to_copy = buflen;
1019
1020 /* The output buffer is smaller than the allocated size of X.
1021 * However X may fit if its leading bytes are zero. */
1022 for( i = bytes_to_copy; i < stored_bytes; i++ )
1023 {
1024 if( GET_BYTE( X, i ) != 0 )
1025 return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
1026 }
1027 }
1028
1029 for( i = 0; i < bytes_to_copy; i++ )
1030 buf[i] = GET_BYTE( X, i );
1031
1032 if( stored_bytes < buflen )
1033 {
1034 /* Write trailing 0 bytes */
1035 memset( buf + stored_bytes, 0, buflen - stored_bytes );
1036 }
1037
1038 return( 0 );
1039}
1040
1041/*
Jens Wiklander817466c2018-05-22 13:49:31 +02001042 * Export X into unsigned binary data, big endian
1043 */
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001044int mbedtls_mpi_write_binary( const mbedtls_mpi *X,
1045 unsigned char *buf, size_t buflen )
Jens Wiklander817466c2018-05-22 13:49:31 +02001046{
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001047 size_t stored_bytes;
1048 size_t bytes_to_copy;
1049 unsigned char *p;
1050 size_t i;
Jens Wiklander817466c2018-05-22 13:49:31 +02001051
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001052 MPI_VALIDATE_RET( X != NULL );
1053 MPI_VALIDATE_RET( buflen == 0 || buf != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02001054
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001055 stored_bytes = X->n * ciL;
Jens Wiklander817466c2018-05-22 13:49:31 +02001056
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001057 if( stored_bytes < buflen )
1058 {
1059 /* There is enough space in the output buffer. Write initial
1060 * null bytes and record the position at which to start
1061 * writing the significant bytes. In this case, the execution
1062 * trace of this function does not depend on the value of the
1063 * number. */
1064 bytes_to_copy = stored_bytes;
1065 p = buf + buflen - stored_bytes;
1066 memset( buf, 0, buflen - stored_bytes );
1067 }
1068 else
1069 {
1070 /* The output buffer is smaller than the allocated size of X.
1071 * However X may fit if its leading bytes are zero. */
1072 bytes_to_copy = buflen;
1073 p = buf;
1074 for( i = bytes_to_copy; i < stored_bytes; i++ )
1075 {
1076 if( GET_BYTE( X, i ) != 0 )
1077 return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
1078 }
1079 }
Jens Wiklander817466c2018-05-22 13:49:31 +02001080
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001081 for( i = 0; i < bytes_to_copy; i++ )
1082 p[bytes_to_copy - i - 1] = GET_BYTE( X, i );
Jens Wiklander817466c2018-05-22 13:49:31 +02001083
1084 return( 0 );
1085}
1086
1087/*
1088 * Left-shift: X <<= count
1089 */
1090int mbedtls_mpi_shift_l( mbedtls_mpi *X, size_t count )
1091{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02001092 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +02001093 size_t i, v0, t1;
1094 mbedtls_mpi_uint r0 = 0, r1;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001095 MPI_VALIDATE_RET( X != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02001096
1097 v0 = count / (biL );
1098 t1 = count & (biL - 1);
1099
1100 i = mbedtls_mpi_bitlen( X ) + count;
1101
1102 if( X->n * biL < i )
1103 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, BITS_TO_LIMBS( i ) ) );
1104
1105 ret = 0;
1106
1107 /*
1108 * shift by count / limb_size
1109 */
1110 if( v0 > 0 )
1111 {
1112 for( i = X->n; i > v0; i-- )
1113 X->p[i - 1] = X->p[i - v0 - 1];
1114
1115 for( ; i > 0; i-- )
1116 X->p[i - 1] = 0;
1117 }
1118
1119 /*
1120 * shift by count % limb_size
1121 */
1122 if( t1 > 0 )
1123 {
1124 for( i = v0; i < X->n; i++ )
1125 {
1126 r1 = X->p[i] >> (biL - t1);
1127 X->p[i] <<= t1;
1128 X->p[i] |= r0;
1129 r0 = r1;
1130 }
1131 }
1132
1133cleanup:
1134
1135 return( ret );
1136}
1137
1138/*
1139 * Right-shift: X >>= count
1140 */
1141int mbedtls_mpi_shift_r( mbedtls_mpi *X, size_t count )
1142{
1143 size_t i, v0, v1;
1144 mbedtls_mpi_uint r0 = 0, r1;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001145 MPI_VALIDATE_RET( X != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02001146
1147 v0 = count / biL;
1148 v1 = count & (biL - 1);
1149
1150 if( v0 > X->n || ( v0 == X->n && v1 > 0 ) )
1151 return mbedtls_mpi_lset( X, 0 );
1152
1153 /*
1154 * shift by count / limb_size
1155 */
1156 if( v0 > 0 )
1157 {
1158 for( i = 0; i < X->n - v0; i++ )
1159 X->p[i] = X->p[i + v0];
1160
1161 for( ; i < X->n; i++ )
1162 X->p[i] = 0;
1163 }
1164
1165 /*
1166 * shift by count % limb_size
1167 */
1168 if( v1 > 0 )
1169 {
1170 for( i = X->n; i > 0; i-- )
1171 {
1172 r1 = X->p[i - 1] << (biL - v1);
1173 X->p[i - 1] >>= v1;
1174 X->p[i - 1] |= r0;
1175 r0 = r1;
1176 }
1177 }
1178
1179 return( 0 );
1180}
1181
1182/*
1183 * Compare unsigned values
1184 */
1185int mbedtls_mpi_cmp_abs( const mbedtls_mpi *X, const mbedtls_mpi *Y )
1186{
1187 size_t i, j;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001188 MPI_VALIDATE_RET( X != NULL );
1189 MPI_VALIDATE_RET( Y != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02001190
1191 for( i = X->n; i > 0; i-- )
1192 if( X->p[i - 1] != 0 )
1193 break;
1194
1195 for( j = Y->n; j > 0; j-- )
1196 if( Y->p[j - 1] != 0 )
1197 break;
1198
1199 if( i == 0 && j == 0 )
1200 return( 0 );
1201
1202 if( i > j ) return( 1 );
1203 if( j > i ) return( -1 );
1204
1205 for( ; i > 0; i-- )
1206 {
1207 if( X->p[i - 1] > Y->p[i - 1] ) return( 1 );
1208 if( X->p[i - 1] < Y->p[i - 1] ) return( -1 );
1209 }
1210
1211 return( 0 );
1212}
1213
1214/*
1215 * Compare signed values
1216 */
1217int mbedtls_mpi_cmp_mpi( const mbedtls_mpi *X, const mbedtls_mpi *Y )
1218{
1219 size_t i, j;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001220 MPI_VALIDATE_RET( X != NULL );
1221 MPI_VALIDATE_RET( Y != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02001222
1223 for( i = X->n; i > 0; i-- )
1224 if( X->p[i - 1] != 0 )
1225 break;
1226
1227 for( j = Y->n; j > 0; j-- )
1228 if( Y->p[j - 1] != 0 )
1229 break;
1230
1231 if( i == 0 && j == 0 )
1232 return( 0 );
1233
1234 if( i > j ) return( X->s );
1235 if( j > i ) return( -Y->s );
1236
1237 if( X->s > 0 && Y->s < 0 ) return( 1 );
1238 if( Y->s > 0 && X->s < 0 ) return( -1 );
1239
1240 for( ; i > 0; i-- )
1241 {
1242 if( X->p[i - 1] > Y->p[i - 1] ) return( X->s );
1243 if( X->p[i - 1] < Y->p[i - 1] ) return( -X->s );
1244 }
1245
1246 return( 0 );
1247}
1248
Jerome Forissier5b25c762020-04-07 11:18:49 +02001249/** Decide if an integer is less than the other, without branches.
1250 *
1251 * \param x First integer.
1252 * \param y Second integer.
1253 *
1254 * \return 1 if \p x is less than \p y, 0 otherwise
1255 */
1256static unsigned ct_lt_mpi_uint( const mbedtls_mpi_uint x,
1257 const mbedtls_mpi_uint y )
1258{
1259 mbedtls_mpi_uint ret;
1260 mbedtls_mpi_uint cond;
1261
1262 /*
1263 * Check if the most significant bits (MSB) of the operands are different.
1264 */
1265 cond = ( x ^ y );
1266 /*
1267 * If the MSB are the same then the difference x-y will be negative (and
1268 * have its MSB set to 1 during conversion to unsigned) if and only if x<y.
1269 */
1270 ret = ( x - y ) & ~cond;
1271 /*
1272 * If the MSB are different, then the operand with the MSB of 1 is the
1273 * bigger. (That is if y has MSB of 1, then x<y is true and it is false if
1274 * the MSB of y is 0.)
1275 */
1276 ret |= y & cond;
1277
1278
1279 ret = ret >> ( biL - 1 );
1280
1281 return (unsigned) ret;
1282}
1283
1284/*
1285 * Compare signed values in constant time
1286 */
1287int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *X, const mbedtls_mpi *Y,
1288 unsigned *ret )
1289{
1290 size_t i;
1291 /* The value of any of these variables is either 0 or 1 at all times. */
1292 unsigned cond, done, X_is_negative, Y_is_negative;
1293
1294 MPI_VALIDATE_RET( X != NULL );
1295 MPI_VALIDATE_RET( Y != NULL );
1296 MPI_VALIDATE_RET( ret != NULL );
1297
1298 if( X->n != Y->n )
1299 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
1300
1301 /*
1302 * Set sign_N to 1 if N >= 0, 0 if N < 0.
1303 * We know that N->s == 1 if N >= 0 and N->s == -1 if N < 0.
1304 */
1305 X_is_negative = ( X->s & 2 ) >> 1;
1306 Y_is_negative = ( Y->s & 2 ) >> 1;
1307
1308 /*
1309 * If the signs are different, then the positive operand is the bigger.
1310 * That is if X is negative (X_is_negative == 1), then X < Y is true and it
1311 * is false if X is positive (X_is_negative == 0).
1312 */
1313 cond = ( X_is_negative ^ Y_is_negative );
1314 *ret = cond & X_is_negative;
1315
1316 /*
1317 * This is a constant-time function. We might have the result, but we still
1318 * need to go through the loop. Record if we have the result already.
1319 */
1320 done = cond;
1321
1322 for( i = X->n; i > 0; i-- )
1323 {
1324 /*
1325 * If Y->p[i - 1] < X->p[i - 1] then X < Y is true if and only if both
1326 * X and Y are negative.
1327 *
1328 * Again even if we can make a decision, we just mark the result and
1329 * the fact that we are done and continue looping.
1330 */
1331 cond = ct_lt_mpi_uint( Y->p[i - 1], X->p[i - 1] );
1332 *ret |= cond & ( 1 - done ) & X_is_negative;
1333 done |= cond;
1334
1335 /*
1336 * If X->p[i - 1] < Y->p[i - 1] then X < Y is true if and only if both
1337 * X and Y are positive.
1338 *
1339 * Again even if we can make a decision, we just mark the result and
1340 * the fact that we are done and continue looping.
1341 */
1342 cond = ct_lt_mpi_uint( X->p[i - 1], Y->p[i - 1] );
1343 *ret |= cond & ( 1 - done ) & ( 1 - X_is_negative );
1344 done |= cond;
1345 }
1346
1347 return( 0 );
1348}
1349
Jens Wiklander817466c2018-05-22 13:49:31 +02001350/*
1351 * Compare signed values
1352 */
1353int mbedtls_mpi_cmp_int( const mbedtls_mpi *X, mbedtls_mpi_sint z )
1354{
1355 mbedtls_mpi Y;
1356 mbedtls_mpi_uint p[1];
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001357 MPI_VALIDATE_RET( X != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02001358
1359 *p = ( z < 0 ) ? -z : z;
1360 Y.s = ( z < 0 ) ? -1 : 1;
1361 Y.n = 1;
1362 Y.p = p;
1363
1364 return( mbedtls_mpi_cmp_mpi( X, &Y ) );
1365}
1366
1367/*
1368 * Unsigned addition: X = |A| + |B| (HAC 14.7)
1369 */
1370int mbedtls_mpi_add_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
1371{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02001372 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +02001373 size_t i, j;
1374 mbedtls_mpi_uint *o, *p, c, tmp;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001375 MPI_VALIDATE_RET( X != NULL );
1376 MPI_VALIDATE_RET( A != NULL );
1377 MPI_VALIDATE_RET( B != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02001378
1379 if( X == B )
1380 {
1381 const mbedtls_mpi *T = A; A = X; B = T;
1382 }
1383
1384 if( X != A )
1385 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, A ) );
1386
1387 /*
1388 * X should always be positive as a result of unsigned additions.
1389 */
1390 X->s = 1;
1391
1392 for( j = B->n; j > 0; j-- )
1393 if( B->p[j - 1] != 0 )
1394 break;
1395
1396 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, j ) );
1397
1398 o = B->p; p = X->p; c = 0;
1399
1400 /*
1401 * tmp is used because it might happen that p == o
1402 */
1403 for( i = 0; i < j; i++, o++, p++ )
1404 {
1405 tmp= *o;
1406 *p += c; c = ( *p < c );
1407 *p += tmp; c += ( *p < tmp );
1408 }
1409
1410 while( c != 0 )
1411 {
1412 if( i >= X->n )
1413 {
1414 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i + 1 ) );
1415 p = X->p + i;
1416 }
1417
1418 *p += c; c = ( *p < c ); i++; p++;
1419 }
1420
1421cleanup:
1422
1423 return( ret );
1424}
1425
Jerome Forissier3602df82021-07-28 10:24:04 +02001426/**
1427 * Helper for mbedtls_mpi subtraction.
1428 *
1429 * Calculate l - r where l and r have the same size.
1430 * This function operates modulo (2^ciL)^n and returns the carry
1431 * (1 if there was a wraparound, i.e. if `l < r`, and 0 otherwise).
1432 *
1433 * d may be aliased to l or r.
1434 *
1435 * \param n Number of limbs of \p d, \p l and \p r.
1436 * \param[out] d The result of the subtraction.
1437 * \param[in] l The left operand.
1438 * \param[in] r The right operand.
1439 *
1440 * \return 1 if `l < r`.
1441 * 0 if `l >= r`.
Jens Wiklander817466c2018-05-22 13:49:31 +02001442 */
Jerome Forissier3602df82021-07-28 10:24:04 +02001443static mbedtls_mpi_uint mpi_sub_hlp( size_t n,
1444 mbedtls_mpi_uint *d,
1445 const mbedtls_mpi_uint *l,
1446 const mbedtls_mpi_uint *r )
Jens Wiklander817466c2018-05-22 13:49:31 +02001447{
1448 size_t i;
Jerome Forissier3602df82021-07-28 10:24:04 +02001449 mbedtls_mpi_uint c = 0, t, z;
Jens Wiklander817466c2018-05-22 13:49:31 +02001450
Jerome Forissier3602df82021-07-28 10:24:04 +02001451 for( i = 0; i < n; i++ )
Jens Wiklander817466c2018-05-22 13:49:31 +02001452 {
Jerome Forissier3602df82021-07-28 10:24:04 +02001453 z = ( l[i] < c ); t = l[i] - c;
1454 c = ( t < r[i] ) + z; d[i] = t - r[i];
Jens Wiklander817466c2018-05-22 13:49:31 +02001455 }
1456
Jerome Forissier3602df82021-07-28 10:24:04 +02001457 return( c );
Jens Wiklander817466c2018-05-22 13:49:31 +02001458}
1459
1460/*
Jerome Forissier3602df82021-07-28 10:24:04 +02001461 * Unsigned subtraction: X = |A| - |B| (HAC 14.9, 14.10)
Jens Wiklander817466c2018-05-22 13:49:31 +02001462 */
1463int mbedtls_mpi_sub_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
1464{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02001465 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +02001466 size_t n;
Jerome Forissier3602df82021-07-28 10:24:04 +02001467 mbedtls_mpi_uint carry;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001468 MPI_VALIDATE_RET( X != NULL );
1469 MPI_VALIDATE_RET( A != NULL );
1470 MPI_VALIDATE_RET( B != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02001471
Jens Wiklander817466c2018-05-22 13:49:31 +02001472 for( n = B->n; n > 0; n-- )
1473 if( B->p[n - 1] != 0 )
1474 break;
Jerome Forissier3602df82021-07-28 10:24:04 +02001475 if( n > A->n )
1476 {
1477 /* B >= (2^ciL)^n > A */
1478 ret = MBEDTLS_ERR_MPI_NEGATIVE_VALUE;
1479 goto cleanup;
1480 }
Jens Wiklander817466c2018-05-22 13:49:31 +02001481
Jerome Forissier3602df82021-07-28 10:24:04 +02001482 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, A->n ) );
1483
1484 /* Set the high limbs of X to match A. Don't touch the lower limbs
1485 * because X might be aliased to B, and we must not overwrite the
1486 * significant digits of B. */
1487 if( A->n > n )
1488 memcpy( X->p + n, A->p + n, ( A->n - n ) * ciL );
1489 if( X->n > A->n )
1490 memset( X->p + A->n, 0, ( X->n - A->n ) * ciL );
1491
1492 carry = mpi_sub_hlp( n, X->p, A->p, B->p );
1493 if( carry != 0 )
1494 {
1495 /* Propagate the carry to the first nonzero limb of X. */
1496 for( ; n < X->n && X->p[n] == 0; n++ )
1497 --X->p[n];
1498 /* If we ran out of space for the carry, it means that the result
1499 * is negative. */
1500 if( n == X->n )
1501 {
1502 ret = MBEDTLS_ERR_MPI_NEGATIVE_VALUE;
1503 goto cleanup;
1504 }
1505 --X->p[n];
1506 }
1507
1508 /* X should always be positive as a result of unsigned subtractions. */
1509 X->s = 1;
Jens Wiklander817466c2018-05-22 13:49:31 +02001510
1511cleanup:
Jens Wiklander817466c2018-05-22 13:49:31 +02001512 return( ret );
1513}
1514
1515/*
1516 * Signed addition: X = A + B
1517 */
1518int mbedtls_mpi_add_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
1519{
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001520 int ret, s;
1521 MPI_VALIDATE_RET( X != NULL );
1522 MPI_VALIDATE_RET( A != NULL );
1523 MPI_VALIDATE_RET( B != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02001524
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001525 s = A->s;
Jens Wiklander817466c2018-05-22 13:49:31 +02001526 if( A->s * B->s < 0 )
1527 {
1528 if( mbedtls_mpi_cmp_abs( A, B ) >= 0 )
1529 {
1530 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( X, A, B ) );
1531 X->s = s;
1532 }
1533 else
1534 {
1535 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( X, B, A ) );
1536 X->s = -s;
1537 }
1538 }
1539 else
1540 {
1541 MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( X, A, B ) );
1542 X->s = s;
1543 }
1544
1545cleanup:
1546
1547 return( ret );
1548}
1549
1550/*
1551 * Signed subtraction: X = A - B
1552 */
1553int mbedtls_mpi_sub_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
1554{
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001555 int ret, s;
1556 MPI_VALIDATE_RET( X != NULL );
1557 MPI_VALIDATE_RET( A != NULL );
1558 MPI_VALIDATE_RET( B != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02001559
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001560 s = A->s;
Jens Wiklander817466c2018-05-22 13:49:31 +02001561 if( A->s * B->s > 0 )
1562 {
1563 if( mbedtls_mpi_cmp_abs( A, B ) >= 0 )
1564 {
1565 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( X, A, B ) );
1566 X->s = s;
1567 }
1568 else
1569 {
1570 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( X, B, A ) );
1571 X->s = -s;
1572 }
1573 }
1574 else
1575 {
1576 MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( X, A, B ) );
1577 X->s = s;
1578 }
1579
1580cleanup:
1581
1582 return( ret );
1583}
1584
1585/*
1586 * Signed addition: X = A + b
1587 */
1588int mbedtls_mpi_add_int( mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_sint b )
1589{
1590 mbedtls_mpi _B;
1591 mbedtls_mpi_uint p[1];
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001592 MPI_VALIDATE_RET( X != NULL );
1593 MPI_VALIDATE_RET( A != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02001594
1595 p[0] = ( b < 0 ) ? -b : b;
1596 _B.s = ( b < 0 ) ? -1 : 1;
1597 _B.n = 1;
1598 _B.p = p;
1599
1600 return( mbedtls_mpi_add_mpi( X, A, &_B ) );
1601}
1602
1603/*
1604 * Signed subtraction: X = A - b
1605 */
1606int mbedtls_mpi_sub_int( mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_sint b )
1607{
1608 mbedtls_mpi _B;
1609 mbedtls_mpi_uint p[1];
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001610 MPI_VALIDATE_RET( X != NULL );
1611 MPI_VALIDATE_RET( A != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02001612
1613 p[0] = ( b < 0 ) ? -b : b;
1614 _B.s = ( b < 0 ) ? -1 : 1;
1615 _B.n = 1;
1616 _B.p = p;
1617
1618 return( mbedtls_mpi_sub_mpi( X, A, &_B ) );
1619}
1620
Jerome Forissier3602df82021-07-28 10:24:04 +02001621/** Helper for mbedtls_mpi multiplication.
1622 *
1623 * Add \p b * \p s to \p d.
1624 *
1625 * \param i The number of limbs of \p s.
1626 * \param[in] s A bignum to multiply, of size \p i.
1627 * It may overlap with \p d, but only if
1628 * \p d <= \p s.
1629 * Its leading limb must not be \c 0.
1630 * \param[in,out] d The bignum to add to.
1631 * It must be sufficiently large to store the
1632 * result of the multiplication. This means
1633 * \p i + 1 limbs if \p d[\p i - 1] started as 0 and \p b
1634 * is not known a priori.
1635 * \param b A scalar to multiply.
Jens Wiklander817466c2018-05-22 13:49:31 +02001636 */
1637static
1638#if defined(__APPLE__) && defined(__arm__)
1639/*
1640 * Apple LLVM version 4.2 (clang-425.0.24) (based on LLVM 3.2svn)
1641 * appears to need this to prevent bad ARM code generation at -O3.
1642 */
1643__attribute__ ((noinline))
1644#endif
Jerome Forissier3602df82021-07-28 10:24:04 +02001645void mpi_mul_hlp( size_t i,
1646 const mbedtls_mpi_uint *s,
1647 mbedtls_mpi_uint *d,
1648 mbedtls_mpi_uint b )
Jens Wiklander817466c2018-05-22 13:49:31 +02001649{
1650 mbedtls_mpi_uint c = 0, t = 0;
1651
1652#if defined(MULADDC_HUIT)
1653 for( ; i >= 8; i -= 8 )
1654 {
1655 MULADDC_INIT
1656 MULADDC_HUIT
1657 MULADDC_STOP
1658 }
1659
1660 for( ; i > 0; i-- )
1661 {
1662 MULADDC_INIT
1663 MULADDC_CORE
1664 MULADDC_STOP
1665 }
1666#else /* MULADDC_HUIT */
1667 for( ; i >= 16; i -= 16 )
1668 {
1669 MULADDC_INIT
1670 MULADDC_CORE MULADDC_CORE
1671 MULADDC_CORE MULADDC_CORE
1672 MULADDC_CORE MULADDC_CORE
1673 MULADDC_CORE MULADDC_CORE
1674
1675 MULADDC_CORE MULADDC_CORE
1676 MULADDC_CORE MULADDC_CORE
1677 MULADDC_CORE MULADDC_CORE
1678 MULADDC_CORE MULADDC_CORE
1679 MULADDC_STOP
1680 }
1681
1682 for( ; i >= 8; i -= 8 )
1683 {
1684 MULADDC_INIT
1685 MULADDC_CORE MULADDC_CORE
1686 MULADDC_CORE MULADDC_CORE
1687
1688 MULADDC_CORE MULADDC_CORE
1689 MULADDC_CORE MULADDC_CORE
1690 MULADDC_STOP
1691 }
1692
1693 for( ; i > 0; i-- )
1694 {
1695 MULADDC_INIT
1696 MULADDC_CORE
1697 MULADDC_STOP
1698 }
1699#endif /* MULADDC_HUIT */
1700
1701 t++;
1702
Jerome Forissier3602df82021-07-28 10:24:04 +02001703 while( c != 0 )
1704 {
Jens Wiklander817466c2018-05-22 13:49:31 +02001705 *d += c; c = ( *d < c ); d++;
1706 }
Jens Wiklander817466c2018-05-22 13:49:31 +02001707}
1708
1709/*
1710 * Baseline multiplication: X = A * B (HAC 14.12)
1711 */
1712int mbedtls_mpi_mul_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
1713{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02001714 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +02001715 size_t i, j;
1716 mbedtls_mpi TA, TB;
Jerome Forissier3602df82021-07-28 10:24:04 +02001717 int result_is_zero = 0;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001718 MPI_VALIDATE_RET( X != NULL );
1719 MPI_VALIDATE_RET( A != NULL );
1720 MPI_VALIDATE_RET( B != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02001721
Jerome Forissier3602df82021-07-28 10:24:04 +02001722 mbedtls_mpi_init( &TA ); mbedtls_mpi_init( &TB );
Jens Wiklander817466c2018-05-22 13:49:31 +02001723
1724 if( X == A ) { MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TA, A ) ); A = &TA; }
1725 if( X == B ) { MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, B ) ); B = &TB; }
1726
1727 for( i = A->n; i > 0; i-- )
1728 if( A->p[i - 1] != 0 )
1729 break;
Jerome Forissier3602df82021-07-28 10:24:04 +02001730 if( i == 0 )
1731 result_is_zero = 1;
Jens Wiklander817466c2018-05-22 13:49:31 +02001732
1733 for( j = B->n; j > 0; j-- )
1734 if( B->p[j - 1] != 0 )
1735 break;
Jerome Forissier3602df82021-07-28 10:24:04 +02001736 if( j == 0 )
1737 result_is_zero = 1;
Jens Wiklander817466c2018-05-22 13:49:31 +02001738
1739 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i + j ) );
1740 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );
1741
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001742 for( ; j > 0; j-- )
1743 mpi_mul_hlp( i, A->p, X->p + j - 1, B->p[j - 1] );
Jens Wiklander817466c2018-05-22 13:49:31 +02001744
Jerome Forissier3602df82021-07-28 10:24:04 +02001745 /* If the result is 0, we don't shortcut the operation, which reduces
1746 * but does not eliminate side channels leaking the zero-ness. We do
1747 * need to take care to set the sign bit properly since the library does
1748 * not fully support an MPI object with a value of 0 and s == -1. */
1749 if( result_is_zero )
1750 X->s = 1;
1751 else
1752 X->s = A->s * B->s;
Jens Wiklander817466c2018-05-22 13:49:31 +02001753
1754cleanup:
1755
1756 mbedtls_mpi_free( &TB ); mbedtls_mpi_free( &TA );
1757
1758 return( ret );
1759}
1760
1761/*
1762 * Baseline multiplication: X = A * b
1763 */
1764int mbedtls_mpi_mul_int( mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_uint b )
1765{
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001766 MPI_VALIDATE_RET( X != NULL );
1767 MPI_VALIDATE_RET( A != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02001768
Jerome Forissier3602df82021-07-28 10:24:04 +02001769 /* mpi_mul_hlp can't deal with a leading 0. */
1770 size_t n = A->n;
1771 while( n > 0 && A->p[n - 1] == 0 )
1772 --n;
Jens Wiklander817466c2018-05-22 13:49:31 +02001773
Jerome Forissier3602df82021-07-28 10:24:04 +02001774 /* The general method below doesn't work if n==0 or b==0. By chance
1775 * calculating the result is trivial in those cases. */
1776 if( b == 0 || n == 0 )
1777 {
1778 return( mbedtls_mpi_lset( X, 0 ) );
1779 }
1780
1781 /* Calculate A*b as A + A*(b-1) to take advantage of mpi_mul_hlp */
1782 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1783 /* In general, A * b requires 1 limb more than b. If
1784 * A->p[n - 1] * b / b == A->p[n - 1], then A * b fits in the same
1785 * number of limbs as A and the call to grow() is not required since
1786 * copy() will take care of the growth if needed. However, experimentally,
1787 * making the call to grow() unconditional causes slightly fewer
1788 * calls to calloc() in ECP code, presumably because it reuses the
1789 * same mpi for a while and this way the mpi is more likely to directly
1790 * grow to its final size. */
1791 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, n + 1 ) );
1792 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, A ) );
1793 mpi_mul_hlp( n, A->p, X->p, b - 1 );
1794
1795cleanup:
1796 return( ret );
Jens Wiklander817466c2018-05-22 13:49:31 +02001797}
1798
1799/*
1800 * Unsigned integer divide - double mbedtls_mpi_uint dividend, u1/u0, and
1801 * mbedtls_mpi_uint divisor, d
1802 */
1803static mbedtls_mpi_uint mbedtls_int_div_int( mbedtls_mpi_uint u1,
1804 mbedtls_mpi_uint u0, mbedtls_mpi_uint d, mbedtls_mpi_uint *r )
1805{
1806#if defined(MBEDTLS_HAVE_UDBL)
1807 mbedtls_t_udbl dividend, quotient;
1808#else
1809 const mbedtls_mpi_uint radix = (mbedtls_mpi_uint) 1 << biH;
1810 const mbedtls_mpi_uint uint_halfword_mask = ( (mbedtls_mpi_uint) 1 << biH ) - 1;
1811 mbedtls_mpi_uint d0, d1, q0, q1, rAX, r0, quotient;
1812 mbedtls_mpi_uint u0_msw, u0_lsw;
1813 size_t s;
1814#endif
1815
1816 /*
1817 * Check for overflow
1818 */
1819 if( 0 == d || u1 >= d )
1820 {
1821 if (r != NULL) *r = ~0;
1822
1823 return ( ~0 );
1824 }
1825
1826#if defined(MBEDTLS_HAVE_UDBL)
1827 dividend = (mbedtls_t_udbl) u1 << biL;
1828 dividend |= (mbedtls_t_udbl) u0;
1829 quotient = dividend / d;
1830 if( quotient > ( (mbedtls_t_udbl) 1 << biL ) - 1 )
1831 quotient = ( (mbedtls_t_udbl) 1 << biL ) - 1;
1832
1833 if( r != NULL )
1834 *r = (mbedtls_mpi_uint)( dividend - (quotient * d ) );
1835
1836 return (mbedtls_mpi_uint) quotient;
1837#else
1838
1839 /*
1840 * Algorithm D, Section 4.3.1 - The Art of Computer Programming
1841 * Vol. 2 - Seminumerical Algorithms, Knuth
1842 */
1843
1844 /*
1845 * Normalize the divisor, d, and dividend, u0, u1
1846 */
1847 s = mbedtls_clz( d );
1848 d = d << s;
1849
1850 u1 = u1 << s;
1851 u1 |= ( u0 >> ( biL - s ) ) & ( -(mbedtls_mpi_sint)s >> ( biL - 1 ) );
1852 u0 = u0 << s;
1853
1854 d1 = d >> biH;
1855 d0 = d & uint_halfword_mask;
1856
1857 u0_msw = u0 >> biH;
1858 u0_lsw = u0 & uint_halfword_mask;
1859
1860 /*
1861 * Find the first quotient and remainder
1862 */
1863 q1 = u1 / d1;
1864 r0 = u1 - d1 * q1;
1865
1866 while( q1 >= radix || ( q1 * d0 > radix * r0 + u0_msw ) )
1867 {
1868 q1 -= 1;
1869 r0 += d1;
1870
1871 if ( r0 >= radix ) break;
1872 }
1873
1874 rAX = ( u1 * radix ) + ( u0_msw - q1 * d );
1875 q0 = rAX / d1;
1876 r0 = rAX - q0 * d1;
1877
1878 while( q0 >= radix || ( q0 * d0 > radix * r0 + u0_lsw ) )
1879 {
1880 q0 -= 1;
1881 r0 += d1;
1882
1883 if ( r0 >= radix ) break;
1884 }
1885
1886 if (r != NULL)
1887 *r = ( rAX * radix + u0_lsw - q0 * d ) >> s;
1888
1889 quotient = q1 * radix + q0;
1890
1891 return quotient;
1892#endif
1893}
1894
1895/*
1896 * Division by mbedtls_mpi: A = Q * B + R (HAC 14.20)
1897 */
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001898int mbedtls_mpi_div_mpi( mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A,
1899 const mbedtls_mpi *B )
Jens Wiklander817466c2018-05-22 13:49:31 +02001900{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02001901 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +02001902 size_t i, n, t, k;
1903 mbedtls_mpi X, Y, Z, T1, T2;
Jerome Forissier11fa71b2020-04-20 17:17:56 +02001904 mbedtls_mpi_uint TP2[3];
Jens Wiklander3d3b0592019-03-20 15:30:29 +01001905 MPI_VALIDATE_RET( A != NULL );
1906 MPI_VALIDATE_RET( B != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02001907
1908 if( mbedtls_mpi_cmp_int( B, 0 ) == 0 )
1909 return( MBEDTLS_ERR_MPI_DIVISION_BY_ZERO );
1910
Jerome Forissier3602df82021-07-28 10:24:04 +02001911 mbedtls_mpi_init( &X ); mbedtls_mpi_init( &Y ); mbedtls_mpi_init( &Z );
1912 mbedtls_mpi_init( &T1 );
Jerome Forissier11fa71b2020-04-20 17:17:56 +02001913 /*
1914 * Avoid dynamic memory allocations for constant-size T2.
1915 *
1916 * T2 is used for comparison only and the 3 limbs are assigned explicitly,
1917 * so nobody increase the size of the MPI and we're safe to use an on-stack
1918 * buffer.
1919 */
1920 T2.s = 1;
1921 T2.n = sizeof( TP2 ) / sizeof( *TP2 );
1922 T2.p = TP2;
Jens Wiklander817466c2018-05-22 13:49:31 +02001923
1924 if( mbedtls_mpi_cmp_abs( A, B ) < 0 )
1925 {
1926 if( Q != NULL ) MBEDTLS_MPI_CHK( mbedtls_mpi_lset( Q, 0 ) );
1927 if( R != NULL ) MBEDTLS_MPI_CHK( mbedtls_mpi_copy( R, A ) );
1928 return( 0 );
1929 }
1930
1931 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &X, A ) );
1932 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Y, B ) );
1933 X.s = Y.s = 1;
1934
1935 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &Z, A->n + 2 ) );
1936 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &Z, 0 ) );
Jerome Forissier3602df82021-07-28 10:24:04 +02001937 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &T1, A->n + 2 ) );
Jens Wiklander817466c2018-05-22 13:49:31 +02001938
1939 k = mbedtls_mpi_bitlen( &Y ) % biL;
1940 if( k < biL - 1 )
1941 {
1942 k = biL - 1 - k;
1943 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &X, k ) );
1944 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &Y, k ) );
1945 }
1946 else k = 0;
1947
1948 n = X.n - 1;
1949 t = Y.n - 1;
1950 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &Y, biL * ( n - t ) ) );
1951
1952 while( mbedtls_mpi_cmp_mpi( &X, &Y ) >= 0 )
1953 {
1954 Z.p[n - t]++;
1955 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &X, &X, &Y ) );
1956 }
1957 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &Y, biL * ( n - t ) ) );
1958
1959 for( i = n; i > t ; i-- )
1960 {
1961 if( X.p[i] >= Y.p[t] )
1962 Z.p[i - t - 1] = ~0;
1963 else
1964 {
1965 Z.p[i - t - 1] = mbedtls_int_div_int( X.p[i], X.p[i - 1],
1966 Y.p[t], NULL);
1967 }
1968
Jerome Forissier11fa71b2020-04-20 17:17:56 +02001969 T2.p[0] = ( i < 2 ) ? 0 : X.p[i - 2];
1970 T2.p[1] = ( i < 1 ) ? 0 : X.p[i - 1];
1971 T2.p[2] = X.p[i];
1972
Jens Wiklander817466c2018-05-22 13:49:31 +02001973 Z.p[i - t - 1]++;
1974 do
1975 {
1976 Z.p[i - t - 1]--;
1977
1978 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &T1, 0 ) );
1979 T1.p[0] = ( t < 1 ) ? 0 : Y.p[t - 1];
1980 T1.p[1] = Y.p[t];
1981 MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &T1, &T1, Z.p[i - t - 1] ) );
Jens Wiklander817466c2018-05-22 13:49:31 +02001982 }
1983 while( mbedtls_mpi_cmp_mpi( &T1, &T2 ) > 0 );
1984
1985 MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &T1, &Y, Z.p[i - t - 1] ) );
1986 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &T1, biL * ( i - t - 1 ) ) );
1987 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &X, &X, &T1 ) );
1988
1989 if( mbedtls_mpi_cmp_int( &X, 0 ) < 0 )
1990 {
1991 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &T1, &Y ) );
1992 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &T1, biL * ( i - t - 1 ) ) );
1993 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &X, &X, &T1 ) );
1994 Z.p[i - t - 1]--;
1995 }
1996 }
1997
1998 if( Q != NULL )
1999 {
2000 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( Q, &Z ) );
2001 Q->s = A->s * B->s;
2002 }
2003
2004 if( R != NULL )
2005 {
2006 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &X, k ) );
2007 X.s = A->s;
2008 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( R, &X ) );
2009
2010 if( mbedtls_mpi_cmp_int( R, 0 ) == 0 )
2011 R->s = 1;
2012 }
2013
2014cleanup:
2015
2016 mbedtls_mpi_free( &X ); mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &Z );
Jerome Forissier11fa71b2020-04-20 17:17:56 +02002017 mbedtls_mpi_free( &T1 );
2018 mbedtls_platform_zeroize( TP2, sizeof( TP2 ) );
Jens Wiklander817466c2018-05-22 13:49:31 +02002019
2020 return( ret );
2021}
2022
2023/*
2024 * Division by int: A = Q * b + R
2025 */
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002026int mbedtls_mpi_div_int( mbedtls_mpi *Q, mbedtls_mpi *R,
2027 const mbedtls_mpi *A,
2028 mbedtls_mpi_sint b )
Jens Wiklander817466c2018-05-22 13:49:31 +02002029{
2030 mbedtls_mpi _B;
2031 mbedtls_mpi_uint p[1];
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002032 MPI_VALIDATE_RET( A != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02002033
2034 p[0] = ( b < 0 ) ? -b : b;
2035 _B.s = ( b < 0 ) ? -1 : 1;
2036 _B.n = 1;
2037 _B.p = p;
2038
2039 return( mbedtls_mpi_div_mpi( Q, R, A, &_B ) );
2040}
2041
2042/*
2043 * Modulo: R = A mod B
2044 */
2045int mbedtls_mpi_mod_mpi( mbedtls_mpi *R, const mbedtls_mpi *A, const mbedtls_mpi *B )
2046{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02002047 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002048 MPI_VALIDATE_RET( R != NULL );
2049 MPI_VALIDATE_RET( A != NULL );
2050 MPI_VALIDATE_RET( B != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02002051
2052 if( mbedtls_mpi_cmp_int( B, 0 ) < 0 )
2053 return( MBEDTLS_ERR_MPI_NEGATIVE_VALUE );
2054
2055 MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( NULL, R, A, B ) );
2056
2057 while( mbedtls_mpi_cmp_int( R, 0 ) < 0 )
2058 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( R, R, B ) );
2059
2060 while( mbedtls_mpi_cmp_mpi( R, B ) >= 0 )
2061 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( R, R, B ) );
2062
2063cleanup:
2064
2065 return( ret );
2066}
2067
2068/*
2069 * Modulo: r = A mod b
2070 */
2071int mbedtls_mpi_mod_int( mbedtls_mpi_uint *r, const mbedtls_mpi *A, mbedtls_mpi_sint b )
2072{
2073 size_t i;
2074 mbedtls_mpi_uint x, y, z;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002075 MPI_VALIDATE_RET( r != NULL );
2076 MPI_VALIDATE_RET( A != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02002077
2078 if( b == 0 )
2079 return( MBEDTLS_ERR_MPI_DIVISION_BY_ZERO );
2080
2081 if( b < 0 )
2082 return( MBEDTLS_ERR_MPI_NEGATIVE_VALUE );
2083
2084 /*
2085 * handle trivial cases
2086 */
2087 if( b == 1 )
2088 {
2089 *r = 0;
2090 return( 0 );
2091 }
2092
2093 if( b == 2 )
2094 {
2095 *r = A->p[0] & 1;
2096 return( 0 );
2097 }
2098
2099 /*
2100 * general case
2101 */
2102 for( i = A->n, y = 0; i > 0; i-- )
2103 {
2104 x = A->p[i - 1];
2105 y = ( y << biH ) | ( x >> biH );
2106 z = y / b;
2107 y -= z * b;
2108
2109 x <<= biH;
2110 y = ( y << biH ) | ( x >> biH );
2111 z = y / b;
2112 y -= z * b;
2113 }
2114
2115 /*
2116 * If A is negative, then the current y represents a negative value.
2117 * Flipping it to the positive side.
2118 */
2119 if( A->s < 0 && y != 0 )
2120 y = b - y;
2121
2122 *r = y;
2123
2124 return( 0 );
2125}
2126
2127/*
2128 * Fast Montgomery initialization (thanks to Tom St Denis)
2129 */
Jerome Forissier3602df82021-07-28 10:24:04 +02002130static void mpi_montg_init( mbedtls_mpi_uint *mm, const mbedtls_mpi *N )
Jens Wiklander817466c2018-05-22 13:49:31 +02002131{
2132 mbedtls_mpi_uint x, m0 = N->p[0];
2133 unsigned int i;
2134
2135 x = m0;
2136 x += ( ( m0 + 2 ) & 4 ) << 1;
2137
2138 for( i = biL; i >= 8; i /= 2 )
2139 x *= ( 2 - ( m0 * x ) );
2140
2141 *mm = ~x + 1;
2142}
2143
Jerome Forissier3602df82021-07-28 10:24:04 +02002144/** Montgomery multiplication: A = A * B * R^-1 mod N (HAC 14.36)
2145 *
2146 * \param[in,out] A One of the numbers to multiply.
2147 * It must have at least as many limbs as N
2148 * (A->n >= N->n), and any limbs beyond n are ignored.
2149 * On successful completion, A contains the result of
2150 * the multiplication A * B * R^-1 mod N where
2151 * R = (2^ciL)^n.
2152 * \param[in] B One of the numbers to multiply.
2153 * It must be nonzero and must not have more limbs than N
2154 * (B->n <= N->n).
2155 * \param[in] N The modulo. N must be odd.
2156 * \param mm The value calculated by `mpi_montg_init(&mm, N)`.
2157 * This is -N^-1 mod 2^ciL.
2158 * \param[in,out] T A bignum for temporary storage.
2159 * It must be at least twice the limb size of N plus 2
2160 * (T->n >= 2 * (N->n + 1)).
2161 * Its initial content is unused and
2162 * its final content is indeterminate.
2163 * Note that unlike the usual convention in the library
2164 * for `const mbedtls_mpi*`, the content of T can change.
Jens Wiklander817466c2018-05-22 13:49:31 +02002165 */
Jerome Forissier3602df82021-07-28 10:24:04 +02002166static void mpi_montmul( mbedtls_mpi *A, const mbedtls_mpi *B, const mbedtls_mpi *N, mbedtls_mpi_uint mm,
Jens Wiklander817466c2018-05-22 13:49:31 +02002167 const mbedtls_mpi *T )
2168{
2169 size_t i, n, m;
2170 mbedtls_mpi_uint u0, u1, *d;
2171
Jens Wiklander817466c2018-05-22 13:49:31 +02002172 memset( T->p, 0, T->n * ciL );
2173
2174 d = T->p;
2175 n = N->n;
2176 m = ( B->n < n ) ? B->n : n;
2177
2178 for( i = 0; i < n; i++ )
2179 {
2180 /*
2181 * T = (T + u0*B + u1*N) / 2^biL
2182 */
2183 u0 = A->p[i];
2184 u1 = ( d[0] + u0 * B->p[0] ) * mm;
2185
2186 mpi_mul_hlp( m, B->p, d, u0 );
2187 mpi_mul_hlp( n, N->p, d, u1 );
2188
2189 *d++ = u0; d[n + 1] = 0;
2190 }
2191
Jerome Forissier3602df82021-07-28 10:24:04 +02002192 /* At this point, d is either the desired result or the desired result
2193 * plus N. We now potentially subtract N, avoiding leaking whether the
2194 * subtraction is performed through side channels. */
Jens Wiklander817466c2018-05-22 13:49:31 +02002195
Jerome Forissier3602df82021-07-28 10:24:04 +02002196 /* Copy the n least significant limbs of d to A, so that
2197 * A = d if d < N (recall that N has n limbs). */
2198 memcpy( A->p, d, n * ciL );
2199 /* If d >= N then we want to set A to d - N. To prevent timing attacks,
2200 * do the calculation without using conditional tests. */
2201 /* Set d to d0 + (2^biL)^n - N where d0 is the current value of d. */
2202 d[n] += 1;
2203 d[n] -= mpi_sub_hlp( n, d, d, N->p );
2204 /* If d0 < N then d < (2^biL)^n
2205 * so d[n] == 0 and we want to keep A as it is.
2206 * If d0 >= N then d >= (2^biL)^n, and d <= (2^biL)^n + N < 2 * (2^biL)^n
2207 * so d[n] == 1 and we want to set A to the result of the subtraction
2208 * which is d - (2^biL)^n, i.e. the n least significant limbs of d.
2209 * This exactly corresponds to a conditional assignment. */
2210 mpi_safe_cond_assign( n, A->p, d, (unsigned char) d[n] );
Jens Wiklander817466c2018-05-22 13:49:31 +02002211}
2212
2213/*
2214 * Montgomery reduction: A = A * R^-1 mod N
Jerome Forissier3602df82021-07-28 10:24:04 +02002215 *
2216 * See mpi_montmul() regarding constraints and guarantees on the parameters.
Jens Wiklander817466c2018-05-22 13:49:31 +02002217 */
Jerome Forissier3602df82021-07-28 10:24:04 +02002218static void mpi_montred( mbedtls_mpi *A, const mbedtls_mpi *N,
2219 mbedtls_mpi_uint mm, const mbedtls_mpi *T )
Jens Wiklander817466c2018-05-22 13:49:31 +02002220{
2221 mbedtls_mpi_uint z = 1;
2222 mbedtls_mpi U;
2223
2224 U.n = U.s = (int) z;
2225 U.p = &z;
2226
Jerome Forissier3602df82021-07-28 10:24:04 +02002227 mpi_montmul( A, &U, N, mm, T );
2228}
2229
2230/*
2231 * Constant-flow boolean "equal" comparison:
2232 * return x == y
2233 *
2234 * This function can be used to write constant-time code by replacing branches
2235 * with bit operations - it can be used in conjunction with
2236 * mbedtls_ssl_cf_mask_from_bit().
2237 *
2238 * This function is implemented without using comparison operators, as those
2239 * might be translated to branches by some compilers on some platforms.
2240 */
2241static size_t mbedtls_mpi_cf_bool_eq( size_t x, size_t y )
2242{
2243 /* diff = 0 if x == y, non-zero otherwise */
2244 const size_t diff = x ^ y;
2245
2246 /* MSVC has a warning about unary minus on unsigned integer types,
2247 * but this is well-defined and precisely what we want to do here. */
2248#if defined(_MSC_VER)
2249#pragma warning( push )
2250#pragma warning( disable : 4146 )
2251#endif
2252
2253 /* diff_msb's most significant bit is equal to x != y */
2254 const size_t diff_msb = ( diff | (size_t) -diff );
2255
2256#if defined(_MSC_VER)
2257#pragma warning( pop )
2258#endif
2259
2260 /* diff1 = (x != y) ? 1 : 0 */
2261 const size_t diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 );
2262
2263 return( 1 ^ diff1 );
2264}
2265
2266/**
2267 * Select an MPI from a table without leaking the index.
2268 *
2269 * This is functionally equivalent to mbedtls_mpi_copy(R, T[idx]) except it
2270 * reads the entire table in order to avoid leaking the value of idx to an
2271 * attacker able to observe memory access patterns.
2272 *
2273 * \param[out] R Where to write the selected MPI.
2274 * \param[in] T The table to read from.
2275 * \param[in] T_size The number of elements in the table.
2276 * \param[in] idx The index of the element to select;
2277 * this must satisfy 0 <= idx < T_size.
2278 *
2279 * \return \c 0 on success, or a negative error code.
2280 */
2281static int mpi_select( mbedtls_mpi *R, const mbedtls_mpi *T, size_t T_size, size_t idx )
2282{
2283 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2284
2285 for( size_t i = 0; i < T_size; i++ )
2286 {
2287 MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( R, &T[i],
2288 (unsigned char) mbedtls_mpi_cf_bool_eq( i, idx ) ) );
2289 }
2290
2291cleanup:
2292 return( ret );
Jens Wiklander817466c2018-05-22 13:49:31 +02002293}
2294
2295/*
2296 * Sliding-window exponentiation: X = A^E mod N (HAC 14.85)
2297 */
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002298int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A,
2299 const mbedtls_mpi *E, const mbedtls_mpi *N,
2300 mbedtls_mpi *_RR )
Jens Wiklander817466c2018-05-22 13:49:31 +02002301{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02002302 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +02002303 size_t wbits, wsize, one = 1;
2304 size_t i, j, nblimbs;
2305 size_t bufsize, nbits;
2306 mbedtls_mpi_uint ei, mm, state;
Jerome Forissier3602df82021-07-28 10:24:04 +02002307 mbedtls_mpi RR, T, W[ 1 << MBEDTLS_MPI_WINDOW_SIZE ], WW, Apos;
Jens Wiklander817466c2018-05-22 13:49:31 +02002308 int neg;
2309
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002310 MPI_VALIDATE_RET( X != NULL );
2311 MPI_VALIDATE_RET( A != NULL );
2312 MPI_VALIDATE_RET( E != NULL );
2313 MPI_VALIDATE_RET( N != NULL );
2314
2315 if( mbedtls_mpi_cmp_int( N, 0 ) <= 0 || ( N->p[0] & 1 ) == 0 )
Jens Wiklander817466c2018-05-22 13:49:31 +02002316 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2317
2318 if( mbedtls_mpi_cmp_int( E, 0 ) < 0 )
2319 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2320
Jerome Forissier3602df82021-07-28 10:24:04 +02002321 if( mbedtls_mpi_bitlen( E ) > MBEDTLS_MPI_MAX_BITS ||
2322 mbedtls_mpi_bitlen( N ) > MBEDTLS_MPI_MAX_BITS )
2323 return ( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2324
Jens Wiklander817466c2018-05-22 13:49:31 +02002325 /*
2326 * Init temps and window size
2327 */
Jerome Forissier3602df82021-07-28 10:24:04 +02002328 mpi_montg_init( &mm, N );
2329 mbedtls_mpi_init( &RR ); mbedtls_mpi_init( &T );
2330 mbedtls_mpi_init( &Apos );
2331 mbedtls_mpi_init( &WW );
2332 memset( W, 0, sizeof( W ) );
Jens Wiklander817466c2018-05-22 13:49:31 +02002333
2334 i = mbedtls_mpi_bitlen( E );
2335
2336 wsize = ( i > 671 ) ? 6 : ( i > 239 ) ? 5 :
2337 ( i > 79 ) ? 4 : ( i > 23 ) ? 3 : 1;
2338
Jerome Forissier5b25c762020-04-07 11:18:49 +02002339#if( MBEDTLS_MPI_WINDOW_SIZE < 6 )
Jens Wiklander817466c2018-05-22 13:49:31 +02002340 if( wsize > MBEDTLS_MPI_WINDOW_SIZE )
2341 wsize = MBEDTLS_MPI_WINDOW_SIZE;
Jerome Forissier5b25c762020-04-07 11:18:49 +02002342#endif
Jens Wiklander817466c2018-05-22 13:49:31 +02002343
2344 j = N->n + 1;
Jerome Forissier3602df82021-07-28 10:24:04 +02002345 /* All W[i] and X must have at least N->n limbs for the mpi_montmul()
2346 * and mpi_montred() calls later. Here we ensure that W[1] and X are
2347 * large enough, and later we'll grow other W[i] to the same length.
2348 * They must not be shrunk midway through this function!
2349 */
Jens Wiklander817466c2018-05-22 13:49:31 +02002350 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, j ) );
Jerome Forissier3602df82021-07-28 10:24:04 +02002351 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[1], j ) );
Jens Wiklander817466c2018-05-22 13:49:31 +02002352 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &T, j * 2 ) );
2353
2354 /*
2355 * Compensate for negative A (and correct at the end)
2356 */
2357 neg = ( A->s == -1 );
2358 if( neg )
2359 {
2360 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Apos, A ) );
2361 Apos.s = 1;
2362 A = &Apos;
2363 }
2364
2365 /*
2366 * If 1st call, pre-compute R^2 mod N
2367 */
2368 if( _RR == NULL || _RR->p == NULL )
2369 {
2370 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &RR, 1 ) );
2371 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &RR, N->n * 2 * biL ) );
2372 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &RR, &RR, N ) );
2373
2374 if( _RR != NULL )
2375 memcpy( _RR, &RR, sizeof( mbedtls_mpi ) );
2376 }
2377 else
2378 memcpy( &RR, _RR, sizeof( mbedtls_mpi ) );
2379
2380 /*
2381 * W[1] = A * R^2 * R^-1 mod N = A * R mod N
2382 */
2383 if( mbedtls_mpi_cmp_mpi( A, N ) >= 0 )
Jerome Forissier3602df82021-07-28 10:24:04 +02002384 {
Jens Wiklander817466c2018-05-22 13:49:31 +02002385 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &W[1], A, N ) );
Jerome Forissier3602df82021-07-28 10:24:04 +02002386 /* This should be a no-op because W[1] is already that large before
2387 * mbedtls_mpi_mod_mpi(), but it's necessary to avoid an overflow
2388 * in mpi_montmul() below, so let's make sure. */
2389 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[1], N->n + 1 ) );
2390 }
Jens Wiklander817466c2018-05-22 13:49:31 +02002391 else
2392 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[1], A ) );
2393
Jerome Forissier3602df82021-07-28 10:24:04 +02002394 /* Note that this is safe because W[1] always has at least N->n limbs
2395 * (it grew above and was preserved by mbedtls_mpi_copy()). */
2396 mpi_montmul( &W[1], &RR, N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002397
2398 /*
2399 * X = R^2 * R^-1 mod N = R mod N
2400 */
2401 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, &RR ) );
Jerome Forissier3602df82021-07-28 10:24:04 +02002402 mpi_montred( X, N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002403
2404 if( wsize > 1 )
2405 {
2406 /*
2407 * W[1 << (wsize - 1)] = W[1] ^ (wsize - 1)
2408 */
2409 j = one << ( wsize - 1 );
2410
2411 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[j], N->n + 1 ) );
2412 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[j], &W[1] ) );
2413
2414 for( i = 0; i < wsize - 1; i++ )
Jerome Forissier3602df82021-07-28 10:24:04 +02002415 mpi_montmul( &W[j], &W[j], N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002416
2417 /*
2418 * W[i] = W[i - 1] * W[1]
2419 */
2420 for( i = j + 1; i < ( one << wsize ); i++ )
2421 {
2422 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[i], N->n + 1 ) );
2423 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[i], &W[i - 1] ) );
2424
Jerome Forissier3602df82021-07-28 10:24:04 +02002425 mpi_montmul( &W[i], &W[1], N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002426 }
2427 }
2428
2429 nblimbs = E->n;
2430 bufsize = 0;
2431 nbits = 0;
2432 wbits = 0;
2433 state = 0;
2434
2435 while( 1 )
2436 {
2437 if( bufsize == 0 )
2438 {
2439 if( nblimbs == 0 )
2440 break;
2441
2442 nblimbs--;
2443
2444 bufsize = sizeof( mbedtls_mpi_uint ) << 3;
2445 }
2446
2447 bufsize--;
2448
2449 ei = (E->p[nblimbs] >> bufsize) & 1;
2450
2451 /*
2452 * skip leading 0s
2453 */
2454 if( ei == 0 && state == 0 )
2455 continue;
2456
2457 if( ei == 0 && state == 1 )
2458 {
2459 /*
2460 * out of window, square X
2461 */
Jerome Forissier3602df82021-07-28 10:24:04 +02002462 mpi_montmul( X, X, N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002463 continue;
2464 }
2465
2466 /*
2467 * add ei to current window
2468 */
2469 state = 2;
2470
2471 nbits++;
2472 wbits |= ( ei << ( wsize - nbits ) );
2473
2474 if( nbits == wsize )
2475 {
2476 /*
2477 * X = X^wsize R^-1 mod N
2478 */
2479 for( i = 0; i < wsize; i++ )
Jerome Forissier3602df82021-07-28 10:24:04 +02002480 mpi_montmul( X, X, N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002481
2482 /*
2483 * X = X * W[wbits] R^-1 mod N
2484 */
Jerome Forissier3602df82021-07-28 10:24:04 +02002485 MBEDTLS_MPI_CHK( mpi_select( &WW, W, (size_t) 1 << wsize, wbits ) );
2486 mpi_montmul( X, &WW, N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002487
2488 state--;
2489 nbits = 0;
2490 wbits = 0;
2491 }
2492 }
2493
2494 /*
2495 * process the remaining bits
2496 */
2497 for( i = 0; i < nbits; i++ )
2498 {
Jerome Forissier3602df82021-07-28 10:24:04 +02002499 mpi_montmul( X, X, N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002500
2501 wbits <<= 1;
2502
2503 if( ( wbits & ( one << wsize ) ) != 0 )
Jerome Forissier3602df82021-07-28 10:24:04 +02002504 mpi_montmul( X, &W[1], N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002505 }
2506
2507 /*
2508 * X = A^E * R * R^-1 mod N = A^E mod N
2509 */
Jerome Forissier3602df82021-07-28 10:24:04 +02002510 mpi_montred( X, N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002511
2512 if( neg && E->n != 0 && ( E->p[0] & 1 ) != 0 )
2513 {
2514 X->s = -1;
2515 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( X, N, X ) );
2516 }
2517
2518cleanup:
2519
Jerome Forissier3602df82021-07-28 10:24:04 +02002520 for( i = ( one << ( wsize - 1 ) ); i < ( one << wsize ); i++ )
2521 mbedtls_mpi_free( &W[i] );
Jens Wiklander817466c2018-05-22 13:49:31 +02002522
Jerome Forissier3602df82021-07-28 10:24:04 +02002523 mbedtls_mpi_free( &W[1] ); mbedtls_mpi_free( &T ); mbedtls_mpi_free( &Apos );
2524 mbedtls_mpi_free( &WW );
Jens Wiklander817466c2018-05-22 13:49:31 +02002525
2526 if( _RR == NULL || _RR->p == NULL )
2527 mbedtls_mpi_free( &RR );
2528
2529 return( ret );
2530}
2531
2532/*
2533 * Greatest common divisor: G = gcd(A, B) (HAC 14.54)
2534 */
2535int mbedtls_mpi_gcd( mbedtls_mpi *G, const mbedtls_mpi *A, const mbedtls_mpi *B )
2536{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02002537 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +02002538 size_t lz, lzt;
Jerome Forissier11fa71b2020-04-20 17:17:56 +02002539 mbedtls_mpi TA, TB;
Jens Wiklander817466c2018-05-22 13:49:31 +02002540
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002541 MPI_VALIDATE_RET( G != NULL );
2542 MPI_VALIDATE_RET( A != NULL );
2543 MPI_VALIDATE_RET( B != NULL );
2544
Jerome Forissier3602df82021-07-28 10:24:04 +02002545 mbedtls_mpi_init( &TA ); mbedtls_mpi_init( &TB );
Jens Wiklander817466c2018-05-22 13:49:31 +02002546
2547 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TA, A ) );
2548 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, B ) );
2549
2550 lz = mbedtls_mpi_lsb( &TA );
2551 lzt = mbedtls_mpi_lsb( &TB );
2552
Jerome Forissier3602df82021-07-28 10:24:04 +02002553 /* The loop below gives the correct result when A==0 but not when B==0.
2554 * So have a special case for B==0. Leverage the fact that we just
2555 * calculated the lsb and lsb(B)==0 iff B is odd or 0 to make the test
2556 * slightly more efficient than cmp_int(). */
2557 if( lzt == 0 && mbedtls_mpi_get_bit( &TB, 0 ) == 0 )
2558 {
2559 ret = mbedtls_mpi_copy( G, A );
2560 goto cleanup;
2561 }
2562
Jens Wiklander817466c2018-05-22 13:49:31 +02002563 if( lzt < lz )
2564 lz = lzt;
2565
Jens Wiklander817466c2018-05-22 13:49:31 +02002566 TA.s = TB.s = 1;
2567
Jerome Forissier3602df82021-07-28 10:24:04 +02002568 /* We mostly follow the procedure described in HAC 14.54, but with some
2569 * minor differences:
2570 * - Sequences of multiplications or divisions by 2 are grouped into a
2571 * single shift operation.
2572 * - The procedure in HAC assumes that 0 < TB <= TA.
2573 * - The condition TB <= TA is not actually necessary for correctness.
2574 * TA and TB have symmetric roles except for the loop termination
2575 * condition, and the shifts at the beginning of the loop body
2576 * remove any significance from the ordering of TA vs TB before
2577 * the shifts.
2578 * - If TA = 0, the loop goes through 0 iterations and the result is
2579 * correctly TB.
2580 * - The case TB = 0 was short-circuited above.
2581 *
2582 * For the correctness proof below, decompose the original values of
2583 * A and B as
2584 * A = sa * 2^a * A' with A'=0 or A' odd, and sa = +-1
2585 * B = sb * 2^b * B' with B'=0 or B' odd, and sb = +-1
2586 * Then gcd(A, B) = 2^{min(a,b)} * gcd(A',B'),
2587 * and gcd(A',B') is odd or 0.
2588 *
2589 * At the beginning, we have TA = |A| and TB = |B| so gcd(A,B) = gcd(TA,TB).
2590 * The code maintains the following invariant:
2591 * gcd(A,B) = 2^k * gcd(TA,TB) for some k (I)
2592 */
2593
2594 /* Proof that the loop terminates:
2595 * At each iteration, either the right-shift by 1 is made on a nonzero
2596 * value and the nonnegative integer bitlen(TA) + bitlen(TB) decreases
2597 * by at least 1, or the right-shift by 1 is made on zero and then
2598 * TA becomes 0 which ends the loop (TB cannot be 0 if it is right-shifted
2599 * since in that case TB is calculated from TB-TA with the condition TB>TA).
2600 */
Jens Wiklander817466c2018-05-22 13:49:31 +02002601 while( mbedtls_mpi_cmp_int( &TA, 0 ) != 0 )
2602 {
Jerome Forissier3602df82021-07-28 10:24:04 +02002603 /* Divisions by 2 preserve the invariant (I). */
Jens Wiklander817466c2018-05-22 13:49:31 +02002604 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TA, mbedtls_mpi_lsb( &TA ) ) );
2605 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TB, mbedtls_mpi_lsb( &TB ) ) );
2606
Jerome Forissier3602df82021-07-28 10:24:04 +02002607 /* Set either TA or TB to |TA-TB|/2. Since TA and TB are both odd,
2608 * TA-TB is even so the division by 2 has an integer result.
2609 * Invariant (I) is preserved since any odd divisor of both TA and TB
2610 * also divides |TA-TB|/2, and any odd divisor of both TA and |TA-TB|/2
2611 * also divides TB, and any odd divisior of both TB and |TA-TB|/2 also
2612 * divides TA.
2613 */
Jens Wiklander817466c2018-05-22 13:49:31 +02002614 if( mbedtls_mpi_cmp_mpi( &TA, &TB ) >= 0 )
2615 {
2616 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &TA, &TA, &TB ) );
2617 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TA, 1 ) );
2618 }
2619 else
2620 {
2621 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &TB, &TB, &TA ) );
2622 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TB, 1 ) );
2623 }
Jerome Forissier3602df82021-07-28 10:24:04 +02002624 /* Note that one of TA or TB is still odd. */
Jens Wiklander817466c2018-05-22 13:49:31 +02002625 }
2626
Jerome Forissier3602df82021-07-28 10:24:04 +02002627 /* By invariant (I), gcd(A,B) = 2^k * gcd(TA,TB) for some k.
2628 * At the loop exit, TA = 0, so gcd(TA,TB) = TB.
2629 * - If there was at least one loop iteration, then one of TA or TB is odd,
2630 * and TA = 0, so TB is odd and gcd(TA,TB) = gcd(A',B'). In this case,
2631 * lz = min(a,b) so gcd(A,B) = 2^lz * TB.
2632 * - If there was no loop iteration, then A was 0, and gcd(A,B) = B.
2633 * In this case, lz = 0 and B = TB so gcd(A,B) = B = 2^lz * TB as well.
2634 */
2635
Jens Wiklander817466c2018-05-22 13:49:31 +02002636 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &TB, lz ) );
2637 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( G, &TB ) );
2638
2639cleanup:
2640
Jerome Forissier11fa71b2020-04-20 17:17:56 +02002641 mbedtls_mpi_free( &TA ); mbedtls_mpi_free( &TB );
Jens Wiklander817466c2018-05-22 13:49:31 +02002642
2643 return( ret );
2644}
2645
Jerome Forissier3602df82021-07-28 10:24:04 +02002646/* Fill X with n_bytes random bytes.
2647 * X must already have room for those bytes.
2648 * The ordering of the bytes returned from the RNG is suitable for
2649 * deterministic ECDSA (see RFC 6979 §3.3 and mbedtls_mpi_random()).
2650 * The size and sign of X are unchanged.
2651 * n_bytes must not be 0.
2652 */
2653static int mpi_fill_random_internal(
2654 mbedtls_mpi *X, size_t n_bytes,
2655 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
2656{
2657 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2658 const size_t limbs = CHARS_TO_LIMBS( n_bytes );
2659 const size_t overhead = ( limbs * ciL ) - n_bytes;
2660
2661 if( X->n < limbs )
2662 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2663
2664 memset( X->p, 0, overhead );
2665 memset( (unsigned char *) X->p + limbs * ciL, 0, ( X->n - limbs ) * ciL );
2666 MBEDTLS_MPI_CHK( f_rng( p_rng, (unsigned char *) X->p + overhead, n_bytes ) );
2667 mpi_bigendian_to_host( X->p, limbs );
2668
2669cleanup:
2670 return( ret );
2671}
2672
Jens Wiklander817466c2018-05-22 13:49:31 +02002673/*
2674 * Fill X with size bytes of random.
2675 *
2676 * Use a temporary bytes representation to make sure the result is the same
2677 * regardless of the platform endianness (useful when f_rng is actually
2678 * deterministic, eg for tests).
2679 */
2680int mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size,
2681 int (*f_rng)(void *, unsigned char *, size_t),
2682 void *p_rng )
2683{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02002684 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jerome Forissier5b25c762020-04-07 11:18:49 +02002685 size_t const limbs = CHARS_TO_LIMBS( size );
Jerome Forissier5b25c762020-04-07 11:18:49 +02002686
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002687 MPI_VALIDATE_RET( X != NULL );
2688 MPI_VALIDATE_RET( f_rng != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02002689
Jerome Forissier5b25c762020-04-07 11:18:49 +02002690 /* Ensure that target MPI has exactly the necessary number of limbs */
Jerome Forissier3602df82021-07-28 10:24:04 +02002691 MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, limbs ) );
2692 if( size == 0 )
2693 return( 0 );
Jens Wiklander817466c2018-05-22 13:49:31 +02002694
Jerome Forissier3602df82021-07-28 10:24:04 +02002695 ret = mpi_fill_random_internal( X, size, f_rng, p_rng );
Jens Wiklander817466c2018-05-22 13:49:31 +02002696
2697cleanup:
2698 return( ret );
2699}
2700
Jerome Forissier3602df82021-07-28 10:24:04 +02002701int mbedtls_mpi_random( mbedtls_mpi *X,
2702 mbedtls_mpi_sint min,
2703 const mbedtls_mpi *N,
2704 int (*f_rng)(void *, unsigned char *, size_t),
2705 void *p_rng )
2706{
2707 int ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
2708 int count;
2709 unsigned lt_lower = 1, lt_upper = 0;
2710 size_t n_bits = mbedtls_mpi_bitlen( N );
2711 size_t n_bytes = ( n_bits + 7 ) / 8;
2712 mbedtls_mpi lower_bound;
2713
2714 if( min < 0 )
2715 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2716 if( mbedtls_mpi_cmp_int( N, min ) <= 0 )
2717 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2718
2719 /*
2720 * When min == 0, each try has at worst a probability 1/2 of failing
2721 * (the msb has a probability 1/2 of being 0, and then the result will
2722 * be < N), so after 30 tries failure probability is a most 2**(-30).
2723 *
2724 * When N is just below a power of 2, as is the case when generating
2725 * a random scalar on most elliptic curves, 1 try is enough with
2726 * overwhelming probability. When N is just above a power of 2,
2727 * as when generating a random scalar on secp224k1, each try has
2728 * a probability of failing that is almost 1/2.
2729 *
2730 * The probabilities are almost the same if min is nonzero but negligible
2731 * compared to N. This is always the case when N is crypto-sized, but
2732 * it's convenient to support small N for testing purposes. When N
2733 * is small, use a higher repeat count, otherwise the probability of
2734 * failure is macroscopic.
2735 */
2736 count = ( n_bytes > 4 ? 30 : 250 );
2737
2738 mbedtls_mpi_init( &lower_bound );
2739
2740 /* Ensure that target MPI has exactly the same number of limbs
2741 * as the upper bound, even if the upper bound has leading zeros.
2742 * This is necessary for the mbedtls_mpi_lt_mpi_ct() check. */
2743 MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, N->n ) );
2744 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &lower_bound, N->n ) );
2745 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &lower_bound, min ) );
2746
2747 /*
2748 * Match the procedure given in RFC 6979 §3.3 (deterministic ECDSA)
2749 * when f_rng is a suitably parametrized instance of HMAC_DRBG:
2750 * - use the same byte ordering;
2751 * - keep the leftmost n_bits bits of the generated octet string;
2752 * - try until result is in the desired range.
2753 * This also avoids any bias, which is especially important for ECDSA.
2754 */
2755 do
2756 {
2757 MBEDTLS_MPI_CHK( mpi_fill_random_internal( X, n_bytes, f_rng, p_rng ) );
2758 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( X, 8 * n_bytes - n_bits ) );
2759
2760 if( --count == 0 )
2761 {
2762 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2763 goto cleanup;
2764 }
2765
2766 MBEDTLS_MPI_CHK( mbedtls_mpi_lt_mpi_ct( X, &lower_bound, &lt_lower ) );
2767 MBEDTLS_MPI_CHK( mbedtls_mpi_lt_mpi_ct( X, N, &lt_upper ) );
2768 }
2769 while( lt_lower != 0 || lt_upper == 0 );
2770
2771cleanup:
2772 mbedtls_mpi_free( &lower_bound );
2773 return( ret );
2774}
2775
Jens Wiklander817466c2018-05-22 13:49:31 +02002776/*
2777 * Modular inverse: X = A^-1 mod N (HAC 14.61 / 14.64)
2778 */
2779int mbedtls_mpi_inv_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *N )
2780{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02002781 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +02002782 mbedtls_mpi G, TA, TU, U1, U2, TB, TV, V1, V2;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002783 MPI_VALIDATE_RET( X != NULL );
2784 MPI_VALIDATE_RET( A != NULL );
2785 MPI_VALIDATE_RET( N != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02002786
2787 if( mbedtls_mpi_cmp_int( N, 1 ) <= 0 )
2788 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2789
Jerome Forissier3602df82021-07-28 10:24:04 +02002790 mbedtls_mpi_init( &TA ); mbedtls_mpi_init( &TU ); mbedtls_mpi_init( &U1 ); mbedtls_mpi_init( &U2 );
2791 mbedtls_mpi_init( &G ); mbedtls_mpi_init( &TB ); mbedtls_mpi_init( &TV );
2792 mbedtls_mpi_init( &V1 ); mbedtls_mpi_init( &V2 );
Jens Wiklander817466c2018-05-22 13:49:31 +02002793
2794 MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, A, N ) );
2795
2796 if( mbedtls_mpi_cmp_int( &G, 1 ) != 0 )
2797 {
2798 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2799 goto cleanup;
2800 }
2801
2802 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &TA, A, N ) );
2803 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TU, &TA ) );
2804 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, N ) );
2805 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TV, N ) );
2806
2807 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &U1, 1 ) );
2808 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &U2, 0 ) );
2809 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &V1, 0 ) );
2810 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &V2, 1 ) );
2811
2812 do
2813 {
2814 while( ( TU.p[0] & 1 ) == 0 )
2815 {
2816 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TU, 1 ) );
2817
2818 if( ( U1.p[0] & 1 ) != 0 || ( U2.p[0] & 1 ) != 0 )
2819 {
2820 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &U1, &U1, &TB ) );
2821 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U2, &U2, &TA ) );
2822 }
2823
2824 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &U1, 1 ) );
2825 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &U2, 1 ) );
2826 }
2827
2828 while( ( TV.p[0] & 1 ) == 0 )
2829 {
2830 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TV, 1 ) );
2831
2832 if( ( V1.p[0] & 1 ) != 0 || ( V2.p[0] & 1 ) != 0 )
2833 {
2834 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &V1, &V1, &TB ) );
2835 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V2, &V2, &TA ) );
2836 }
2837
2838 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &V1, 1 ) );
2839 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &V2, 1 ) );
2840 }
2841
2842 if( mbedtls_mpi_cmp_mpi( &TU, &TV ) >= 0 )
2843 {
2844 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &TU, &TU, &TV ) );
2845 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U1, &U1, &V1 ) );
2846 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U2, &U2, &V2 ) );
2847 }
2848 else
2849 {
2850 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &TV, &TV, &TU ) );
2851 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V1, &V1, &U1 ) );
2852 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V2, &V2, &U2 ) );
2853 }
2854 }
2855 while( mbedtls_mpi_cmp_int( &TU, 0 ) != 0 );
2856
2857 while( mbedtls_mpi_cmp_int( &V1, 0 ) < 0 )
2858 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &V1, &V1, N ) );
2859
2860 while( mbedtls_mpi_cmp_mpi( &V1, N ) >= 0 )
2861 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V1, &V1, N ) );
2862
2863 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, &V1 ) );
2864
2865cleanup:
2866
2867 mbedtls_mpi_free( &TA ); mbedtls_mpi_free( &TU ); mbedtls_mpi_free( &U1 ); mbedtls_mpi_free( &U2 );
2868 mbedtls_mpi_free( &G ); mbedtls_mpi_free( &TB ); mbedtls_mpi_free( &TV );
2869 mbedtls_mpi_free( &V1 ); mbedtls_mpi_free( &V2 );
2870
2871 return( ret );
2872}
2873
2874#if defined(MBEDTLS_GENPRIME)
2875
2876static const int small_prime[] =
2877{
2878 3, 5, 7, 11, 13, 17, 19, 23,
2879 29, 31, 37, 41, 43, 47, 53, 59,
2880 61, 67, 71, 73, 79, 83, 89, 97,
2881 101, 103, 107, 109, 113, 127, 131, 137,
2882 139, 149, 151, 157, 163, 167, 173, 179,
2883 181, 191, 193, 197, 199, 211, 223, 227,
2884 229, 233, 239, 241, 251, 257, 263, 269,
2885 271, 277, 281, 283, 293, 307, 311, 313,
2886 317, 331, 337, 347, 349, 353, 359, 367,
2887 373, 379, 383, 389, 397, 401, 409, 419,
2888 421, 431, 433, 439, 443, 449, 457, 461,
2889 463, 467, 479, 487, 491, 499, 503, 509,
2890 521, 523, 541, 547, 557, 563, 569, 571,
2891 577, 587, 593, 599, 601, 607, 613, 617,
2892 619, 631, 641, 643, 647, 653, 659, 661,
2893 673, 677, 683, 691, 701, 709, 719, 727,
2894 733, 739, 743, 751, 757, 761, 769, 773,
2895 787, 797, 809, 811, 821, 823, 827, 829,
2896 839, 853, 857, 859, 863, 877, 881, 883,
2897 887, 907, 911, 919, 929, 937, 941, 947,
2898 953, 967, 971, 977, 983, 991, 997, -103
2899};
2900
2901/*
2902 * Small divisors test (X must be positive)
2903 *
2904 * Return values:
2905 * 0: no small factor (possible prime, more tests needed)
2906 * 1: certain prime
2907 * MBEDTLS_ERR_MPI_NOT_ACCEPTABLE: certain non-prime
2908 * other negative: error
2909 */
2910static int mpi_check_small_factors( const mbedtls_mpi *X )
2911{
2912 int ret = 0;
2913 size_t i;
2914 mbedtls_mpi_uint r;
2915
2916 if( ( X->p[0] & 1 ) == 0 )
2917 return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
2918
2919 for( i = 0; small_prime[i] > 0; i++ )
2920 {
2921 if( mbedtls_mpi_cmp_int( X, small_prime[i] ) <= 0 )
2922 return( 1 );
2923
2924 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, small_prime[i] ) );
2925
2926 if( r == 0 )
2927 return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
2928 }
2929
2930cleanup:
2931 return( ret );
2932}
2933
2934/*
2935 * Miller-Rabin pseudo-primality test (HAC 4.24)
2936 */
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002937static int mpi_miller_rabin( const mbedtls_mpi *X, size_t rounds,
Jens Wiklander817466c2018-05-22 13:49:31 +02002938 int (*f_rng)(void *, unsigned char *, size_t),
2939 void *p_rng )
2940{
2941 int ret, count;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002942 size_t i, j, k, s;
Jens Wiklander817466c2018-05-22 13:49:31 +02002943 mbedtls_mpi W, R, T, A, RR;
2944
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002945 MPI_VALIDATE_RET( X != NULL );
2946 MPI_VALIDATE_RET( f_rng != NULL );
2947
Jerome Forissier3602df82021-07-28 10:24:04 +02002948 mbedtls_mpi_init( &W ); mbedtls_mpi_init( &R );
2949 mbedtls_mpi_init( &T ); mbedtls_mpi_init( &A );
2950 mbedtls_mpi_init( &RR );
Jens Wiklander817466c2018-05-22 13:49:31 +02002951
2952 /*
2953 * W = |X| - 1
2954 * R = W >> lsb( W )
2955 */
2956 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &W, X, 1 ) );
2957 s = mbedtls_mpi_lsb( &W );
2958 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R, &W ) );
2959 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &R, s ) );
2960
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002961 for( i = 0; i < rounds; i++ )
Jens Wiklander817466c2018-05-22 13:49:31 +02002962 {
2963 /*
2964 * pick a random A, 1 < A < |X| - 1
2965 */
Jens Wiklander817466c2018-05-22 13:49:31 +02002966 count = 0;
2967 do {
2968 MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &A, X->n * ciL, f_rng, p_rng ) );
2969
2970 j = mbedtls_mpi_bitlen( &A );
2971 k = mbedtls_mpi_bitlen( &W );
2972 if (j > k) {
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002973 A.p[A.n - 1] &= ( (mbedtls_mpi_uint) 1 << ( k - ( A.n - 1 ) * biL - 1 ) ) - 1;
Jens Wiklander817466c2018-05-22 13:49:31 +02002974 }
2975
Jerome Forissier3602df82021-07-28 10:24:04 +02002976 if (count++ > 30) {
Jens Wiklander336e3292019-01-17 11:14:38 +01002977 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2978 goto cleanup;
Jens Wiklander817466c2018-05-22 13:49:31 +02002979 }
2980
2981 } while ( mbedtls_mpi_cmp_mpi( &A, &W ) >= 0 ||
2982 mbedtls_mpi_cmp_int( &A, 1 ) <= 0 );
2983
2984 /*
2985 * A = A^R mod |X|
2986 */
2987 MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &A, &A, &R, X, &RR ) );
2988
2989 if( mbedtls_mpi_cmp_mpi( &A, &W ) == 0 ||
2990 mbedtls_mpi_cmp_int( &A, 1 ) == 0 )
2991 continue;
2992
2993 j = 1;
2994 while( j < s && mbedtls_mpi_cmp_mpi( &A, &W ) != 0 )
2995 {
2996 /*
2997 * A = A * A mod |X|
2998 */
2999 MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &A, &A ) );
3000 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &A, &T, X ) );
3001
3002 if( mbedtls_mpi_cmp_int( &A, 1 ) == 0 )
3003 break;
3004
3005 j++;
3006 }
3007
3008 /*
3009 * not prime if A != |X| - 1 or A == 1
3010 */
3011 if( mbedtls_mpi_cmp_mpi( &A, &W ) != 0 ||
3012 mbedtls_mpi_cmp_int( &A, 1 ) == 0 )
3013 {
3014 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
3015 break;
3016 }
3017 }
3018
3019cleanup:
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003020 mbedtls_mpi_free( &W ); mbedtls_mpi_free( &R );
3021 mbedtls_mpi_free( &T ); mbedtls_mpi_free( &A );
Jens Wiklander817466c2018-05-22 13:49:31 +02003022 mbedtls_mpi_free( &RR );
3023
3024 return( ret );
3025}
3026
3027/*
3028 * Pseudo-primality test: small factors, then Miller-Rabin
3029 */
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003030int mbedtls_mpi_is_prime_ext( const mbedtls_mpi *X, int rounds,
3031 int (*f_rng)(void *, unsigned char *, size_t),
3032 void *p_rng )
Jens Wiklander817466c2018-05-22 13:49:31 +02003033{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02003034 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +02003035 mbedtls_mpi XX;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003036 MPI_VALIDATE_RET( X != NULL );
3037 MPI_VALIDATE_RET( f_rng != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02003038
3039 XX.s = 1;
3040 XX.n = X->n;
3041 XX.p = X->p;
3042
3043 if( mbedtls_mpi_cmp_int( &XX, 0 ) == 0 ||
3044 mbedtls_mpi_cmp_int( &XX, 1 ) == 0 )
3045 return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
3046
3047 if( mbedtls_mpi_cmp_int( &XX, 2 ) == 0 )
3048 return( 0 );
3049
3050 if( ( ret = mpi_check_small_factors( &XX ) ) != 0 )
3051 {
3052 if( ret == 1 )
3053 return( 0 );
3054
3055 return( ret );
3056 }
3057
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003058 return( mpi_miller_rabin( &XX, rounds, f_rng, p_rng ) );
Jens Wiklander817466c2018-05-22 13:49:31 +02003059}
3060
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003061#if !defined(MBEDTLS_DEPRECATED_REMOVED)
3062/*
3063 * Pseudo-primality test, error probability 2^-80
3064 */
3065int mbedtls_mpi_is_prime( const mbedtls_mpi *X,
3066 int (*f_rng)(void *, unsigned char *, size_t),
3067 void *p_rng )
3068{
3069 MPI_VALIDATE_RET( X != NULL );
3070 MPI_VALIDATE_RET( f_rng != NULL );
3071
3072 /*
3073 * In the past our key generation aimed for an error rate of at most
3074 * 2^-80. Since this function is deprecated, aim for the same certainty
3075 * here as well.
3076 */
3077 return( mbedtls_mpi_is_prime_ext( X, 40, f_rng, p_rng ) );
3078}
3079#endif
3080
Jens Wiklander817466c2018-05-22 13:49:31 +02003081/*
3082 * Prime number generation
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003083 *
3084 * To generate an RSA key in a way recommended by FIPS 186-4, both primes must
3085 * be either 1024 bits or 1536 bits long, and flags must contain
3086 * MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR.
Jens Wiklander817466c2018-05-22 13:49:31 +02003087 */
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003088int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int flags,
Jens Wiklander817466c2018-05-22 13:49:31 +02003089 int (*f_rng)(void *, unsigned char *, size_t),
3090 void *p_rng )
3091{
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003092#ifdef MBEDTLS_HAVE_INT64
3093// ceil(2^63.5)
3094#define CEIL_MAXUINT_DIV_SQRT2 0xb504f333f9de6485ULL
3095#else
3096// ceil(2^31.5)
3097#define CEIL_MAXUINT_DIV_SQRT2 0xb504f334U
3098#endif
3099 int ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
Jens Wiklander817466c2018-05-22 13:49:31 +02003100 size_t k, n;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003101 int rounds;
Jens Wiklander817466c2018-05-22 13:49:31 +02003102 mbedtls_mpi_uint r;
3103 mbedtls_mpi Y;
3104
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003105 MPI_VALIDATE_RET( X != NULL );
3106 MPI_VALIDATE_RET( f_rng != NULL );
3107
Jens Wiklander817466c2018-05-22 13:49:31 +02003108 if( nbits < 3 || nbits > MBEDTLS_MPI_MAX_BITS )
3109 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
3110
Jerome Forissier3602df82021-07-28 10:24:04 +02003111 mbedtls_mpi_init( &Y );
Jens Wiklander817466c2018-05-22 13:49:31 +02003112
3113 n = BITS_TO_LIMBS( nbits );
3114
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003115 if( ( flags & MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR ) == 0 )
Jens Wiklander817466c2018-05-22 13:49:31 +02003116 {
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003117 /*
3118 * 2^-80 error probability, number of rounds chosen per HAC, table 4.4
3119 */
3120 rounds = ( ( nbits >= 1300 ) ? 2 : ( nbits >= 850 ) ? 3 :
3121 ( nbits >= 650 ) ? 4 : ( nbits >= 350 ) ? 8 :
3122 ( nbits >= 250 ) ? 12 : ( nbits >= 150 ) ? 18 : 27 );
Jens Wiklander817466c2018-05-22 13:49:31 +02003123 }
3124 else
3125 {
3126 /*
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003127 * 2^-100 error probability, number of rounds computed based on HAC,
3128 * fact 4.48
Jens Wiklander817466c2018-05-22 13:49:31 +02003129 */
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003130 rounds = ( ( nbits >= 1450 ) ? 4 : ( nbits >= 1150 ) ? 5 :
3131 ( nbits >= 1000 ) ? 6 : ( nbits >= 850 ) ? 7 :
3132 ( nbits >= 750 ) ? 8 : ( nbits >= 500 ) ? 13 :
3133 ( nbits >= 250 ) ? 28 : ( nbits >= 150 ) ? 40 : 51 );
3134 }
Jens Wiklander817466c2018-05-22 13:49:31 +02003135
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003136 while( 1 )
3137 {
3138 MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( X, n * ciL, f_rng, p_rng ) );
3139 /* make sure generated number is at least (nbits-1)+0.5 bits (FIPS 186-4 §B.3.3 steps 4.4, 5.5) */
3140 if( X->p[n-1] < CEIL_MAXUINT_DIV_SQRT2 ) continue;
Jens Wiklander817466c2018-05-22 13:49:31 +02003141
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003142 k = n * biL;
3143 if( k > nbits ) MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( X, k - nbits ) );
3144 X->p[0] |= 1;
Jens Wiklander817466c2018-05-22 13:49:31 +02003145
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003146 if( ( flags & MBEDTLS_MPI_GEN_PRIME_FLAG_DH ) == 0 )
Jens Wiklander817466c2018-05-22 13:49:31 +02003147 {
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003148 ret = mbedtls_mpi_is_prime_ext( X, rounds, f_rng, p_rng );
Jens Wiklander817466c2018-05-22 13:49:31 +02003149
3150 if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
3151 goto cleanup;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003152 }
3153 else
3154 {
Jens Wiklander817466c2018-05-22 13:49:31 +02003155 /*
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003156 * An necessary condition for Y and X = 2Y + 1 to be prime
3157 * is X = 2 mod 3 (which is equivalent to Y = 2 mod 3).
3158 * Make sure it is satisfied, while keeping X = 3 mod 4
Jens Wiklander817466c2018-05-22 13:49:31 +02003159 */
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003160
3161 X->p[0] |= 2;
3162
3163 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, 3 ) );
3164 if( r == 0 )
3165 MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 8 ) );
3166 else if( r == 1 )
3167 MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 4 ) );
3168
3169 /* Set Y = (X-1) / 2, which is X / 2 because X is odd */
3170 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Y, X ) );
3171 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &Y, 1 ) );
3172
3173 while( 1 )
3174 {
3175 /*
3176 * First, check small factors for X and Y
3177 * before doing Miller-Rabin on any of them
3178 */
3179 if( ( ret = mpi_check_small_factors( X ) ) == 0 &&
3180 ( ret = mpi_check_small_factors( &Y ) ) == 0 &&
3181 ( ret = mpi_miller_rabin( X, rounds, f_rng, p_rng ) )
3182 == 0 &&
3183 ( ret = mpi_miller_rabin( &Y, rounds, f_rng, p_rng ) )
3184 == 0 )
3185 goto cleanup;
3186
3187 if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
3188 goto cleanup;
3189
3190 /*
3191 * Next candidates. We want to preserve Y = (X-1) / 2 and
3192 * Y = 1 mod 2 and Y = 2 mod 3 (eq X = 3 mod 4 and X = 2 mod 3)
3193 * so up Y by 6 and X by 12.
3194 */
3195 MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 12 ) );
3196 MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &Y, &Y, 6 ) );
3197 }
Jens Wiklander817466c2018-05-22 13:49:31 +02003198 }
3199 }
3200
3201cleanup:
3202
3203 mbedtls_mpi_free( &Y );
3204
3205 return( ret );
3206}
3207
3208#endif /* MBEDTLS_GENPRIME */
3209
3210#if defined(MBEDTLS_SELF_TEST)
3211
3212#define GCD_PAIR_COUNT 3
3213
3214static const int gcd_pairs[GCD_PAIR_COUNT][3] =
3215{
3216 { 693, 609, 21 },
3217 { 1764, 868, 28 },
3218 { 768454923, 542167814, 1 }
3219};
3220
3221/*
3222 * Checkup routine
3223 */
3224int mbedtls_mpi_self_test( int verbose )
3225{
3226 int ret, i;
3227 mbedtls_mpi A, E, N, X, Y, U, V;
3228
Jerome Forissier3602df82021-07-28 10:24:04 +02003229 mbedtls_mpi_init( &A ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &N ); mbedtls_mpi_init( &X );
3230 mbedtls_mpi_init( &Y ); mbedtls_mpi_init( &U ); mbedtls_mpi_init( &V );
Jens Wiklander817466c2018-05-22 13:49:31 +02003231
3232 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &A, 16,
3233 "EFE021C2645FD1DC586E69184AF4A31E" \
3234 "D5F53E93B5F123FA41680867BA110131" \
3235 "944FE7952E2517337780CB0DB80E61AA" \
3236 "E7C8DDC6C5C6AADEB34EB38A2F40D5E6" ) );
3237
3238 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &E, 16,
3239 "B2E7EFD37075B9F03FF989C7C5051C20" \
3240 "34D2A323810251127E7BF8625A4F49A5" \
3241 "F3E27F4DA8BD59C47D6DAABA4C8127BD" \
3242 "5B5C25763222FEFCCFC38B832366C29E" ) );
3243
3244 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &N, 16,
3245 "0066A198186C18C10B2F5ED9B522752A" \
3246 "9830B69916E535C8F047518A889A43A5" \
3247 "94B6BED27A168D31D4A52F88925AA8F5" ) );
3248
3249 MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &X, &A, &N ) );
3250
3251 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
3252 "602AB7ECA597A3D6B56FF9829A5E8B85" \
3253 "9E857EA95A03512E2BAE7391688D264A" \
3254 "A5663B0341DB9CCFD2C4C5F421FEC814" \
3255 "8001B72E848A38CAE1C65F78E56ABDEF" \
3256 "E12D3C039B8A02D6BE593F0BBBDA56F1" \
3257 "ECF677152EF804370C1A305CAF3B5BF1" \
3258 "30879B56C61DE584A0F53A2447A51E" ) );
3259
3260 if( verbose != 0 )
3261 mbedtls_printf( " MPI test #1 (mul_mpi): " );
3262
3263 if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 )
3264 {
3265 if( verbose != 0 )
3266 mbedtls_printf( "failed\n" );
3267
3268 ret = 1;
3269 goto cleanup;
3270 }
3271
3272 if( verbose != 0 )
3273 mbedtls_printf( "passed\n" );
3274
3275 MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &X, &Y, &A, &N ) );
3276
3277 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
3278 "256567336059E52CAE22925474705F39A94" ) );
3279
3280 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &V, 16,
3281 "6613F26162223DF488E9CD48CC132C7A" \
3282 "0AC93C701B001B092E4E5B9F73BCD27B" \
3283 "9EE50D0657C77F374E903CDFA4C642" ) );
3284
3285 if( verbose != 0 )
3286 mbedtls_printf( " MPI test #2 (div_mpi): " );
3287
3288 if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 ||
3289 mbedtls_mpi_cmp_mpi( &Y, &V ) != 0 )
3290 {
3291 if( verbose != 0 )
3292 mbedtls_printf( "failed\n" );
3293
3294 ret = 1;
3295 goto cleanup;
3296 }
3297
3298 if( verbose != 0 )
3299 mbedtls_printf( "passed\n" );
3300
3301 MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &X, &A, &E, &N, NULL ) );
3302
3303 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
3304 "36E139AEA55215609D2816998ED020BB" \
3305 "BD96C37890F65171D948E9BC7CBAA4D9" \
3306 "325D24D6A3C12710F10A09FA08AB87" ) );
3307
3308 if( verbose != 0 )
3309 mbedtls_printf( " MPI test #3 (exp_mod): " );
3310
3311 if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 )
3312 {
3313 if( verbose != 0 )
3314 mbedtls_printf( "failed\n" );
3315
3316 ret = 1;
3317 goto cleanup;
3318 }
3319
3320 if( verbose != 0 )
3321 mbedtls_printf( "passed\n" );
3322
3323 MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &X, &A, &N ) );
3324
3325 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
3326 "003A0AAEDD7E784FC07D8F9EC6E3BFD5" \
3327 "C3DBA76456363A10869622EAC2DD84EC" \
3328 "C5B8A74DAC4D09E03B5E0BE779F2DF61" ) );
3329
3330 if( verbose != 0 )
3331 mbedtls_printf( " MPI test #4 (inv_mod): " );
3332
3333 if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 )
3334 {
3335 if( verbose != 0 )
3336 mbedtls_printf( "failed\n" );
3337
3338 ret = 1;
3339 goto cleanup;
3340 }
3341
3342 if( verbose != 0 )
3343 mbedtls_printf( "passed\n" );
3344
3345 if( verbose != 0 )
3346 mbedtls_printf( " MPI test #5 (simple gcd): " );
3347
3348 for( i = 0; i < GCD_PAIR_COUNT; i++ )
3349 {
3350 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &X, gcd_pairs[i][0] ) );
3351 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &Y, gcd_pairs[i][1] ) );
3352
3353 MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &A, &X, &Y ) );
3354
3355 if( mbedtls_mpi_cmp_int( &A, gcd_pairs[i][2] ) != 0 )
3356 {
3357 if( verbose != 0 )
3358 mbedtls_printf( "failed at %d\n", i );
3359
3360 ret = 1;
3361 goto cleanup;
3362 }
3363 }
3364
3365 if( verbose != 0 )
3366 mbedtls_printf( "passed\n" );
3367
3368cleanup:
3369
3370 if( ret != 0 && verbose != 0 )
Jerome Forissier3602df82021-07-28 10:24:04 +02003371 mbedtls_printf( "Unexpected error, return code = %08X\n", (unsigned int) ret );
Jens Wiklander817466c2018-05-22 13:49:31 +02003372
3373 mbedtls_mpi_free( &A ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &N ); mbedtls_mpi_free( &X );
3374 mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &U ); mbedtls_mpi_free( &V );
3375
3376 if( verbose != 0 )
3377 mbedtls_printf( "\n" );
3378
3379 return( ret );
3380}
3381
3382#endif /* MBEDTLS_SELF_TEST */
3383
3384#endif /* MBEDTLS_BIGNUM_C */