blob: 9e84da591946ddbdc29b3b7c836b352582613236 [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
Jens Wiklander3fbd8662018-11-07 08:11:29 +01002144void mbedtls_mpi_montg_init( mbedtls_mpi_uint *mm, const mbedtls_mpi *N )
2145{
2146 mpi_montg_init( mm, N );
2147}
2148
Jerome Forissier3602df82021-07-28 10:24:04 +02002149/** Montgomery multiplication: A = A * B * R^-1 mod N (HAC 14.36)
2150 *
2151 * \param[in,out] A One of the numbers to multiply.
2152 * It must have at least as many limbs as N
2153 * (A->n >= N->n), and any limbs beyond n are ignored.
2154 * On successful completion, A contains the result of
2155 * the multiplication A * B * R^-1 mod N where
2156 * R = (2^ciL)^n.
2157 * \param[in] B One of the numbers to multiply.
2158 * It must be nonzero and must not have more limbs than N
2159 * (B->n <= N->n).
2160 * \param[in] N The modulo. N must be odd.
2161 * \param mm The value calculated by `mpi_montg_init(&mm, N)`.
2162 * This is -N^-1 mod 2^ciL.
2163 * \param[in,out] T A bignum for temporary storage.
2164 * It must be at least twice the limb size of N plus 2
2165 * (T->n >= 2 * (N->n + 1)).
2166 * Its initial content is unused and
2167 * its final content is indeterminate.
2168 * Note that unlike the usual convention in the library
2169 * for `const mbedtls_mpi*`, the content of T can change.
Jens Wiklander817466c2018-05-22 13:49:31 +02002170 */
Jerome Forissier3602df82021-07-28 10:24:04 +02002171static 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 +02002172 const mbedtls_mpi *T )
2173{
2174 size_t i, n, m;
2175 mbedtls_mpi_uint u0, u1, *d;
2176
Jens Wiklander817466c2018-05-22 13:49:31 +02002177 memset( T->p, 0, T->n * ciL );
2178
2179 d = T->p;
2180 n = N->n;
2181 m = ( B->n < n ) ? B->n : n;
2182
2183 for( i = 0; i < n; i++ )
2184 {
2185 /*
2186 * T = (T + u0*B + u1*N) / 2^biL
2187 */
2188 u0 = A->p[i];
2189 u1 = ( d[0] + u0 * B->p[0] ) * mm;
2190
2191 mpi_mul_hlp( m, B->p, d, u0 );
2192 mpi_mul_hlp( n, N->p, d, u1 );
2193
2194 *d++ = u0; d[n + 1] = 0;
2195 }
2196
Jerome Forissier3602df82021-07-28 10:24:04 +02002197 /* At this point, d is either the desired result or the desired result
2198 * plus N. We now potentially subtract N, avoiding leaking whether the
2199 * subtraction is performed through side channels. */
Jens Wiklander817466c2018-05-22 13:49:31 +02002200
Jerome Forissier3602df82021-07-28 10:24:04 +02002201 /* Copy the n least significant limbs of d to A, so that
2202 * A = d if d < N (recall that N has n limbs). */
2203 memcpy( A->p, d, n * ciL );
2204 /* If d >= N then we want to set A to d - N. To prevent timing attacks,
2205 * do the calculation without using conditional tests. */
2206 /* Set d to d0 + (2^biL)^n - N where d0 is the current value of d. */
2207 d[n] += 1;
2208 d[n] -= mpi_sub_hlp( n, d, d, N->p );
2209 /* If d0 < N then d < (2^biL)^n
2210 * so d[n] == 0 and we want to keep A as it is.
2211 * If d0 >= N then d >= (2^biL)^n, and d <= (2^biL)^n + N < 2 * (2^biL)^n
2212 * so d[n] == 1 and we want to set A to the result of the subtraction
2213 * which is d - (2^biL)^n, i.e. the n least significant limbs of d.
2214 * This exactly corresponds to a conditional assignment. */
2215 mpi_safe_cond_assign( n, A->p, d, (unsigned char) d[n] );
Jens Wiklander817466c2018-05-22 13:49:31 +02002216}
2217
Jens Wiklander3fbd8662018-11-07 08:11:29 +01002218void mbedtls_mpi_montmul( mbedtls_mpi *A, const mbedtls_mpi *B, const mbedtls_mpi *N, mbedtls_mpi_uint mm,
2219 const mbedtls_mpi *T )
2220{
2221 mpi_montmul( A, B, N, mm, T);
2222}
2223
Jens Wiklander817466c2018-05-22 13:49:31 +02002224/*
2225 * Montgomery reduction: A = A * R^-1 mod N
Jerome Forissier3602df82021-07-28 10:24:04 +02002226 *
2227 * See mpi_montmul() regarding constraints and guarantees on the parameters.
Jens Wiklander817466c2018-05-22 13:49:31 +02002228 */
Jerome Forissier3602df82021-07-28 10:24:04 +02002229static void mpi_montred( mbedtls_mpi *A, const mbedtls_mpi *N,
2230 mbedtls_mpi_uint mm, const mbedtls_mpi *T )
Jens Wiklander817466c2018-05-22 13:49:31 +02002231{
2232 mbedtls_mpi_uint z = 1;
2233 mbedtls_mpi U;
2234
2235 U.n = U.s = (int) z;
2236 U.p = &z;
2237
Jerome Forissier3602df82021-07-28 10:24:04 +02002238 mpi_montmul( A, &U, N, mm, T );
2239}
2240
Jens Wiklander3fbd8662018-11-07 08:11:29 +01002241void mbedtls_mpi_montred( mbedtls_mpi *A, const mbedtls_mpi *N,
2242 mbedtls_mpi_uint mm, const mbedtls_mpi *T )
2243{
2244 mpi_montred( A, N, mm, T );
2245}
2246
Jerome Forissier3602df82021-07-28 10:24:04 +02002247/*
2248 * Constant-flow boolean "equal" comparison:
2249 * return x == y
2250 *
2251 * This function can be used to write constant-time code by replacing branches
2252 * with bit operations - it can be used in conjunction with
2253 * mbedtls_ssl_cf_mask_from_bit().
2254 *
2255 * This function is implemented without using comparison operators, as those
2256 * might be translated to branches by some compilers on some platforms.
2257 */
2258static size_t mbedtls_mpi_cf_bool_eq( size_t x, size_t y )
2259{
2260 /* diff = 0 if x == y, non-zero otherwise */
2261 const size_t diff = x ^ y;
2262
2263 /* MSVC has a warning about unary minus on unsigned integer types,
2264 * but this is well-defined and precisely what we want to do here. */
2265#if defined(_MSC_VER)
2266#pragma warning( push )
2267#pragma warning( disable : 4146 )
2268#endif
2269
2270 /* diff_msb's most significant bit is equal to x != y */
2271 const size_t diff_msb = ( diff | (size_t) -diff );
2272
2273#if defined(_MSC_VER)
2274#pragma warning( pop )
2275#endif
2276
2277 /* diff1 = (x != y) ? 1 : 0 */
2278 const size_t diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 );
2279
2280 return( 1 ^ diff1 );
2281}
2282
2283/**
2284 * Select an MPI from a table without leaking the index.
2285 *
2286 * This is functionally equivalent to mbedtls_mpi_copy(R, T[idx]) except it
2287 * reads the entire table in order to avoid leaking the value of idx to an
2288 * attacker able to observe memory access patterns.
2289 *
2290 * \param[out] R Where to write the selected MPI.
2291 * \param[in] T The table to read from.
2292 * \param[in] T_size The number of elements in the table.
2293 * \param[in] idx The index of the element to select;
2294 * this must satisfy 0 <= idx < T_size.
2295 *
2296 * \return \c 0 on success, or a negative error code.
2297 */
2298static int mpi_select( mbedtls_mpi *R, const mbedtls_mpi *T, size_t T_size, size_t idx )
2299{
2300 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2301
2302 for( size_t i = 0; i < T_size; i++ )
2303 {
2304 MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( R, &T[i],
2305 (unsigned char) mbedtls_mpi_cf_bool_eq( i, idx ) ) );
2306 }
2307
2308cleanup:
2309 return( ret );
Jens Wiklander817466c2018-05-22 13:49:31 +02002310}
2311
2312/*
2313 * Sliding-window exponentiation: X = A^E mod N (HAC 14.85)
2314 */
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002315int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A,
2316 const mbedtls_mpi *E, const mbedtls_mpi *N,
2317 mbedtls_mpi *_RR )
Jens Wiklander817466c2018-05-22 13:49:31 +02002318{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02002319 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +02002320 size_t wbits, wsize, one = 1;
2321 size_t i, j, nblimbs;
2322 size_t bufsize, nbits;
2323 mbedtls_mpi_uint ei, mm, state;
Jerome Forissier3602df82021-07-28 10:24:04 +02002324 mbedtls_mpi RR, T, W[ 1 << MBEDTLS_MPI_WINDOW_SIZE ], WW, Apos;
Jens Wiklander817466c2018-05-22 13:49:31 +02002325 int neg;
2326
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002327 MPI_VALIDATE_RET( X != NULL );
2328 MPI_VALIDATE_RET( A != NULL );
2329 MPI_VALIDATE_RET( E != NULL );
2330 MPI_VALIDATE_RET( N != NULL );
2331
2332 if( mbedtls_mpi_cmp_int( N, 0 ) <= 0 || ( N->p[0] & 1 ) == 0 )
Jens Wiklander817466c2018-05-22 13:49:31 +02002333 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2334
2335 if( mbedtls_mpi_cmp_int( E, 0 ) < 0 )
2336 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2337
Jerome Forissier3602df82021-07-28 10:24:04 +02002338 if( mbedtls_mpi_bitlen( E ) > MBEDTLS_MPI_MAX_BITS ||
2339 mbedtls_mpi_bitlen( N ) > MBEDTLS_MPI_MAX_BITS )
2340 return ( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2341
Jens Wiklander817466c2018-05-22 13:49:31 +02002342 /*
2343 * Init temps and window size
2344 */
Jerome Forissier3602df82021-07-28 10:24:04 +02002345 mpi_montg_init( &mm, N );
2346 mbedtls_mpi_init( &RR ); mbedtls_mpi_init( &T );
2347 mbedtls_mpi_init( &Apos );
2348 mbedtls_mpi_init( &WW );
2349 memset( W, 0, sizeof( W ) );
Jens Wiklander817466c2018-05-22 13:49:31 +02002350
2351 i = mbedtls_mpi_bitlen( E );
2352
2353 wsize = ( i > 671 ) ? 6 : ( i > 239 ) ? 5 :
2354 ( i > 79 ) ? 4 : ( i > 23 ) ? 3 : 1;
2355
Jerome Forissier5b25c762020-04-07 11:18:49 +02002356#if( MBEDTLS_MPI_WINDOW_SIZE < 6 )
Jens Wiklander817466c2018-05-22 13:49:31 +02002357 if( wsize > MBEDTLS_MPI_WINDOW_SIZE )
2358 wsize = MBEDTLS_MPI_WINDOW_SIZE;
Jerome Forissier5b25c762020-04-07 11:18:49 +02002359#endif
Jens Wiklander817466c2018-05-22 13:49:31 +02002360
2361 j = N->n + 1;
Jerome Forissier3602df82021-07-28 10:24:04 +02002362 /* All W[i] and X must have at least N->n limbs for the mpi_montmul()
2363 * and mpi_montred() calls later. Here we ensure that W[1] and X are
2364 * large enough, and later we'll grow other W[i] to the same length.
2365 * They must not be shrunk midway through this function!
2366 */
Jens Wiklander817466c2018-05-22 13:49:31 +02002367 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, j ) );
Jerome Forissier3602df82021-07-28 10:24:04 +02002368 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[1], j ) );
Jens Wiklander817466c2018-05-22 13:49:31 +02002369 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &T, j * 2 ) );
2370
2371 /*
2372 * Compensate for negative A (and correct at the end)
2373 */
2374 neg = ( A->s == -1 );
2375 if( neg )
2376 {
2377 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Apos, A ) );
2378 Apos.s = 1;
2379 A = &Apos;
2380 }
2381
2382 /*
2383 * If 1st call, pre-compute R^2 mod N
2384 */
2385 if( _RR == NULL || _RR->p == NULL )
2386 {
2387 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &RR, 1 ) );
2388 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &RR, N->n * 2 * biL ) );
2389 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &RR, &RR, N ) );
2390
2391 if( _RR != NULL )
2392 memcpy( _RR, &RR, sizeof( mbedtls_mpi ) );
2393 }
2394 else
2395 memcpy( &RR, _RR, sizeof( mbedtls_mpi ) );
2396
2397 /*
2398 * W[1] = A * R^2 * R^-1 mod N = A * R mod N
2399 */
2400 if( mbedtls_mpi_cmp_mpi( A, N ) >= 0 )
Jerome Forissier3602df82021-07-28 10:24:04 +02002401 {
Jens Wiklander817466c2018-05-22 13:49:31 +02002402 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &W[1], A, N ) );
Jerome Forissier3602df82021-07-28 10:24:04 +02002403 /* This should be a no-op because W[1] is already that large before
2404 * mbedtls_mpi_mod_mpi(), but it's necessary to avoid an overflow
2405 * in mpi_montmul() below, so let's make sure. */
2406 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[1], N->n + 1 ) );
2407 }
Jens Wiklander817466c2018-05-22 13:49:31 +02002408 else
2409 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[1], A ) );
2410
Jerome Forissier3602df82021-07-28 10:24:04 +02002411 /* Note that this is safe because W[1] always has at least N->n limbs
2412 * (it grew above and was preserved by mbedtls_mpi_copy()). */
2413 mpi_montmul( &W[1], &RR, N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002414
2415 /*
2416 * X = R^2 * R^-1 mod N = R mod N
2417 */
2418 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, &RR ) );
Jerome Forissier3602df82021-07-28 10:24:04 +02002419 mpi_montred( X, N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002420
2421 if( wsize > 1 )
2422 {
2423 /*
2424 * W[1 << (wsize - 1)] = W[1] ^ (wsize - 1)
2425 */
2426 j = one << ( wsize - 1 );
2427
2428 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[j], N->n + 1 ) );
2429 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[j], &W[1] ) );
2430
2431 for( i = 0; i < wsize - 1; i++ )
Jerome Forissier3602df82021-07-28 10:24:04 +02002432 mpi_montmul( &W[j], &W[j], N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002433
2434 /*
2435 * W[i] = W[i - 1] * W[1]
2436 */
2437 for( i = j + 1; i < ( one << wsize ); i++ )
2438 {
2439 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[i], N->n + 1 ) );
2440 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[i], &W[i - 1] ) );
2441
Jerome Forissier3602df82021-07-28 10:24:04 +02002442 mpi_montmul( &W[i], &W[1], N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002443 }
2444 }
2445
2446 nblimbs = E->n;
2447 bufsize = 0;
2448 nbits = 0;
2449 wbits = 0;
2450 state = 0;
2451
2452 while( 1 )
2453 {
2454 if( bufsize == 0 )
2455 {
2456 if( nblimbs == 0 )
2457 break;
2458
2459 nblimbs--;
2460
2461 bufsize = sizeof( mbedtls_mpi_uint ) << 3;
2462 }
2463
2464 bufsize--;
2465
2466 ei = (E->p[nblimbs] >> bufsize) & 1;
2467
2468 /*
2469 * skip leading 0s
2470 */
2471 if( ei == 0 && state == 0 )
2472 continue;
2473
2474 if( ei == 0 && state == 1 )
2475 {
2476 /*
2477 * out of window, square X
2478 */
Jerome Forissier3602df82021-07-28 10:24:04 +02002479 mpi_montmul( X, X, N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002480 continue;
2481 }
2482
2483 /*
2484 * add ei to current window
2485 */
2486 state = 2;
2487
2488 nbits++;
2489 wbits |= ( ei << ( wsize - nbits ) );
2490
2491 if( nbits == wsize )
2492 {
2493 /*
2494 * X = X^wsize R^-1 mod N
2495 */
2496 for( i = 0; i < wsize; i++ )
Jerome Forissier3602df82021-07-28 10:24:04 +02002497 mpi_montmul( X, X, N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002498
2499 /*
2500 * X = X * W[wbits] R^-1 mod N
2501 */
Jerome Forissier3602df82021-07-28 10:24:04 +02002502 MBEDTLS_MPI_CHK( mpi_select( &WW, W, (size_t) 1 << wsize, wbits ) );
2503 mpi_montmul( X, &WW, N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002504
2505 state--;
2506 nbits = 0;
2507 wbits = 0;
2508 }
2509 }
2510
2511 /*
2512 * process the remaining bits
2513 */
2514 for( i = 0; i < nbits; i++ )
2515 {
Jerome Forissier3602df82021-07-28 10:24:04 +02002516 mpi_montmul( X, X, N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002517
2518 wbits <<= 1;
2519
2520 if( ( wbits & ( one << wsize ) ) != 0 )
Jerome Forissier3602df82021-07-28 10:24:04 +02002521 mpi_montmul( X, &W[1], N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002522 }
2523
2524 /*
2525 * X = A^E * R * R^-1 mod N = A^E mod N
2526 */
Jerome Forissier3602df82021-07-28 10:24:04 +02002527 mpi_montred( X, N, mm, &T );
Jens Wiklander817466c2018-05-22 13:49:31 +02002528
2529 if( neg && E->n != 0 && ( E->p[0] & 1 ) != 0 )
2530 {
2531 X->s = -1;
2532 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( X, N, X ) );
2533 }
2534
2535cleanup:
2536
Jerome Forissier3602df82021-07-28 10:24:04 +02002537 for( i = ( one << ( wsize - 1 ) ); i < ( one << wsize ); i++ )
2538 mbedtls_mpi_free( &W[i] );
Jens Wiklander817466c2018-05-22 13:49:31 +02002539
Jerome Forissier3602df82021-07-28 10:24:04 +02002540 mbedtls_mpi_free( &W[1] ); mbedtls_mpi_free( &T ); mbedtls_mpi_free( &Apos );
2541 mbedtls_mpi_free( &WW );
Jens Wiklander817466c2018-05-22 13:49:31 +02002542
2543 if( _RR == NULL || _RR->p == NULL )
2544 mbedtls_mpi_free( &RR );
2545
2546 return( ret );
2547}
2548
2549/*
2550 * Greatest common divisor: G = gcd(A, B) (HAC 14.54)
2551 */
2552int mbedtls_mpi_gcd( mbedtls_mpi *G, const mbedtls_mpi *A, const mbedtls_mpi *B )
2553{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02002554 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +02002555 size_t lz, lzt;
Jerome Forissier11fa71b2020-04-20 17:17:56 +02002556 mbedtls_mpi TA, TB;
Jens Wiklander817466c2018-05-22 13:49:31 +02002557
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002558 MPI_VALIDATE_RET( G != NULL );
2559 MPI_VALIDATE_RET( A != NULL );
2560 MPI_VALIDATE_RET( B != NULL );
2561
Jerome Forissier3602df82021-07-28 10:24:04 +02002562 mbedtls_mpi_init( &TA ); mbedtls_mpi_init( &TB );
Jens Wiklander817466c2018-05-22 13:49:31 +02002563
2564 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TA, A ) );
2565 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, B ) );
2566
2567 lz = mbedtls_mpi_lsb( &TA );
2568 lzt = mbedtls_mpi_lsb( &TB );
2569
Jerome Forissier3602df82021-07-28 10:24:04 +02002570 /* The loop below gives the correct result when A==0 but not when B==0.
2571 * So have a special case for B==0. Leverage the fact that we just
2572 * calculated the lsb and lsb(B)==0 iff B is odd or 0 to make the test
2573 * slightly more efficient than cmp_int(). */
2574 if( lzt == 0 && mbedtls_mpi_get_bit( &TB, 0 ) == 0 )
2575 {
2576 ret = mbedtls_mpi_copy( G, A );
2577 goto cleanup;
2578 }
2579
Jens Wiklander817466c2018-05-22 13:49:31 +02002580 if( lzt < lz )
2581 lz = lzt;
2582
Jens Wiklander817466c2018-05-22 13:49:31 +02002583 TA.s = TB.s = 1;
2584
Jerome Forissier3602df82021-07-28 10:24:04 +02002585 /* We mostly follow the procedure described in HAC 14.54, but with some
2586 * minor differences:
2587 * - Sequences of multiplications or divisions by 2 are grouped into a
2588 * single shift operation.
2589 * - The procedure in HAC assumes that 0 < TB <= TA.
2590 * - The condition TB <= TA is not actually necessary for correctness.
2591 * TA and TB have symmetric roles except for the loop termination
2592 * condition, and the shifts at the beginning of the loop body
2593 * remove any significance from the ordering of TA vs TB before
2594 * the shifts.
2595 * - If TA = 0, the loop goes through 0 iterations and the result is
2596 * correctly TB.
2597 * - The case TB = 0 was short-circuited above.
2598 *
2599 * For the correctness proof below, decompose the original values of
2600 * A and B as
2601 * A = sa * 2^a * A' with A'=0 or A' odd, and sa = +-1
2602 * B = sb * 2^b * B' with B'=0 or B' odd, and sb = +-1
2603 * Then gcd(A, B) = 2^{min(a,b)} * gcd(A',B'),
2604 * and gcd(A',B') is odd or 0.
2605 *
2606 * At the beginning, we have TA = |A| and TB = |B| so gcd(A,B) = gcd(TA,TB).
2607 * The code maintains the following invariant:
2608 * gcd(A,B) = 2^k * gcd(TA,TB) for some k (I)
2609 */
2610
2611 /* Proof that the loop terminates:
2612 * At each iteration, either the right-shift by 1 is made on a nonzero
2613 * value and the nonnegative integer bitlen(TA) + bitlen(TB) decreases
2614 * by at least 1, or the right-shift by 1 is made on zero and then
2615 * TA becomes 0 which ends the loop (TB cannot be 0 if it is right-shifted
2616 * since in that case TB is calculated from TB-TA with the condition TB>TA).
2617 */
Jens Wiklander817466c2018-05-22 13:49:31 +02002618 while( mbedtls_mpi_cmp_int( &TA, 0 ) != 0 )
2619 {
Jerome Forissier3602df82021-07-28 10:24:04 +02002620 /* Divisions by 2 preserve the invariant (I). */
Jens Wiklander817466c2018-05-22 13:49:31 +02002621 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TA, mbedtls_mpi_lsb( &TA ) ) );
2622 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TB, mbedtls_mpi_lsb( &TB ) ) );
2623
Jerome Forissier3602df82021-07-28 10:24:04 +02002624 /* Set either TA or TB to |TA-TB|/2. Since TA and TB are both odd,
2625 * TA-TB is even so the division by 2 has an integer result.
2626 * Invariant (I) is preserved since any odd divisor of both TA and TB
2627 * also divides |TA-TB|/2, and any odd divisor of both TA and |TA-TB|/2
2628 * also divides TB, and any odd divisior of both TB and |TA-TB|/2 also
2629 * divides TA.
2630 */
Jens Wiklander817466c2018-05-22 13:49:31 +02002631 if( mbedtls_mpi_cmp_mpi( &TA, &TB ) >= 0 )
2632 {
2633 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &TA, &TA, &TB ) );
2634 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TA, 1 ) );
2635 }
2636 else
2637 {
2638 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &TB, &TB, &TA ) );
2639 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TB, 1 ) );
2640 }
Jerome Forissier3602df82021-07-28 10:24:04 +02002641 /* Note that one of TA or TB is still odd. */
Jens Wiklander817466c2018-05-22 13:49:31 +02002642 }
2643
Jerome Forissier3602df82021-07-28 10:24:04 +02002644 /* By invariant (I), gcd(A,B) = 2^k * gcd(TA,TB) for some k.
2645 * At the loop exit, TA = 0, so gcd(TA,TB) = TB.
2646 * - If there was at least one loop iteration, then one of TA or TB is odd,
2647 * and TA = 0, so TB is odd and gcd(TA,TB) = gcd(A',B'). In this case,
2648 * lz = min(a,b) so gcd(A,B) = 2^lz * TB.
2649 * - If there was no loop iteration, then A was 0, and gcd(A,B) = B.
2650 * In this case, lz = 0 and B = TB so gcd(A,B) = B = 2^lz * TB as well.
2651 */
2652
Jens Wiklander817466c2018-05-22 13:49:31 +02002653 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &TB, lz ) );
2654 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( G, &TB ) );
2655
2656cleanup:
2657
Jerome Forissier11fa71b2020-04-20 17:17:56 +02002658 mbedtls_mpi_free( &TA ); mbedtls_mpi_free( &TB );
Jens Wiklander817466c2018-05-22 13:49:31 +02002659
2660 return( ret );
2661}
2662
Jerome Forissier3602df82021-07-28 10:24:04 +02002663/* Fill X with n_bytes random bytes.
2664 * X must already have room for those bytes.
2665 * The ordering of the bytes returned from the RNG is suitable for
2666 * deterministic ECDSA (see RFC 6979 §3.3 and mbedtls_mpi_random()).
2667 * The size and sign of X are unchanged.
2668 * n_bytes must not be 0.
2669 */
2670static int mpi_fill_random_internal(
2671 mbedtls_mpi *X, size_t n_bytes,
2672 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
2673{
2674 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2675 const size_t limbs = CHARS_TO_LIMBS( n_bytes );
2676 const size_t overhead = ( limbs * ciL ) - n_bytes;
2677
2678 if( X->n < limbs )
2679 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2680
2681 memset( X->p, 0, overhead );
2682 memset( (unsigned char *) X->p + limbs * ciL, 0, ( X->n - limbs ) * ciL );
2683 MBEDTLS_MPI_CHK( f_rng( p_rng, (unsigned char *) X->p + overhead, n_bytes ) );
2684 mpi_bigendian_to_host( X->p, limbs );
2685
2686cleanup:
2687 return( ret );
2688}
2689
Jens Wiklander817466c2018-05-22 13:49:31 +02002690/*
2691 * Fill X with size bytes of random.
2692 *
2693 * Use a temporary bytes representation to make sure the result is the same
2694 * regardless of the platform endianness (useful when f_rng is actually
2695 * deterministic, eg for tests).
2696 */
2697int mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size,
2698 int (*f_rng)(void *, unsigned char *, size_t),
2699 void *p_rng )
2700{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02002701 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jerome Forissier5b25c762020-04-07 11:18:49 +02002702 size_t const limbs = CHARS_TO_LIMBS( size );
Jerome Forissier5b25c762020-04-07 11:18:49 +02002703
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002704 MPI_VALIDATE_RET( X != NULL );
2705 MPI_VALIDATE_RET( f_rng != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02002706
Jerome Forissier5b25c762020-04-07 11:18:49 +02002707 /* Ensure that target MPI has exactly the necessary number of limbs */
Jerome Forissier3602df82021-07-28 10:24:04 +02002708 MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, limbs ) );
2709 if( size == 0 )
2710 return( 0 );
Jens Wiklander817466c2018-05-22 13:49:31 +02002711
Jerome Forissier3602df82021-07-28 10:24:04 +02002712 ret = mpi_fill_random_internal( X, size, f_rng, p_rng );
Jens Wiklander817466c2018-05-22 13:49:31 +02002713
2714cleanup:
2715 return( ret );
2716}
2717
Jerome Forissier3602df82021-07-28 10:24:04 +02002718int mbedtls_mpi_random( mbedtls_mpi *X,
2719 mbedtls_mpi_sint min,
2720 const mbedtls_mpi *N,
2721 int (*f_rng)(void *, unsigned char *, size_t),
2722 void *p_rng )
2723{
2724 int ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
2725 int count;
2726 unsigned lt_lower = 1, lt_upper = 0;
2727 size_t n_bits = mbedtls_mpi_bitlen( N );
2728 size_t n_bytes = ( n_bits + 7 ) / 8;
2729 mbedtls_mpi lower_bound;
2730
2731 if( min < 0 )
2732 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2733 if( mbedtls_mpi_cmp_int( N, min ) <= 0 )
2734 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2735
2736 /*
2737 * When min == 0, each try has at worst a probability 1/2 of failing
2738 * (the msb has a probability 1/2 of being 0, and then the result will
2739 * be < N), so after 30 tries failure probability is a most 2**(-30).
2740 *
2741 * When N is just below a power of 2, as is the case when generating
2742 * a random scalar on most elliptic curves, 1 try is enough with
2743 * overwhelming probability. When N is just above a power of 2,
2744 * as when generating a random scalar on secp224k1, each try has
2745 * a probability of failing that is almost 1/2.
2746 *
2747 * The probabilities are almost the same if min is nonzero but negligible
2748 * compared to N. This is always the case when N is crypto-sized, but
2749 * it's convenient to support small N for testing purposes. When N
2750 * is small, use a higher repeat count, otherwise the probability of
2751 * failure is macroscopic.
2752 */
2753 count = ( n_bytes > 4 ? 30 : 250 );
2754
2755 mbedtls_mpi_init( &lower_bound );
2756
2757 /* Ensure that target MPI has exactly the same number of limbs
2758 * as the upper bound, even if the upper bound has leading zeros.
2759 * This is necessary for the mbedtls_mpi_lt_mpi_ct() check. */
2760 MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, N->n ) );
2761 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &lower_bound, N->n ) );
2762 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &lower_bound, min ) );
2763
2764 /*
2765 * Match the procedure given in RFC 6979 §3.3 (deterministic ECDSA)
2766 * when f_rng is a suitably parametrized instance of HMAC_DRBG:
2767 * - use the same byte ordering;
2768 * - keep the leftmost n_bits bits of the generated octet string;
2769 * - try until result is in the desired range.
2770 * This also avoids any bias, which is especially important for ECDSA.
2771 */
2772 do
2773 {
2774 MBEDTLS_MPI_CHK( mpi_fill_random_internal( X, n_bytes, f_rng, p_rng ) );
2775 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( X, 8 * n_bytes - n_bits ) );
2776
2777 if( --count == 0 )
2778 {
2779 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2780 goto cleanup;
2781 }
2782
2783 MBEDTLS_MPI_CHK( mbedtls_mpi_lt_mpi_ct( X, &lower_bound, &lt_lower ) );
2784 MBEDTLS_MPI_CHK( mbedtls_mpi_lt_mpi_ct( X, N, &lt_upper ) );
2785 }
2786 while( lt_lower != 0 || lt_upper == 0 );
2787
2788cleanup:
2789 mbedtls_mpi_free( &lower_bound );
2790 return( ret );
2791}
2792
Jens Wiklander817466c2018-05-22 13:49:31 +02002793/*
2794 * Modular inverse: X = A^-1 mod N (HAC 14.61 / 14.64)
2795 */
2796int mbedtls_mpi_inv_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *N )
2797{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02002798 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +02002799 mbedtls_mpi G, TA, TU, U1, U2, TB, TV, V1, V2;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002800 MPI_VALIDATE_RET( X != NULL );
2801 MPI_VALIDATE_RET( A != NULL );
2802 MPI_VALIDATE_RET( N != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02002803
2804 if( mbedtls_mpi_cmp_int( N, 1 ) <= 0 )
2805 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2806
Jerome Forissier3602df82021-07-28 10:24:04 +02002807 mbedtls_mpi_init( &TA ); mbedtls_mpi_init( &TU ); mbedtls_mpi_init( &U1 ); mbedtls_mpi_init( &U2 );
2808 mbedtls_mpi_init( &G ); mbedtls_mpi_init( &TB ); mbedtls_mpi_init( &TV );
2809 mbedtls_mpi_init( &V1 ); mbedtls_mpi_init( &V2 );
Jens Wiklander817466c2018-05-22 13:49:31 +02002810
2811 MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, A, N ) );
2812
2813 if( mbedtls_mpi_cmp_int( &G, 1 ) != 0 )
2814 {
2815 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2816 goto cleanup;
2817 }
2818
2819 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &TA, A, N ) );
2820 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TU, &TA ) );
2821 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, N ) );
2822 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TV, N ) );
2823
2824 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &U1, 1 ) );
2825 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &U2, 0 ) );
2826 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &V1, 0 ) );
2827 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &V2, 1 ) );
2828
2829 do
2830 {
2831 while( ( TU.p[0] & 1 ) == 0 )
2832 {
2833 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TU, 1 ) );
2834
2835 if( ( U1.p[0] & 1 ) != 0 || ( U2.p[0] & 1 ) != 0 )
2836 {
2837 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &U1, &U1, &TB ) );
2838 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U2, &U2, &TA ) );
2839 }
2840
2841 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &U1, 1 ) );
2842 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &U2, 1 ) );
2843 }
2844
2845 while( ( TV.p[0] & 1 ) == 0 )
2846 {
2847 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TV, 1 ) );
2848
2849 if( ( V1.p[0] & 1 ) != 0 || ( V2.p[0] & 1 ) != 0 )
2850 {
2851 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &V1, &V1, &TB ) );
2852 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V2, &V2, &TA ) );
2853 }
2854
2855 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &V1, 1 ) );
2856 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &V2, 1 ) );
2857 }
2858
2859 if( mbedtls_mpi_cmp_mpi( &TU, &TV ) >= 0 )
2860 {
2861 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &TU, &TU, &TV ) );
2862 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U1, &U1, &V1 ) );
2863 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U2, &U2, &V2 ) );
2864 }
2865 else
2866 {
2867 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &TV, &TV, &TU ) );
2868 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V1, &V1, &U1 ) );
2869 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V2, &V2, &U2 ) );
2870 }
2871 }
2872 while( mbedtls_mpi_cmp_int( &TU, 0 ) != 0 );
2873
2874 while( mbedtls_mpi_cmp_int( &V1, 0 ) < 0 )
2875 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &V1, &V1, N ) );
2876
2877 while( mbedtls_mpi_cmp_mpi( &V1, N ) >= 0 )
2878 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V1, &V1, N ) );
2879
2880 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, &V1 ) );
2881
2882cleanup:
2883
2884 mbedtls_mpi_free( &TA ); mbedtls_mpi_free( &TU ); mbedtls_mpi_free( &U1 ); mbedtls_mpi_free( &U2 );
2885 mbedtls_mpi_free( &G ); mbedtls_mpi_free( &TB ); mbedtls_mpi_free( &TV );
2886 mbedtls_mpi_free( &V1 ); mbedtls_mpi_free( &V2 );
2887
2888 return( ret );
2889}
2890
2891#if defined(MBEDTLS_GENPRIME)
2892
2893static const int small_prime[] =
2894{
2895 3, 5, 7, 11, 13, 17, 19, 23,
2896 29, 31, 37, 41, 43, 47, 53, 59,
2897 61, 67, 71, 73, 79, 83, 89, 97,
2898 101, 103, 107, 109, 113, 127, 131, 137,
2899 139, 149, 151, 157, 163, 167, 173, 179,
2900 181, 191, 193, 197, 199, 211, 223, 227,
2901 229, 233, 239, 241, 251, 257, 263, 269,
2902 271, 277, 281, 283, 293, 307, 311, 313,
2903 317, 331, 337, 347, 349, 353, 359, 367,
2904 373, 379, 383, 389, 397, 401, 409, 419,
2905 421, 431, 433, 439, 443, 449, 457, 461,
2906 463, 467, 479, 487, 491, 499, 503, 509,
2907 521, 523, 541, 547, 557, 563, 569, 571,
2908 577, 587, 593, 599, 601, 607, 613, 617,
2909 619, 631, 641, 643, 647, 653, 659, 661,
2910 673, 677, 683, 691, 701, 709, 719, 727,
2911 733, 739, 743, 751, 757, 761, 769, 773,
2912 787, 797, 809, 811, 821, 823, 827, 829,
2913 839, 853, 857, 859, 863, 877, 881, 883,
2914 887, 907, 911, 919, 929, 937, 941, 947,
2915 953, 967, 971, 977, 983, 991, 997, -103
2916};
2917
2918/*
2919 * Small divisors test (X must be positive)
2920 *
2921 * Return values:
2922 * 0: no small factor (possible prime, more tests needed)
2923 * 1: certain prime
2924 * MBEDTLS_ERR_MPI_NOT_ACCEPTABLE: certain non-prime
2925 * other negative: error
2926 */
2927static int mpi_check_small_factors( const mbedtls_mpi *X )
2928{
2929 int ret = 0;
2930 size_t i;
2931 mbedtls_mpi_uint r;
2932
2933 if( ( X->p[0] & 1 ) == 0 )
2934 return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
2935
2936 for( i = 0; small_prime[i] > 0; i++ )
2937 {
2938 if( mbedtls_mpi_cmp_int( X, small_prime[i] ) <= 0 )
2939 return( 1 );
2940
2941 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, small_prime[i] ) );
2942
2943 if( r == 0 )
2944 return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
2945 }
2946
2947cleanup:
2948 return( ret );
2949}
2950
2951/*
2952 * Miller-Rabin pseudo-primality test (HAC 4.24)
2953 */
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002954static int mpi_miller_rabin( const mbedtls_mpi *X, size_t rounds,
Jens Wiklander817466c2018-05-22 13:49:31 +02002955 int (*f_rng)(void *, unsigned char *, size_t),
2956 void *p_rng )
2957{
2958 int ret, count;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002959 size_t i, j, k, s;
Jens Wiklander817466c2018-05-22 13:49:31 +02002960 mbedtls_mpi W, R, T, A, RR;
2961
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002962 MPI_VALIDATE_RET( X != NULL );
2963 MPI_VALIDATE_RET( f_rng != NULL );
2964
Jerome Forissier3602df82021-07-28 10:24:04 +02002965 mbedtls_mpi_init( &W ); mbedtls_mpi_init( &R );
2966 mbedtls_mpi_init( &T ); mbedtls_mpi_init( &A );
2967 mbedtls_mpi_init( &RR );
Jens Wiklander817466c2018-05-22 13:49:31 +02002968
2969 /*
2970 * W = |X| - 1
2971 * R = W >> lsb( W )
2972 */
2973 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &W, X, 1 ) );
2974 s = mbedtls_mpi_lsb( &W );
2975 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R, &W ) );
2976 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &R, s ) );
2977
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002978 for( i = 0; i < rounds; i++ )
Jens Wiklander817466c2018-05-22 13:49:31 +02002979 {
2980 /*
2981 * pick a random A, 1 < A < |X| - 1
2982 */
Jens Wiklander817466c2018-05-22 13:49:31 +02002983 count = 0;
2984 do {
2985 MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &A, X->n * ciL, f_rng, p_rng ) );
2986
2987 j = mbedtls_mpi_bitlen( &A );
2988 k = mbedtls_mpi_bitlen( &W );
2989 if (j > k) {
Jens Wiklander3d3b0592019-03-20 15:30:29 +01002990 A.p[A.n - 1] &= ( (mbedtls_mpi_uint) 1 << ( k - ( A.n - 1 ) * biL - 1 ) ) - 1;
Jens Wiklander817466c2018-05-22 13:49:31 +02002991 }
2992
Jerome Forissier3602df82021-07-28 10:24:04 +02002993 if (count++ > 30) {
Jens Wiklander336e3292019-01-17 11:14:38 +01002994 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2995 goto cleanup;
Jens Wiklander817466c2018-05-22 13:49:31 +02002996 }
2997
2998 } while ( mbedtls_mpi_cmp_mpi( &A, &W ) >= 0 ||
2999 mbedtls_mpi_cmp_int( &A, 1 ) <= 0 );
3000
3001 /*
3002 * A = A^R mod |X|
3003 */
3004 MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &A, &A, &R, X, &RR ) );
3005
3006 if( mbedtls_mpi_cmp_mpi( &A, &W ) == 0 ||
3007 mbedtls_mpi_cmp_int( &A, 1 ) == 0 )
3008 continue;
3009
3010 j = 1;
3011 while( j < s && mbedtls_mpi_cmp_mpi( &A, &W ) != 0 )
3012 {
3013 /*
3014 * A = A * A mod |X|
3015 */
3016 MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &A, &A ) );
3017 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &A, &T, X ) );
3018
3019 if( mbedtls_mpi_cmp_int( &A, 1 ) == 0 )
3020 break;
3021
3022 j++;
3023 }
3024
3025 /*
3026 * not prime if A != |X| - 1 or A == 1
3027 */
3028 if( mbedtls_mpi_cmp_mpi( &A, &W ) != 0 ||
3029 mbedtls_mpi_cmp_int( &A, 1 ) == 0 )
3030 {
3031 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
3032 break;
3033 }
3034 }
3035
3036cleanup:
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003037 mbedtls_mpi_free( &W ); mbedtls_mpi_free( &R );
3038 mbedtls_mpi_free( &T ); mbedtls_mpi_free( &A );
Jens Wiklander817466c2018-05-22 13:49:31 +02003039 mbedtls_mpi_free( &RR );
3040
3041 return( ret );
3042}
3043
3044/*
3045 * Pseudo-primality test: small factors, then Miller-Rabin
3046 */
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003047int mbedtls_mpi_is_prime_ext( const mbedtls_mpi *X, int rounds,
3048 int (*f_rng)(void *, unsigned char *, size_t),
3049 void *p_rng )
Jens Wiklander817466c2018-05-22 13:49:31 +02003050{
Jerome Forissier11fa71b2020-04-20 17:17:56 +02003051 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Jens Wiklander817466c2018-05-22 13:49:31 +02003052 mbedtls_mpi XX;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003053 MPI_VALIDATE_RET( X != NULL );
3054 MPI_VALIDATE_RET( f_rng != NULL );
Jens Wiklander817466c2018-05-22 13:49:31 +02003055
3056 XX.s = 1;
3057 XX.n = X->n;
3058 XX.p = X->p;
3059
3060 if( mbedtls_mpi_cmp_int( &XX, 0 ) == 0 ||
3061 mbedtls_mpi_cmp_int( &XX, 1 ) == 0 )
3062 return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
3063
3064 if( mbedtls_mpi_cmp_int( &XX, 2 ) == 0 )
3065 return( 0 );
3066
3067 if( ( ret = mpi_check_small_factors( &XX ) ) != 0 )
3068 {
3069 if( ret == 1 )
3070 return( 0 );
3071
3072 return( ret );
3073 }
3074
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003075 return( mpi_miller_rabin( &XX, rounds, f_rng, p_rng ) );
Jens Wiklander817466c2018-05-22 13:49:31 +02003076}
3077
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003078#if !defined(MBEDTLS_DEPRECATED_REMOVED)
3079/*
3080 * Pseudo-primality test, error probability 2^-80
3081 */
3082int mbedtls_mpi_is_prime( const mbedtls_mpi *X,
3083 int (*f_rng)(void *, unsigned char *, size_t),
3084 void *p_rng )
3085{
3086 MPI_VALIDATE_RET( X != NULL );
3087 MPI_VALIDATE_RET( f_rng != NULL );
3088
3089 /*
3090 * In the past our key generation aimed for an error rate of at most
3091 * 2^-80. Since this function is deprecated, aim for the same certainty
3092 * here as well.
3093 */
3094 return( mbedtls_mpi_is_prime_ext( X, 40, f_rng, p_rng ) );
3095}
3096#endif
3097
Jens Wiklander817466c2018-05-22 13:49:31 +02003098/*
3099 * Prime number generation
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003100 *
3101 * To generate an RSA key in a way recommended by FIPS 186-4, both primes must
3102 * be either 1024 bits or 1536 bits long, and flags must contain
3103 * MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR.
Jens Wiklander817466c2018-05-22 13:49:31 +02003104 */
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003105int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int flags,
Jens Wiklander817466c2018-05-22 13:49:31 +02003106 int (*f_rng)(void *, unsigned char *, size_t),
3107 void *p_rng )
3108{
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003109#ifdef MBEDTLS_HAVE_INT64
3110// ceil(2^63.5)
3111#define CEIL_MAXUINT_DIV_SQRT2 0xb504f333f9de6485ULL
3112#else
3113// ceil(2^31.5)
3114#define CEIL_MAXUINT_DIV_SQRT2 0xb504f334U
3115#endif
3116 int ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
Jens Wiklander817466c2018-05-22 13:49:31 +02003117 size_t k, n;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003118 int rounds;
Jens Wiklander817466c2018-05-22 13:49:31 +02003119 mbedtls_mpi_uint r;
3120 mbedtls_mpi Y;
3121
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003122 MPI_VALIDATE_RET( X != NULL );
3123 MPI_VALIDATE_RET( f_rng != NULL );
3124
Jens Wiklander817466c2018-05-22 13:49:31 +02003125 if( nbits < 3 || nbits > MBEDTLS_MPI_MAX_BITS )
3126 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
3127
Jerome Forissier3602df82021-07-28 10:24:04 +02003128 mbedtls_mpi_init( &Y );
Jens Wiklander817466c2018-05-22 13:49:31 +02003129
3130 n = BITS_TO_LIMBS( nbits );
3131
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003132 if( ( flags & MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR ) == 0 )
Jens Wiklander817466c2018-05-22 13:49:31 +02003133 {
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003134 /*
3135 * 2^-80 error probability, number of rounds chosen per HAC, table 4.4
3136 */
3137 rounds = ( ( nbits >= 1300 ) ? 2 : ( nbits >= 850 ) ? 3 :
3138 ( nbits >= 650 ) ? 4 : ( nbits >= 350 ) ? 8 :
3139 ( nbits >= 250 ) ? 12 : ( nbits >= 150 ) ? 18 : 27 );
Jens Wiklander817466c2018-05-22 13:49:31 +02003140 }
3141 else
3142 {
3143 /*
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003144 * 2^-100 error probability, number of rounds computed based on HAC,
3145 * fact 4.48
Jens Wiklander817466c2018-05-22 13:49:31 +02003146 */
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003147 rounds = ( ( nbits >= 1450 ) ? 4 : ( nbits >= 1150 ) ? 5 :
3148 ( nbits >= 1000 ) ? 6 : ( nbits >= 850 ) ? 7 :
3149 ( nbits >= 750 ) ? 8 : ( nbits >= 500 ) ? 13 :
3150 ( nbits >= 250 ) ? 28 : ( nbits >= 150 ) ? 40 : 51 );
3151 }
Jens Wiklander817466c2018-05-22 13:49:31 +02003152
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003153 while( 1 )
3154 {
3155 MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( X, n * ciL, f_rng, p_rng ) );
3156 /* make sure generated number is at least (nbits-1)+0.5 bits (FIPS 186-4 §B.3.3 steps 4.4, 5.5) */
3157 if( X->p[n-1] < CEIL_MAXUINT_DIV_SQRT2 ) continue;
Jens Wiklander817466c2018-05-22 13:49:31 +02003158
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003159 k = n * biL;
3160 if( k > nbits ) MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( X, k - nbits ) );
3161 X->p[0] |= 1;
Jens Wiklander817466c2018-05-22 13:49:31 +02003162
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003163 if( ( flags & MBEDTLS_MPI_GEN_PRIME_FLAG_DH ) == 0 )
Jens Wiklander817466c2018-05-22 13:49:31 +02003164 {
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003165 ret = mbedtls_mpi_is_prime_ext( X, rounds, f_rng, p_rng );
Jens Wiklander817466c2018-05-22 13:49:31 +02003166
3167 if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
3168 goto cleanup;
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003169 }
3170 else
3171 {
Jens Wiklander817466c2018-05-22 13:49:31 +02003172 /*
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003173 * An necessary condition for Y and X = 2Y + 1 to be prime
3174 * is X = 2 mod 3 (which is equivalent to Y = 2 mod 3).
3175 * Make sure it is satisfied, while keeping X = 3 mod 4
Jens Wiklander817466c2018-05-22 13:49:31 +02003176 */
Jens Wiklander3d3b0592019-03-20 15:30:29 +01003177
3178 X->p[0] |= 2;
3179
3180 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, 3 ) );
3181 if( r == 0 )
3182 MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 8 ) );
3183 else if( r == 1 )
3184 MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 4 ) );
3185
3186 /* Set Y = (X-1) / 2, which is X / 2 because X is odd */
3187 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Y, X ) );
3188 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &Y, 1 ) );
3189
3190 while( 1 )
3191 {
3192 /*
3193 * First, check small factors for X and Y
3194 * before doing Miller-Rabin on any of them
3195 */
3196 if( ( ret = mpi_check_small_factors( X ) ) == 0 &&
3197 ( ret = mpi_check_small_factors( &Y ) ) == 0 &&
3198 ( ret = mpi_miller_rabin( X, rounds, f_rng, p_rng ) )
3199 == 0 &&
3200 ( ret = mpi_miller_rabin( &Y, rounds, f_rng, p_rng ) )
3201 == 0 )
3202 goto cleanup;
3203
3204 if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
3205 goto cleanup;
3206
3207 /*
3208 * Next candidates. We want to preserve Y = (X-1) / 2 and
3209 * Y = 1 mod 2 and Y = 2 mod 3 (eq X = 3 mod 4 and X = 2 mod 3)
3210 * so up Y by 6 and X by 12.
3211 */
3212 MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 12 ) );
3213 MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &Y, &Y, 6 ) );
3214 }
Jens Wiklander817466c2018-05-22 13:49:31 +02003215 }
3216 }
3217
3218cleanup:
3219
3220 mbedtls_mpi_free( &Y );
3221
3222 return( ret );
3223}
3224
3225#endif /* MBEDTLS_GENPRIME */
3226
3227#if defined(MBEDTLS_SELF_TEST)
3228
3229#define GCD_PAIR_COUNT 3
3230
3231static const int gcd_pairs[GCD_PAIR_COUNT][3] =
3232{
3233 { 693, 609, 21 },
3234 { 1764, 868, 28 },
3235 { 768454923, 542167814, 1 }
3236};
3237
3238/*
3239 * Checkup routine
3240 */
3241int mbedtls_mpi_self_test( int verbose )
3242{
3243 int ret, i;
3244 mbedtls_mpi A, E, N, X, Y, U, V;
3245
Jerome Forissier3602df82021-07-28 10:24:04 +02003246 mbedtls_mpi_init( &A ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &N ); mbedtls_mpi_init( &X );
3247 mbedtls_mpi_init( &Y ); mbedtls_mpi_init( &U ); mbedtls_mpi_init( &V );
Jens Wiklander817466c2018-05-22 13:49:31 +02003248
3249 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &A, 16,
3250 "EFE021C2645FD1DC586E69184AF4A31E" \
3251 "D5F53E93B5F123FA41680867BA110131" \
3252 "944FE7952E2517337780CB0DB80E61AA" \
3253 "E7C8DDC6C5C6AADEB34EB38A2F40D5E6" ) );
3254
3255 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &E, 16,
3256 "B2E7EFD37075B9F03FF989C7C5051C20" \
3257 "34D2A323810251127E7BF8625A4F49A5" \
3258 "F3E27F4DA8BD59C47D6DAABA4C8127BD" \
3259 "5B5C25763222FEFCCFC38B832366C29E" ) );
3260
3261 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &N, 16,
3262 "0066A198186C18C10B2F5ED9B522752A" \
3263 "9830B69916E535C8F047518A889A43A5" \
3264 "94B6BED27A168D31D4A52F88925AA8F5" ) );
3265
3266 MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &X, &A, &N ) );
3267
3268 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
3269 "602AB7ECA597A3D6B56FF9829A5E8B85" \
3270 "9E857EA95A03512E2BAE7391688D264A" \
3271 "A5663B0341DB9CCFD2C4C5F421FEC814" \
3272 "8001B72E848A38CAE1C65F78E56ABDEF" \
3273 "E12D3C039B8A02D6BE593F0BBBDA56F1" \
3274 "ECF677152EF804370C1A305CAF3B5BF1" \
3275 "30879B56C61DE584A0F53A2447A51E" ) );
3276
3277 if( verbose != 0 )
3278 mbedtls_printf( " MPI test #1 (mul_mpi): " );
3279
3280 if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 )
3281 {
3282 if( verbose != 0 )
3283 mbedtls_printf( "failed\n" );
3284
3285 ret = 1;
3286 goto cleanup;
3287 }
3288
3289 if( verbose != 0 )
3290 mbedtls_printf( "passed\n" );
3291
3292 MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &X, &Y, &A, &N ) );
3293
3294 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
3295 "256567336059E52CAE22925474705F39A94" ) );
3296
3297 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &V, 16,
3298 "6613F26162223DF488E9CD48CC132C7A" \
3299 "0AC93C701B001B092E4E5B9F73BCD27B" \
3300 "9EE50D0657C77F374E903CDFA4C642" ) );
3301
3302 if( verbose != 0 )
3303 mbedtls_printf( " MPI test #2 (div_mpi): " );
3304
3305 if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 ||
3306 mbedtls_mpi_cmp_mpi( &Y, &V ) != 0 )
3307 {
3308 if( verbose != 0 )
3309 mbedtls_printf( "failed\n" );
3310
3311 ret = 1;
3312 goto cleanup;
3313 }
3314
3315 if( verbose != 0 )
3316 mbedtls_printf( "passed\n" );
3317
3318 MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &X, &A, &E, &N, NULL ) );
3319
3320 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
3321 "36E139AEA55215609D2816998ED020BB" \
3322 "BD96C37890F65171D948E9BC7CBAA4D9" \
3323 "325D24D6A3C12710F10A09FA08AB87" ) );
3324
3325 if( verbose != 0 )
3326 mbedtls_printf( " MPI test #3 (exp_mod): " );
3327
3328 if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 )
3329 {
3330 if( verbose != 0 )
3331 mbedtls_printf( "failed\n" );
3332
3333 ret = 1;
3334 goto cleanup;
3335 }
3336
3337 if( verbose != 0 )
3338 mbedtls_printf( "passed\n" );
3339
3340 MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &X, &A, &N ) );
3341
3342 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
3343 "003A0AAEDD7E784FC07D8F9EC6E3BFD5" \
3344 "C3DBA76456363A10869622EAC2DD84EC" \
3345 "C5B8A74DAC4D09E03B5E0BE779F2DF61" ) );
3346
3347 if( verbose != 0 )
3348 mbedtls_printf( " MPI test #4 (inv_mod): " );
3349
3350 if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 )
3351 {
3352 if( verbose != 0 )
3353 mbedtls_printf( "failed\n" );
3354
3355 ret = 1;
3356 goto cleanup;
3357 }
3358
3359 if( verbose != 0 )
3360 mbedtls_printf( "passed\n" );
3361
3362 if( verbose != 0 )
3363 mbedtls_printf( " MPI test #5 (simple gcd): " );
3364
3365 for( i = 0; i < GCD_PAIR_COUNT; i++ )
3366 {
3367 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &X, gcd_pairs[i][0] ) );
3368 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &Y, gcd_pairs[i][1] ) );
3369
3370 MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &A, &X, &Y ) );
3371
3372 if( mbedtls_mpi_cmp_int( &A, gcd_pairs[i][2] ) != 0 )
3373 {
3374 if( verbose != 0 )
3375 mbedtls_printf( "failed at %d\n", i );
3376
3377 ret = 1;
3378 goto cleanup;
3379 }
3380 }
3381
3382 if( verbose != 0 )
3383 mbedtls_printf( "passed\n" );
3384
3385cleanup:
3386
3387 if( ret != 0 && verbose != 0 )
Jerome Forissier3602df82021-07-28 10:24:04 +02003388 mbedtls_printf( "Unexpected error, return code = %08X\n", (unsigned int) ret );
Jens Wiklander817466c2018-05-22 13:49:31 +02003389
3390 mbedtls_mpi_free( &A ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &N ); mbedtls_mpi_free( &X );
3391 mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &U ); mbedtls_mpi_free( &V );
3392
3393 if( verbose != 0 )
3394 mbedtls_printf( "\n" );
3395
3396 return( ret );
3397}
3398
3399#endif /* MBEDTLS_SELF_TEST */
3400
3401#endif /* MBEDTLS_BIGNUM_C */