1 /*
2 * Multi-precision integer library
3 *
4 * Copyright The Mbed TLS Contributors
5 * SPDX-License-Identifier: Apache-2.0
6 *
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.
18 */
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
36 #include "common.h"
37
38 #if defined(MBEDTLS_BIGNUM_C)
39
40 #include "mbedtls/bignum.h"
41 #include "bn_mul.h"
42 #include "mbedtls/platform_util.h"
43 #include "mbedtls/error.h"
44
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
57 #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 )
61
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
75 /* Implementation that should never be optimized out by the compiler */
mbedtls_mpi_zeroize(mbedtls_mpi_uint * v,size_t n)76 static void mbedtls_mpi_zeroize( mbedtls_mpi_uint *v, size_t n )
77 {
78 mbedtls_platform_zeroize( v, ciL * n );
79 }
80
81 /*
82 * Initialize one MPI
83 */
mbedtls_mpi_init(mbedtls_mpi * X)84 void mbedtls_mpi_init( mbedtls_mpi *X )
85 {
86 MPI_VALIDATE( X != NULL );
87
88 X->s = 1;
89 X->n = 0;
90 X->p = NULL;
91 }
92
93 /*
94 * Unallocate one MPI
95 */
mbedtls_mpi_free(mbedtls_mpi * X)96 void 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 );
104 mbedtls_free( X->p );
105 }
106
107 X->s = 1;
108 X->n = 0;
109 X->p = NULL;
110 }
111
112 /*
113 * Enlarge to the specified number of limbs
114 */
mbedtls_mpi_grow(mbedtls_mpi * X,size_t nblimbs)115 int mbedtls_mpi_grow( mbedtls_mpi *X, size_t nblimbs )
116 {
117 mbedtls_mpi_uint *p;
118 MPI_VALIDATE_RET( X != NULL );
119
120 if( nblimbs > MBEDTLS_MPI_MAX_LIMBS )
121 return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
122
123 if( X->n < nblimbs )
124 {
125 if( ( p = (mbedtls_mpi_uint*)mbedtls_calloc( nblimbs, ciL ) ) == NULL )
126 return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
127
128 if( X->p != NULL )
129 {
130 memcpy( p, X->p, X->n * ciL );
131 mbedtls_mpi_zeroize( X->p, X->n );
132 mbedtls_free( X->p );
133 }
134
135 X->n = nblimbs;
136 X->p = p;
137 }
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 */
mbedtls_mpi_shrink(mbedtls_mpi * X,size_t nblimbs)146 int mbedtls_mpi_shrink( mbedtls_mpi *X, size_t nblimbs )
147 {
148 mbedtls_mpi_uint *p;
149 size_t i;
150 MPI_VALIDATE_RET( X != NULL );
151
152 if( nblimbs > MBEDTLS_MPI_MAX_LIMBS )
153 return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
154
155 /* Actually resize up if there are currently fewer than nblimbs limbs. */
156 if( X->n <= nblimbs )
157 return( mbedtls_mpi_grow( X, nblimbs ) );
158 /* After this point, then X->n > nblimbs and in particular X->n > 0. */
159
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
168 if( ( p = (mbedtls_mpi_uint*)mbedtls_calloc( i, ciL ) ) == NULL )
169 return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
170
171 if( X->p != NULL )
172 {
173 memcpy( p, X->p, i * ciL );
174 mbedtls_mpi_zeroize( X->p, X->n );
175 mbedtls_free( X->p );
176 }
177
178 X->n = i;
179 X->p = p;
180
181 return( 0 );
182 }
183
184 /* Resize X to have exactly n limbs and set it to 0. */
mbedtls_mpi_resize_clear(mbedtls_mpi * X,size_t limbs)185 static 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
205 /*
206 * 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().
213 */
mbedtls_mpi_copy(mbedtls_mpi * X,const mbedtls_mpi * Y)214 int mbedtls_mpi_copy( mbedtls_mpi *X, const mbedtls_mpi *Y )
215 {
216 int ret = 0;
217 size_t i;
218 MPI_VALIDATE_RET( X != NULL );
219 MPI_VALIDATE_RET( Y != NULL );
220
221 if( X == Y )
222 return( 0 );
223
224 if( Y->n == 0 )
225 {
226 if( X->n != 0 )
227 {
228 X->s = 1;
229 memset( X->p, 0, X->n * ciL );
230 }
231 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
241 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 }
249
250 memcpy( X->p, Y->p, i * ciL );
251
252 cleanup:
253
254 return( ret );
255 }
256
257 /*
258 * Swap the contents of X and Y
259 */
mbedtls_mpi_swap(mbedtls_mpi * X,mbedtls_mpi * Y)260 void mbedtls_mpi_swap( mbedtls_mpi *X, mbedtls_mpi *Y )
261 {
262 mbedtls_mpi T;
263 MPI_VALIDATE( X != NULL );
264 MPI_VALIDATE( Y != NULL );
265
266 memcpy( &T, X, sizeof( mbedtls_mpi ) );
267 memcpy( X, Y, sizeof( mbedtls_mpi ) );
268 memcpy( Y, &T, sizeof( mbedtls_mpi ) );
269 }
270
271 /**
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 */
mpi_safe_cond_select_sign(int a,int b,unsigned char second)283 static 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 */
mpi_safe_cond_assign(size_t n,mbedtls_mpi_uint * dest,const mbedtls_mpi_uint * src,unsigned char assign)307 static 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
332 /*
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 */
mbedtls_mpi_safe_cond_assign(mbedtls_mpi * X,const mbedtls_mpi * Y,unsigned char assign)337 int mbedtls_mpi_safe_cond_assign( mbedtls_mpi *X, const mbedtls_mpi *Y, unsigned char assign )
338 {
339 int ret = 0;
340 size_t i;
341 mbedtls_mpi_uint limb_mask;
342 MPI_VALIDATE_RET( X != NULL );
343 MPI_VALIDATE_RET( Y != NULL );
344
345 /* 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
352 /* make sure assign is 0 or 1 in a time-constant manner */
353 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
360
361 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
362
363 X->s = mpi_safe_cond_select_sign( X->s, Y->s, assign );
364
365 mpi_safe_cond_assign( Y->n, X->p, Y->p, assign );
366
367 for( i = Y->n; i < X->n; i++ )
368 X->p[i] &= ~limb_mask;
369
370 cleanup:
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 */
mbedtls_mpi_safe_cond_swap(mbedtls_mpi * X,mbedtls_mpi * Y,unsigned char swap)380 int mbedtls_mpi_safe_cond_swap( mbedtls_mpi *X, mbedtls_mpi *Y, unsigned char swap )
381 {
382 int ret, s;
383 size_t i;
384 mbedtls_mpi_uint limb_mask;
385 mbedtls_mpi_uint tmp;
386 MPI_VALIDATE_RET( X != NULL );
387 MPI_VALIDATE_RET( Y != NULL );
388
389 if( X == Y )
390 return( 0 );
391
392 /* 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
399 /* make sure swap is 0 or 1 in a time-constant manner */
400 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
407
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;
412 X->s = mpi_safe_cond_select_sign( X->s, Y->s, swap );
413 Y->s = mpi_safe_cond_select_sign( Y->s, s, swap );
414
415
416 for( i = 0; i < X->n; i++ )
417 {
418 tmp = X->p[i];
419 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 );
421 }
422
423 cleanup:
424 return( ret );
425 }
426
427 /*
428 * Set value from integer
429 */
mbedtls_mpi_lset(mbedtls_mpi * X,mbedtls_mpi_sint z)430 int mbedtls_mpi_lset( mbedtls_mpi *X, mbedtls_mpi_sint z )
431 {
432 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
433 MPI_VALIDATE_RET( X != NULL );
434
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
441 cleanup:
442
443 return( ret );
444 }
445
446 /*
447 * Get a specific bit
448 */
mbedtls_mpi_get_bit(const mbedtls_mpi * X,size_t pos)449 int mbedtls_mpi_get_bit( const mbedtls_mpi *X, size_t pos )
450 {
451 MPI_VALIDATE_RET( X != NULL );
452
453 if( X->n * biL <= pos )
454 return( 0 );
455
456 return( ( X->p[pos / biL] >> ( pos % biL ) ) & 0x01 );
457 }
458
459 /* Get a specific byte, without range checks. */
460 #define GET_BYTE( X, i ) \
461 ( ( ( X )->p[( i ) / ciL] >> ( ( ( i ) % ciL ) * 8 ) ) & 0xff )
462
463 /*
464 * Set a bit to a specific value of 0 or 1
465 */
mbedtls_mpi_set_bit(mbedtls_mpi * X,size_t pos,unsigned char val)466 int 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;
471 MPI_VALIDATE_RET( X != NULL );
472
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
487 cleanup:
488
489 return( ret );
490 }
491
492 /*
493 * Return the number of less significant zero-bits
494 */
mbedtls_mpi_lsb(const mbedtls_mpi * X)495 size_t mbedtls_mpi_lsb( const mbedtls_mpi *X )
496 {
497 size_t i, j, count = 0;
498 MBEDTLS_INTERNAL_VALIDATE_RET( X != NULL, 0 );
499
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 */
mbedtls_clz(const mbedtls_mpi_uint x)511 static 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 */
mbedtls_mpi_bitlen(const mbedtls_mpi * X)529 size_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 */
mbedtls_mpi_size(const mbedtls_mpi * X)548 size_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 */
mpi_get_digit(mbedtls_mpi_uint * d,int radix,char c)556 static 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 */
mbedtls_mpi_read_string(mbedtls_mpi * X,int radix,const char * s)573 int mbedtls_mpi_read_string( mbedtls_mpi *X, int radix, const char *s )
574 {
575 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
576 size_t i, j, slen, n;
577 int sign = 1;
578 mbedtls_mpi_uint d;
579 mbedtls_mpi T;
580 MPI_VALIDATE_RET( X != NULL );
581 MPI_VALIDATE_RET( s != NULL );
582
583 if( radix < 2 || radix > 16 )
584 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
585
586 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 }
599
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 {
614 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 {
624 MBEDTLS_MPI_CHK( mpi_get_digit( &d, radix, s[i] ) );
625 MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &T, X, radix ) );
626 MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, &T, d ) );
627 }
628 }
629
630 if( sign < 0 && mbedtls_mpi_bitlen( X ) != 0 )
631 X->s = -1;
632
633 cleanup:
634
635 mbedtls_mpi_free( &T );
636
637 return( ret );
638 }
639
640 /*
641 * Helper to write the digits high-order first.
642 */
mpi_write_hlp(mbedtls_mpi * X,int radix,char ** p,const size_t buflen)643 static int mpi_write_hlp( mbedtls_mpi *X, int radix,
644 char **p, const size_t buflen )
645 {
646 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
647 mbedtls_mpi_uint r;
648 size_t length = 0;
649 char *p_end = *p + buflen;
650
651 do
652 {
653 if( length >= buflen )
654 {
655 return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
656 }
657
658 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 ) );
667
668 length++;
669 } while( mbedtls_mpi_cmp_int( X, 0 ) != 0 );
670
671 memmove( *p, p_end, length );
672 *p += length;
673
674 cleanup:
675
676 return( ret );
677 }
678
679 /*
680 * Export into an ASCII string
681 */
mbedtls_mpi_write_string(const mbedtls_mpi * X,int radix,char * buf,size_t buflen,size_t * olen)682 int 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;
689 MPI_VALIDATE_RET( X != NULL );
690 MPI_VALIDATE_RET( olen != NULL );
691 MPI_VALIDATE_RET( buflen == 0 || buf != NULL );
692
693 if( radix < 2 || radix > 16 )
694 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
695
696 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. */
710
711 if( buflen < n )
712 {
713 *olen = n;
714 return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
715 }
716
717 p = buf;
718 mbedtls_mpi_init( &T );
719
720 if( X->s == -1 )
721 {
722 *p++ = '-';
723 buflen--;
724 }
725
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
753 MBEDTLS_MPI_CHK( mpi_write_hlp( &T, radix, &p, buflen ) );
754 }
755
756 *p++ = '\0';
757 *olen = p - buf;
758
759 cleanup:
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 */
mbedtls_mpi_read_file(mbedtls_mpi * X,int radix,FILE * fin)770 int 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
781 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
787 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 */
mbedtls_mpi_write_file(const char * p,const mbedtls_mpi * X,int radix,FILE * fout)809 int mbedtls_mpi_write_file( const char *p, const mbedtls_mpi *X, int radix, FILE *fout )
810 {
811 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
812 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 ];
818 MPI_VALIDATE_RET( X != NULL );
819
820 if( radix < 2 || radix > 16 )
821 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
822
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
843 cleanup:
844
845 return( ret );
846 }
847 #endif /* MBEDTLS_FS_IO */
848
849
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
mpi_uint_bigendian_to_host_c(mbedtls_mpi_uint x)853 static 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
mpi_uint_bigendian_to_host(mbedtls_mpi_uint x)868 static 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
mpi_bigendian_to_host(mbedtls_mpi_uint * const p,size_t limbs)911 static 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
940 /*
941 * Import X from unsigned binary data, little endian
942 */
mbedtls_mpi_read_binary_le(mbedtls_mpi * X,const unsigned char * buf,size_t buflen)943 int 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 */
951 MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, limbs ) );
952
953 for( i = 0; i < buflen; i++ )
954 X->p[i / ciL] |= ((mbedtls_mpi_uint) buf[i]) << ((i % ciL) << 3);
955
956 cleanup:
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 /*
967 * Import X from unsigned binary data, big endian
968 */
mbedtls_mpi_read_binary(mbedtls_mpi * X,const unsigned char * buf,size_t buflen)969 int mbedtls_mpi_read_binary( mbedtls_mpi *X, const unsigned char *buf, size_t buflen )
970 {
971 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
972 size_t const limbs = CHARS_TO_LIMBS( buflen );
973 size_t const overhead = ( limbs * ciL ) - buflen;
974 unsigned char *Xp;
975
976 MPI_VALIDATE_RET( X != NULL );
977 MPI_VALIDATE_RET( buflen == 0 || buf != NULL );
978
979 /* Ensure that target MPI has exactly the necessary number of limbs */
980 MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, limbs ) );
981
982 /* Avoid calling `memcpy` with NULL source or destination argument,
983 * even if buflen is 0. */
984 if( buflen != 0 )
985 {
986 Xp = (unsigned char*) X->p;
987 memcpy( Xp + overhead, buf, buflen );
988
989 mpi_bigendian_to_host( X->p, limbs );
990 }
991
992 cleanup:
993
994 /*
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 */
999 return( ret );
1000 }
1001
1002 /*
1003 * Export X into unsigned binary data, little endian
1004 */
mbedtls_mpi_write_binary_le(const mbedtls_mpi * X,unsigned char * buf,size_t buflen)1005 int 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 /*
1042 * Export X into unsigned binary data, big endian
1043 */
mbedtls_mpi_write_binary(const mbedtls_mpi * X,unsigned char * buf,size_t buflen)1044 int mbedtls_mpi_write_binary( const mbedtls_mpi *X,
1045 unsigned char *buf, size_t buflen )
1046 {
1047 size_t stored_bytes;
1048 size_t bytes_to_copy;
1049 unsigned char *p;
1050 size_t i;
1051
1052 MPI_VALIDATE_RET( X != NULL );
1053 MPI_VALIDATE_RET( buflen == 0 || buf != NULL );
1054
1055 stored_bytes = X->n * ciL;
1056
1057 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 }
1080
1081 for( i = 0; i < bytes_to_copy; i++ )
1082 p[bytes_to_copy - i - 1] = GET_BYTE( X, i );
1083
1084 return( 0 );
1085 }
1086
1087 /*
1088 * Left-shift: X <<= count
1089 */
mbedtls_mpi_shift_l(mbedtls_mpi * X,size_t count)1090 int mbedtls_mpi_shift_l( mbedtls_mpi *X, size_t count )
1091 {
1092 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1093 size_t i, v0, t1;
1094 mbedtls_mpi_uint r0 = 0, r1;
1095 MPI_VALIDATE_RET( X != NULL );
1096
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
1133 cleanup:
1134
1135 return( ret );
1136 }
1137
1138 /*
1139 * Right-shift: X >>= count
1140 */
mbedtls_mpi_shift_r(mbedtls_mpi * X,size_t count)1141 int mbedtls_mpi_shift_r( mbedtls_mpi *X, size_t count )
1142 {
1143 size_t i, v0, v1;
1144 mbedtls_mpi_uint r0 = 0, r1;
1145 MPI_VALIDATE_RET( X != NULL );
1146
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 */
mbedtls_mpi_cmp_abs(const mbedtls_mpi * X,const mbedtls_mpi * Y)1185 int mbedtls_mpi_cmp_abs( const mbedtls_mpi *X, const mbedtls_mpi *Y )
1186 {
1187 size_t i, j;
1188 MPI_VALIDATE_RET( X != NULL );
1189 MPI_VALIDATE_RET( Y != NULL );
1190
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 */
mbedtls_mpi_cmp_mpi(const mbedtls_mpi * X,const mbedtls_mpi * Y)1217 int mbedtls_mpi_cmp_mpi( const mbedtls_mpi *X, const mbedtls_mpi *Y )
1218 {
1219 size_t i, j;
1220 MPI_VALIDATE_RET( X != NULL );
1221 MPI_VALIDATE_RET( Y != NULL );
1222
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
1249 /** 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 */
ct_lt_mpi_uint(const mbedtls_mpi_uint x,const mbedtls_mpi_uint y)1256 static 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 */
mbedtls_mpi_lt_mpi_ct(const mbedtls_mpi * X,const mbedtls_mpi * Y,unsigned * ret)1287 int 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
1350 /*
1351 * Compare signed values
1352 */
mbedtls_mpi_cmp_int(const mbedtls_mpi * X,mbedtls_mpi_sint z)1353 int mbedtls_mpi_cmp_int( const mbedtls_mpi *X, mbedtls_mpi_sint z )
1354 {
1355 mbedtls_mpi Y;
1356 mbedtls_mpi_uint p[1];
1357 MPI_VALIDATE_RET( X != NULL );
1358
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 */
mbedtls_mpi_add_abs(mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1370 int mbedtls_mpi_add_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
1371 {
1372 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1373 size_t i, j;
1374 mbedtls_mpi_uint *o, *p, c, tmp;
1375 MPI_VALIDATE_RET( X != NULL );
1376 MPI_VALIDATE_RET( A != NULL );
1377 MPI_VALIDATE_RET( B != NULL );
1378
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
1421 cleanup:
1422
1423 return( ret );
1424 }
1425
1426 /**
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`.
1442 */
mpi_sub_hlp(size_t n,mbedtls_mpi_uint * d,const mbedtls_mpi_uint * l,const mbedtls_mpi_uint * r)1443 static 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 )
1447 {
1448 size_t i;
1449 mbedtls_mpi_uint c = 0, t, z;
1450
1451 for( i = 0; i < n; i++ )
1452 {
1453 z = ( l[i] < c ); t = l[i] - c;
1454 c = ( t < r[i] ) + z; d[i] = t - r[i];
1455 }
1456
1457 return( c );
1458 }
1459
1460 /*
1461 * Unsigned subtraction: X = |A| - |B| (HAC 14.9, 14.10)
1462 */
mbedtls_mpi_sub_abs(mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1463 int mbedtls_mpi_sub_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
1464 {
1465 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1466 size_t n;
1467 mbedtls_mpi_uint carry;
1468 MPI_VALIDATE_RET( X != NULL );
1469 MPI_VALIDATE_RET( A != NULL );
1470 MPI_VALIDATE_RET( B != NULL );
1471
1472 for( n = B->n; n > 0; n-- )
1473 if( B->p[n - 1] != 0 )
1474 break;
1475 if( n > A->n )
1476 {
1477 /* B >= (2^ciL)^n > A */
1478 ret = MBEDTLS_ERR_MPI_NEGATIVE_VALUE;
1479 goto cleanup;
1480 }
1481
1482 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;
1510
1511 cleanup:
1512 return( ret );
1513 }
1514
1515 /*
1516 * Signed addition: X = A + B
1517 */
mbedtls_mpi_add_mpi(mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1518 int mbedtls_mpi_add_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
1519 {
1520 int ret, s;
1521 MPI_VALIDATE_RET( X != NULL );
1522 MPI_VALIDATE_RET( A != NULL );
1523 MPI_VALIDATE_RET( B != NULL );
1524
1525 s = A->s;
1526 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
1545 cleanup:
1546
1547 return( ret );
1548 }
1549
1550 /*
1551 * Signed subtraction: X = A - B
1552 */
mbedtls_mpi_sub_mpi(mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1553 int mbedtls_mpi_sub_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
1554 {
1555 int ret, s;
1556 MPI_VALIDATE_RET( X != NULL );
1557 MPI_VALIDATE_RET( A != NULL );
1558 MPI_VALIDATE_RET( B != NULL );
1559
1560 s = A->s;
1561 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
1580 cleanup:
1581
1582 return( ret );
1583 }
1584
1585 /*
1586 * Signed addition: X = A + b
1587 */
mbedtls_mpi_add_int(mbedtls_mpi * X,const mbedtls_mpi * A,mbedtls_mpi_sint b)1588 int 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];
1592 MPI_VALIDATE_RET( X != NULL );
1593 MPI_VALIDATE_RET( A != NULL );
1594
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 */
mbedtls_mpi_sub_int(mbedtls_mpi * X,const mbedtls_mpi * A,mbedtls_mpi_sint b)1606 int 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];
1610 MPI_VALIDATE_RET( X != NULL );
1611 MPI_VALIDATE_RET( A != NULL );
1612
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
1621 /** 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.
1636 */
1637 static
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
mpi_mul_hlp(size_t i,const mbedtls_mpi_uint * s,mbedtls_mpi_uint * d,mbedtls_mpi_uint b)1645 void mpi_mul_hlp( size_t i,
1646 const mbedtls_mpi_uint *s,
1647 mbedtls_mpi_uint *d,
1648 mbedtls_mpi_uint b )
1649 {
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
1703 while( c != 0 )
1704 {
1705 *d += c; c = ( *d < c ); d++;
1706 }
1707 }
1708
1709 /*
1710 * Baseline multiplication: X = A * B (HAC 14.12)
1711 */
mbedtls_mpi_mul_mpi(mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1712 int mbedtls_mpi_mul_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )
1713 {
1714 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1715 size_t i, j;
1716 mbedtls_mpi TA, TB;
1717 int result_is_zero = 0;
1718 MPI_VALIDATE_RET( X != NULL );
1719 MPI_VALIDATE_RET( A != NULL );
1720 MPI_VALIDATE_RET( B != NULL );
1721
1722 mbedtls_mpi_init( &TA ); mbedtls_mpi_init( &TB );
1723
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;
1730 if( i == 0 )
1731 result_is_zero = 1;
1732
1733 for( j = B->n; j > 0; j-- )
1734 if( B->p[j - 1] != 0 )
1735 break;
1736 if( j == 0 )
1737 result_is_zero = 1;
1738
1739 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i + j ) );
1740 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );
1741
1742 for( ; j > 0; j-- )
1743 mpi_mul_hlp( i, A->p, X->p + j - 1, B->p[j - 1] );
1744
1745 /* 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;
1753
1754 cleanup:
1755
1756 mbedtls_mpi_free( &TB ); mbedtls_mpi_free( &TA );
1757
1758 return( ret );
1759 }
1760
1761 /*
1762 * Baseline multiplication: X = A * b
1763 */
mbedtls_mpi_mul_int(mbedtls_mpi * X,const mbedtls_mpi * A,mbedtls_mpi_uint b)1764 int mbedtls_mpi_mul_int( mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_uint b )
1765 {
1766 MPI_VALIDATE_RET( X != NULL );
1767 MPI_VALIDATE_RET( A != NULL );
1768
1769 /* 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;
1773
1774 /* 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
1795 cleanup:
1796 return( ret );
1797 }
1798
1799 /*
1800 * Unsigned integer divide - double mbedtls_mpi_uint dividend, u1/u0, and
1801 * mbedtls_mpi_uint divisor, d
1802 */
mbedtls_int_div_int(mbedtls_mpi_uint u1,mbedtls_mpi_uint u0,mbedtls_mpi_uint d,mbedtls_mpi_uint * r)1803 static 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 */
mbedtls_mpi_div_mpi(mbedtls_mpi * Q,mbedtls_mpi * R,const mbedtls_mpi * A,const mbedtls_mpi * B)1898 int mbedtls_mpi_div_mpi( mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A,
1899 const mbedtls_mpi *B )
1900 {
1901 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1902 size_t i, n, t, k;
1903 mbedtls_mpi X, Y, Z, T1, T2;
1904 mbedtls_mpi_uint TP2[3];
1905 MPI_VALIDATE_RET( A != NULL );
1906 MPI_VALIDATE_RET( B != NULL );
1907
1908 if( mbedtls_mpi_cmp_int( B, 0 ) == 0 )
1909 return( MBEDTLS_ERR_MPI_DIVISION_BY_ZERO );
1910
1911 mbedtls_mpi_init( &X ); mbedtls_mpi_init( &Y ); mbedtls_mpi_init( &Z );
1912 mbedtls_mpi_init( &T1 );
1913 /*
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;
1923
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 ) );
1937 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &T1, A->n + 2 ) );
1938
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
1969 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
1973 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] ) );
1982 }
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
2014 cleanup:
2015
2016 mbedtls_mpi_free( &X ); mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &Z );
2017 mbedtls_mpi_free( &T1 );
2018 mbedtls_platform_zeroize( TP2, sizeof( TP2 ) );
2019
2020 return( ret );
2021 }
2022
2023 /*
2024 * Division by int: A = Q * b + R
2025 */
mbedtls_mpi_div_int(mbedtls_mpi * Q,mbedtls_mpi * R,const mbedtls_mpi * A,mbedtls_mpi_sint b)2026 int mbedtls_mpi_div_int( mbedtls_mpi *Q, mbedtls_mpi *R,
2027 const mbedtls_mpi *A,
2028 mbedtls_mpi_sint b )
2029 {
2030 mbedtls_mpi B;
2031 mbedtls_mpi_uint p[1];
2032 MPI_VALIDATE_RET( A != NULL );
2033
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 */
mbedtls_mpi_mod_mpi(mbedtls_mpi * R,const mbedtls_mpi * A,const mbedtls_mpi * B)2045 int mbedtls_mpi_mod_mpi( mbedtls_mpi *R, const mbedtls_mpi *A, const mbedtls_mpi *B )
2046 {
2047 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2048 MPI_VALIDATE_RET( R != NULL );
2049 MPI_VALIDATE_RET( A != NULL );
2050 MPI_VALIDATE_RET( B != NULL );
2051
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
2063 cleanup:
2064
2065 return( ret );
2066 }
2067
2068 /*
2069 * Modulo: r = A mod b
2070 */
mbedtls_mpi_mod_int(mbedtls_mpi_uint * r,const mbedtls_mpi * A,mbedtls_mpi_sint b)2071 int 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;
2075 MPI_VALIDATE_RET( r != NULL );
2076 MPI_VALIDATE_RET( A != NULL );
2077
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 */
mpi_montg_init(mbedtls_mpi_uint * mm,const mbedtls_mpi * N)2130 static void mpi_montg_init( mbedtls_mpi_uint *mm, const mbedtls_mpi *N )
2131 {
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
2144 /** Montgomery multiplication: A = A * B * R^-1 mod N (HAC 14.36)
2145 *
2146 * \param[in,out] A One of the numbers to multiply.
2147 * It must have at least as many limbs as N
2148 * (A->n >= N->n), and any limbs beyond n are ignored.
2149 * On successful completion, A contains the result of
2150 * the multiplication A * B * R^-1 mod N where
2151 * R = (2^ciL)^n.
2152 * \param[in] B One of the numbers to multiply.
2153 * It must be nonzero and must not have more limbs than N
2154 * (B->n <= N->n).
2155 * \param[in] N The modulo. N must be odd.
2156 * \param mm The value calculated by `mpi_montg_init(&mm, N)`.
2157 * This is -N^-1 mod 2^ciL.
2158 * \param[in,out] T A bignum for temporary storage.
2159 * It must be at least twice the limb size of N plus 2
2160 * (T->n >= 2 * (N->n + 1)).
2161 * Its initial content is unused and
2162 * its final content is indeterminate.
2163 * Note that unlike the usual convention in the library
2164 * for `const mbedtls_mpi*`, the content of T can change.
2165 */
mpi_montmul(mbedtls_mpi * A,const mbedtls_mpi * B,const mbedtls_mpi * N,mbedtls_mpi_uint mm,const mbedtls_mpi * T)2166 static void mpi_montmul( mbedtls_mpi *A, const mbedtls_mpi *B, const mbedtls_mpi *N, mbedtls_mpi_uint mm,
2167 const mbedtls_mpi *T )
2168 {
2169 size_t i, n, m;
2170 mbedtls_mpi_uint u0, u1, *d;
2171
2172 memset( T->p, 0, T->n * ciL );
2173
2174 d = T->p;
2175 n = N->n;
2176 m = ( B->n < n ) ? B->n : n;
2177
2178 for( i = 0; i < n; i++ )
2179 {
2180 /*
2181 * T = (T + u0*B + u1*N) / 2^biL
2182 */
2183 u0 = A->p[i];
2184 u1 = ( d[0] + u0 * B->p[0] ) * mm;
2185
2186 mpi_mul_hlp( m, B->p, d, u0 );
2187 mpi_mul_hlp( n, N->p, d, u1 );
2188
2189 *d++ = u0; d[n + 1] = 0;
2190 }
2191
2192 /* At this point, d is either the desired result or the desired result
2193 * plus N. We now potentially subtract N, avoiding leaking whether the
2194 * subtraction is performed through side channels. */
2195
2196 /* Copy the n least significant limbs of d to A, so that
2197 * A = d if d < N (recall that N has n limbs). */
2198 memcpy( A->p, d, n * ciL );
2199 /* If d >= N then we want to set A to d - N. To prevent timing attacks,
2200 * do the calculation without using conditional tests. */
2201 /* Set d to d0 + (2^biL)^n - N where d0 is the current value of d. */
2202 d[n] += 1;
2203 d[n] -= mpi_sub_hlp( n, d, d, N->p );
2204 /* If d0 < N then d < (2^biL)^n
2205 * so d[n] == 0 and we want to keep A as it is.
2206 * If d0 >= N then d >= (2^biL)^n, and d <= (2^biL)^n + N < 2 * (2^biL)^n
2207 * so d[n] == 1 and we want to set A to the result of the subtraction
2208 * which is d - (2^biL)^n, i.e. the n least significant limbs of d.
2209 * This exactly corresponds to a conditional assignment. */
2210 mpi_safe_cond_assign( n, A->p, d, (unsigned char) d[n] );
2211 }
2212
2213 /*
2214 * Montgomery reduction: A = A * R^-1 mod N
2215 *
2216 * See mpi_montmul() regarding constraints and guarantees on the parameters.
2217 */
mpi_montred(mbedtls_mpi * A,const mbedtls_mpi * N,mbedtls_mpi_uint mm,const mbedtls_mpi * T)2218 static void mpi_montred( mbedtls_mpi *A, const mbedtls_mpi *N,
2219 mbedtls_mpi_uint mm, const mbedtls_mpi *T )
2220 {
2221 mbedtls_mpi_uint z = 1;
2222 mbedtls_mpi U;
2223
2224 U.n = U.s = (int) z;
2225 U.p = &z;
2226
2227 mpi_montmul( A, &U, N, mm, T );
2228 }
2229
2230 /*
2231 * Constant-flow boolean "equal" comparison:
2232 * return x == y
2233 *
2234 * This function can be used to write constant-time code by replacing branches
2235 * with bit operations - it can be used in conjunction with
2236 * mbedtls_ssl_cf_mask_from_bit().
2237 *
2238 * This function is implemented without using comparison operators, as those
2239 * might be translated to branches by some compilers on some platforms.
2240 */
mbedtls_mpi_cf_bool_eq(size_t x,size_t y)2241 static size_t mbedtls_mpi_cf_bool_eq( size_t x, size_t y )
2242 {
2243 /* diff = 0 if x == y, non-zero otherwise */
2244 const size_t diff = x ^ y;
2245
2246 /* MSVC has a warning about unary minus on unsigned integer types,
2247 * but this is well-defined and precisely what we want to do here. */
2248 #if defined(_MSC_VER)
2249 #pragma warning( push )
2250 #pragma warning( disable : 4146 )
2251 #endif
2252
2253 /* diff_msb's most significant bit is equal to x != y */
2254 const size_t diff_msb = ( diff | (size_t) -diff );
2255
2256 #if defined(_MSC_VER)
2257 #pragma warning( pop )
2258 #endif
2259
2260 /* diff1 = (x != y) ? 1 : 0 */
2261 const size_t diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 );
2262
2263 return( 1 ^ diff1 );
2264 }
2265
2266 /**
2267 * Select an MPI from a table without leaking the index.
2268 *
2269 * This is functionally equivalent to mbedtls_mpi_copy(R, T[idx]) except it
2270 * reads the entire table in order to avoid leaking the value of idx to an
2271 * attacker able to observe memory access patterns.
2272 *
2273 * \param[out] R Where to write the selected MPI.
2274 * \param[in] T The table to read from.
2275 * \param[in] T_size The number of elements in the table.
2276 * \param[in] idx The index of the element to select;
2277 * this must satisfy 0 <= idx < T_size.
2278 *
2279 * \return \c 0 on success, or a negative error code.
2280 */
mpi_select(mbedtls_mpi * R,const mbedtls_mpi * T,size_t T_size,size_t idx)2281 static int mpi_select( mbedtls_mpi *R, const mbedtls_mpi *T, size_t T_size, size_t idx )
2282 {
2283 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2284
2285 for( size_t i = 0; i < T_size; i++ )
2286 {
2287 MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( R, &T[i],
2288 (unsigned char) mbedtls_mpi_cf_bool_eq( i, idx ) ) );
2289 }
2290
2291 cleanup:
2292 return( ret );
2293 }
2294
2295 /*
2296 * Sliding-window exponentiation: X = A^E mod N (HAC 14.85)
2297 */
mbedtls_mpi_exp_mod(mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * E,const mbedtls_mpi * N,mbedtls_mpi * prec_RR)2298 int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A,
2299 const mbedtls_mpi *E, const mbedtls_mpi *N,
2300 mbedtls_mpi *prec_RR )
2301 {
2302 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2303 size_t wbits, wsize, one = 1;
2304 size_t i, j, nblimbs;
2305 size_t bufsize, nbits;
2306 mbedtls_mpi_uint ei, mm, state;
2307 mbedtls_mpi RR, T, W[ 1 << MBEDTLS_MPI_WINDOW_SIZE ], WW, Apos;
2308 int neg;
2309
2310 MPI_VALIDATE_RET( X != NULL );
2311 MPI_VALIDATE_RET( A != NULL );
2312 MPI_VALIDATE_RET( E != NULL );
2313 MPI_VALIDATE_RET( N != NULL );
2314
2315 if( mbedtls_mpi_cmp_int( N, 0 ) <= 0 || ( N->p[0] & 1 ) == 0 )
2316 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2317
2318 if( mbedtls_mpi_cmp_int( E, 0 ) < 0 )
2319 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2320
2321 if( mbedtls_mpi_bitlen( E ) > MBEDTLS_MPI_MAX_BITS ||
2322 mbedtls_mpi_bitlen( N ) > MBEDTLS_MPI_MAX_BITS )
2323 return ( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2324
2325 /*
2326 * Init temps and window size
2327 */
2328 mpi_montg_init( &mm, N );
2329 mbedtls_mpi_init( &RR ); mbedtls_mpi_init( &T );
2330 mbedtls_mpi_init( &Apos );
2331 mbedtls_mpi_init( &WW );
2332 memset( W, 0, sizeof( W ) );
2333
2334 i = mbedtls_mpi_bitlen( E );
2335
2336 wsize = ( i > 671 ) ? 6 : ( i > 239 ) ? 5 :
2337 ( i > 79 ) ? 4 : ( i > 23 ) ? 3 : 1;
2338
2339 #if( MBEDTLS_MPI_WINDOW_SIZE < 6 )
2340 if( wsize > MBEDTLS_MPI_WINDOW_SIZE )
2341 wsize = MBEDTLS_MPI_WINDOW_SIZE;
2342 #endif
2343
2344 j = N->n + 1;
2345 /* All W[i] and X must have at least N->n limbs for the mpi_montmul()
2346 * and mpi_montred() calls later. Here we ensure that W[1] and X are
2347 * large enough, and later we'll grow other W[i] to the same length.
2348 * They must not be shrunk midway through this function!
2349 */
2350 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, j ) );
2351 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[1], j ) );
2352 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &T, j * 2 ) );
2353
2354 /*
2355 * Compensate for negative A (and correct at the end)
2356 */
2357 neg = ( A->s == -1 );
2358 if( neg )
2359 {
2360 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Apos, A ) );
2361 Apos.s = 1;
2362 A = &Apos;
2363 }
2364
2365 /*
2366 * If 1st call, pre-compute R^2 mod N
2367 */
2368 if( prec_RR == NULL || prec_RR->p == NULL )
2369 {
2370 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &RR, 1 ) );
2371 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &RR, N->n * 2 * biL ) );
2372 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &RR, &RR, N ) );
2373
2374 if( prec_RR != NULL )
2375 memcpy( prec_RR, &RR, sizeof( mbedtls_mpi ) );
2376 }
2377 else
2378 memcpy( &RR, prec_RR, sizeof( mbedtls_mpi ) );
2379
2380 /*
2381 * W[1] = A * R^2 * R^-1 mod N = A * R mod N
2382 */
2383 if( mbedtls_mpi_cmp_mpi( A, N ) >= 0 )
2384 {
2385 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &W[1], A, N ) );
2386 /* This should be a no-op because W[1] is already that large before
2387 * mbedtls_mpi_mod_mpi(), but it's necessary to avoid an overflow
2388 * in mpi_montmul() below, so let's make sure. */
2389 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[1], N->n + 1 ) );
2390 }
2391 else
2392 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[1], A ) );
2393
2394 /* Note that this is safe because W[1] always has at least N->n limbs
2395 * (it grew above and was preserved by mbedtls_mpi_copy()). */
2396 mpi_montmul( &W[1], &RR, N, mm, &T );
2397
2398 /*
2399 * X = R^2 * R^-1 mod N = R mod N
2400 */
2401 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, &RR ) );
2402 mpi_montred( X, N, mm, &T );
2403
2404 if( wsize > 1 )
2405 {
2406 /*
2407 * W[1 << (wsize - 1)] = W[1] ^ (wsize - 1)
2408 */
2409 j = one << ( wsize - 1 );
2410
2411 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[j], N->n + 1 ) );
2412 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[j], &W[1] ) );
2413
2414 for( i = 0; i < wsize - 1; i++ )
2415 mpi_montmul( &W[j], &W[j], N, mm, &T );
2416
2417 /*
2418 * W[i] = W[i - 1] * W[1]
2419 */
2420 for( i = j + 1; i < ( one << wsize ); i++ )
2421 {
2422 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[i], N->n + 1 ) );
2423 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[i], &W[i - 1] ) );
2424
2425 mpi_montmul( &W[i], &W[1], N, mm, &T );
2426 }
2427 }
2428
2429 nblimbs = E->n;
2430 bufsize = 0;
2431 nbits = 0;
2432 wbits = 0;
2433 state = 0;
2434
2435 while( 1 )
2436 {
2437 if( bufsize == 0 )
2438 {
2439 if( nblimbs == 0 )
2440 break;
2441
2442 nblimbs--;
2443
2444 bufsize = sizeof( mbedtls_mpi_uint ) << 3;
2445 }
2446
2447 bufsize--;
2448
2449 ei = (E->p[nblimbs] >> bufsize) & 1;
2450
2451 /*
2452 * skip leading 0s
2453 */
2454 if( ei == 0 && state == 0 )
2455 continue;
2456
2457 if( ei == 0 && state == 1 )
2458 {
2459 /*
2460 * out of window, square X
2461 */
2462 mpi_montmul( X, X, N, mm, &T );
2463 continue;
2464 }
2465
2466 /*
2467 * add ei to current window
2468 */
2469 state = 2;
2470
2471 nbits++;
2472 wbits |= ( ei << ( wsize - nbits ) );
2473
2474 if( nbits == wsize )
2475 {
2476 /*
2477 * X = X^wsize R^-1 mod N
2478 */
2479 for( i = 0; i < wsize; i++ )
2480 mpi_montmul( X, X, N, mm, &T );
2481
2482 /*
2483 * X = X * W[wbits] R^-1 mod N
2484 */
2485 MBEDTLS_MPI_CHK( mpi_select( &WW, W, (size_t) 1 << wsize, wbits ) );
2486 mpi_montmul( X, &WW, N, mm, &T );
2487
2488 state--;
2489 nbits = 0;
2490 wbits = 0;
2491 }
2492 }
2493
2494 /*
2495 * process the remaining bits
2496 */
2497 for( i = 0; i < nbits; i++ )
2498 {
2499 mpi_montmul( X, X, N, mm, &T );
2500
2501 wbits <<= 1;
2502
2503 if( ( wbits & ( one << wsize ) ) != 0 )
2504 mpi_montmul( X, &W[1], N, mm, &T );
2505 }
2506
2507 /*
2508 * X = A^E * R * R^-1 mod N = A^E mod N
2509 */
2510 mpi_montred( X, N, mm, &T );
2511
2512 if( neg && E->n != 0 && ( E->p[0] & 1 ) != 0 )
2513 {
2514 X->s = -1;
2515 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( X, N, X ) );
2516 }
2517
2518 cleanup:
2519
2520 for( i = ( one << ( wsize - 1 ) ); i < ( one << wsize ); i++ )
2521 mbedtls_mpi_free( &W[i] );
2522
2523 mbedtls_mpi_free( &W[1] ); mbedtls_mpi_free( &T ); mbedtls_mpi_free( &Apos );
2524 mbedtls_mpi_free( &WW );
2525
2526 if( prec_RR == NULL || prec_RR->p == NULL )
2527 mbedtls_mpi_free( &RR );
2528
2529 return( ret );
2530 }
2531
2532 /*
2533 * Greatest common divisor: G = gcd(A, B) (HAC 14.54)
2534 */
mbedtls_mpi_gcd(mbedtls_mpi * G,const mbedtls_mpi * A,const mbedtls_mpi * B)2535 int mbedtls_mpi_gcd( mbedtls_mpi *G, const mbedtls_mpi *A, const mbedtls_mpi *B )
2536 {
2537 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2538 size_t lz, lzt;
2539 mbedtls_mpi TA, TB;
2540
2541 MPI_VALIDATE_RET( G != NULL );
2542 MPI_VALIDATE_RET( A != NULL );
2543 MPI_VALIDATE_RET( B != NULL );
2544
2545 mbedtls_mpi_init( &TA ); mbedtls_mpi_init( &TB );
2546
2547 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TA, A ) );
2548 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, B ) );
2549
2550 lz = mbedtls_mpi_lsb( &TA );
2551 lzt = mbedtls_mpi_lsb( &TB );
2552
2553 /* The loop below gives the correct result when A==0 but not when B==0.
2554 * So have a special case for B==0. Leverage the fact that we just
2555 * calculated the lsb and lsb(B)==0 iff B is odd or 0 to make the test
2556 * slightly more efficient than cmp_int(). */
2557 if( lzt == 0 && mbedtls_mpi_get_bit( &TB, 0 ) == 0 )
2558 {
2559 ret = mbedtls_mpi_copy( G, A );
2560 goto cleanup;
2561 }
2562
2563 if( lzt < lz )
2564 lz = lzt;
2565
2566 TA.s = TB.s = 1;
2567
2568 /* We mostly follow the procedure described in HAC 14.54, but with some
2569 * minor differences:
2570 * - Sequences of multiplications or divisions by 2 are grouped into a
2571 * single shift operation.
2572 * - The procedure in HAC assumes that 0 < TB <= TA.
2573 * - The condition TB <= TA is not actually necessary for correctness.
2574 * TA and TB have symmetric roles except for the loop termination
2575 * condition, and the shifts at the beginning of the loop body
2576 * remove any significance from the ordering of TA vs TB before
2577 * the shifts.
2578 * - If TA = 0, the loop goes through 0 iterations and the result is
2579 * correctly TB.
2580 * - The case TB = 0 was short-circuited above.
2581 *
2582 * For the correctness proof below, decompose the original values of
2583 * A and B as
2584 * A = sa * 2^a * A' with A'=0 or A' odd, and sa = +-1
2585 * B = sb * 2^b * B' with B'=0 or B' odd, and sb = +-1
2586 * Then gcd(A, B) = 2^{min(a,b)} * gcd(A',B'),
2587 * and gcd(A',B') is odd or 0.
2588 *
2589 * At the beginning, we have TA = |A| and TB = |B| so gcd(A,B) = gcd(TA,TB).
2590 * The code maintains the following invariant:
2591 * gcd(A,B) = 2^k * gcd(TA,TB) for some k (I)
2592 */
2593
2594 /* Proof that the loop terminates:
2595 * At each iteration, either the right-shift by 1 is made on a nonzero
2596 * value and the nonnegative integer bitlen(TA) + bitlen(TB) decreases
2597 * by at least 1, or the right-shift by 1 is made on zero and then
2598 * TA becomes 0 which ends the loop (TB cannot be 0 if it is right-shifted
2599 * since in that case TB is calculated from TB-TA with the condition TB>TA).
2600 */
2601 while( mbedtls_mpi_cmp_int( &TA, 0 ) != 0 )
2602 {
2603 /* Divisions by 2 preserve the invariant (I). */
2604 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TA, mbedtls_mpi_lsb( &TA ) ) );
2605 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TB, mbedtls_mpi_lsb( &TB ) ) );
2606
2607 /* Set either TA or TB to |TA-TB|/2. Since TA and TB are both odd,
2608 * TA-TB is even so the division by 2 has an integer result.
2609 * Invariant (I) is preserved since any odd divisor of both TA and TB
2610 * also divides |TA-TB|/2, and any odd divisor of both TA and |TA-TB|/2
2611 * also divides TB, and any odd divisior of both TB and |TA-TB|/2 also
2612 * divides TA.
2613 */
2614 if( mbedtls_mpi_cmp_mpi( &TA, &TB ) >= 0 )
2615 {
2616 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &TA, &TA, &TB ) );
2617 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TA, 1 ) );
2618 }
2619 else
2620 {
2621 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &TB, &TB, &TA ) );
2622 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TB, 1 ) );
2623 }
2624 /* Note that one of TA or TB is still odd. */
2625 }
2626
2627 /* By invariant (I), gcd(A,B) = 2^k * gcd(TA,TB) for some k.
2628 * At the loop exit, TA = 0, so gcd(TA,TB) = TB.
2629 * - If there was at least one loop iteration, then one of TA or TB is odd,
2630 * and TA = 0, so TB is odd and gcd(TA,TB) = gcd(A',B'). In this case,
2631 * lz = min(a,b) so gcd(A,B) = 2^lz * TB.
2632 * - If there was no loop iteration, then A was 0, and gcd(A,B) = B.
2633 * In this case, lz = 0 and B = TB so gcd(A,B) = B = 2^lz * TB as well.
2634 */
2635
2636 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &TB, lz ) );
2637 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( G, &TB ) );
2638
2639 cleanup:
2640
2641 mbedtls_mpi_free( &TA ); mbedtls_mpi_free( &TB );
2642
2643 return( ret );
2644 }
2645
2646 /* Fill X with n_bytes random bytes.
2647 * X must already have room for those bytes.
2648 * The ordering of the bytes returned from the RNG is suitable for
2649 * deterministic ECDSA (see RFC 6979 §3.3 and mbedtls_mpi_random()).
2650 * The size and sign of X are unchanged.
2651 * n_bytes must not be 0.
2652 */
mpi_fill_random_internal(mbedtls_mpi * X,size_t n_bytes,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)2653 static int mpi_fill_random_internal(
2654 mbedtls_mpi *X, size_t n_bytes,
2655 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
2656 {
2657 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2658 const size_t limbs = CHARS_TO_LIMBS( n_bytes );
2659 const size_t overhead = ( limbs * ciL ) - n_bytes;
2660
2661 if( X->n < limbs )
2662 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2663
2664 memset( X->p, 0, overhead );
2665 memset( (unsigned char *) X->p + limbs * ciL, 0, ( X->n - limbs ) * ciL );
2666 MBEDTLS_MPI_CHK( f_rng( p_rng, (unsigned char *) X->p + overhead, n_bytes ) );
2667 mpi_bigendian_to_host( X->p, limbs );
2668
2669 cleanup:
2670 return( ret );
2671 }
2672
2673 /*
2674 * Fill X with size bytes of random.
2675 *
2676 * Use a temporary bytes representation to make sure the result is the same
2677 * regardless of the platform endianness (useful when f_rng is actually
2678 * deterministic, eg for tests).
2679 */
mbedtls_mpi_fill_random(mbedtls_mpi * X,size_t size,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)2680 int mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size,
2681 int (*f_rng)(void *, unsigned char *, size_t),
2682 void *p_rng )
2683 {
2684 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2685 size_t const limbs = CHARS_TO_LIMBS( size );
2686
2687 MPI_VALIDATE_RET( X != NULL );
2688 MPI_VALIDATE_RET( f_rng != NULL );
2689
2690 /* Ensure that target MPI has exactly the necessary number of limbs */
2691 MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, limbs ) );
2692 if( size == 0 )
2693 return( 0 );
2694
2695 ret = mpi_fill_random_internal( X, size, f_rng, p_rng );
2696
2697 cleanup:
2698 return( ret );
2699 }
2700
mbedtls_mpi_random(mbedtls_mpi * X,mbedtls_mpi_sint min,const mbedtls_mpi * N,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)2701 int mbedtls_mpi_random( mbedtls_mpi *X,
2702 mbedtls_mpi_sint min,
2703 const mbedtls_mpi *N,
2704 int (*f_rng)(void *, unsigned char *, size_t),
2705 void *p_rng )
2706 {
2707 int ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
2708 int count;
2709 unsigned lt_lower = 1, lt_upper = 0;
2710 size_t n_bits = mbedtls_mpi_bitlen( N );
2711 size_t n_bytes = ( n_bits + 7 ) / 8;
2712 mbedtls_mpi lower_bound;
2713
2714 if( min < 0 )
2715 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2716 if( mbedtls_mpi_cmp_int( N, min ) <= 0 )
2717 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2718
2719 /*
2720 * When min == 0, each try has at worst a probability 1/2 of failing
2721 * (the msb has a probability 1/2 of being 0, and then the result will
2722 * be < N), so after 30 tries failure probability is a most 2**(-30).
2723 *
2724 * When N is just below a power of 2, as is the case when generating
2725 * a random scalar on most elliptic curves, 1 try is enough with
2726 * overwhelming probability. When N is just above a power of 2,
2727 * as when generating a random scalar on secp224k1, each try has
2728 * a probability of failing that is almost 1/2.
2729 *
2730 * The probabilities are almost the same if min is nonzero but negligible
2731 * compared to N. This is always the case when N is crypto-sized, but
2732 * it's convenient to support small N for testing purposes. When N
2733 * is small, use a higher repeat count, otherwise the probability of
2734 * failure is macroscopic.
2735 */
2736 count = ( n_bytes > 4 ? 30 : 250 );
2737
2738 mbedtls_mpi_init( &lower_bound );
2739
2740 /* Ensure that target MPI has exactly the same number of limbs
2741 * as the upper bound, even if the upper bound has leading zeros.
2742 * This is necessary for the mbedtls_mpi_lt_mpi_ct() check. */
2743 MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, N->n ) );
2744 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &lower_bound, N->n ) );
2745 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &lower_bound, min ) );
2746
2747 /*
2748 * Match the procedure given in RFC 6979 §3.3 (deterministic ECDSA)
2749 * when f_rng is a suitably parametrized instance of HMAC_DRBG:
2750 * - use the same byte ordering;
2751 * - keep the leftmost n_bits bits of the generated octet string;
2752 * - try until result is in the desired range.
2753 * This also avoids any bias, which is especially important for ECDSA.
2754 */
2755 do
2756 {
2757 MBEDTLS_MPI_CHK( mpi_fill_random_internal( X, n_bytes, f_rng, p_rng ) );
2758 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( X, 8 * n_bytes - n_bits ) );
2759
2760 if( --count == 0 )
2761 {
2762 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2763 goto cleanup;
2764 }
2765
2766 MBEDTLS_MPI_CHK( mbedtls_mpi_lt_mpi_ct( X, &lower_bound, <_lower ) );
2767 MBEDTLS_MPI_CHK( mbedtls_mpi_lt_mpi_ct( X, N, <_upper ) );
2768 }
2769 while( lt_lower != 0 || lt_upper == 0 );
2770
2771 cleanup:
2772 mbedtls_mpi_free( &lower_bound );
2773 return( ret );
2774 }
2775
2776 /*
2777 * Modular inverse: X = A^-1 mod N (HAC 14.61 / 14.64)
2778 */
mbedtls_mpi_inv_mod(mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * N)2779 int mbedtls_mpi_inv_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *N )
2780 {
2781 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2782 mbedtls_mpi G, TA, TU, U1, U2, TB, TV, V1, V2;
2783 MPI_VALIDATE_RET( X != NULL );
2784 MPI_VALIDATE_RET( A != NULL );
2785 MPI_VALIDATE_RET( N != NULL );
2786
2787 if( mbedtls_mpi_cmp_int( N, 1 ) <= 0 )
2788 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
2789
2790 mbedtls_mpi_init( &TA ); mbedtls_mpi_init( &TU ); mbedtls_mpi_init( &U1 ); mbedtls_mpi_init( &U2 );
2791 mbedtls_mpi_init( &G ); mbedtls_mpi_init( &TB ); mbedtls_mpi_init( &TV );
2792 mbedtls_mpi_init( &V1 ); mbedtls_mpi_init( &V2 );
2793
2794 MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, A, N ) );
2795
2796 if( mbedtls_mpi_cmp_int( &G, 1 ) != 0 )
2797 {
2798 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2799 goto cleanup;
2800 }
2801
2802 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &TA, A, N ) );
2803 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TU, &TA ) );
2804 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, N ) );
2805 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TV, N ) );
2806
2807 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &U1, 1 ) );
2808 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &U2, 0 ) );
2809 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &V1, 0 ) );
2810 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &V2, 1 ) );
2811
2812 do
2813 {
2814 while( ( TU.p[0] & 1 ) == 0 )
2815 {
2816 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TU, 1 ) );
2817
2818 if( ( U1.p[0] & 1 ) != 0 || ( U2.p[0] & 1 ) != 0 )
2819 {
2820 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &U1, &U1, &TB ) );
2821 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U2, &U2, &TA ) );
2822 }
2823
2824 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &U1, 1 ) );
2825 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &U2, 1 ) );
2826 }
2827
2828 while( ( TV.p[0] & 1 ) == 0 )
2829 {
2830 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TV, 1 ) );
2831
2832 if( ( V1.p[0] & 1 ) != 0 || ( V2.p[0] & 1 ) != 0 )
2833 {
2834 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &V1, &V1, &TB ) );
2835 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V2, &V2, &TA ) );
2836 }
2837
2838 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &V1, 1 ) );
2839 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &V2, 1 ) );
2840 }
2841
2842 if( mbedtls_mpi_cmp_mpi( &TU, &TV ) >= 0 )
2843 {
2844 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &TU, &TU, &TV ) );
2845 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U1, &U1, &V1 ) );
2846 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U2, &U2, &V2 ) );
2847 }
2848 else
2849 {
2850 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &TV, &TV, &TU ) );
2851 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V1, &V1, &U1 ) );
2852 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V2, &V2, &U2 ) );
2853 }
2854 }
2855 while( mbedtls_mpi_cmp_int( &TU, 0 ) != 0 );
2856
2857 while( mbedtls_mpi_cmp_int( &V1, 0 ) < 0 )
2858 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &V1, &V1, N ) );
2859
2860 while( mbedtls_mpi_cmp_mpi( &V1, N ) >= 0 )
2861 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V1, &V1, N ) );
2862
2863 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, &V1 ) );
2864
2865 cleanup:
2866
2867 mbedtls_mpi_free( &TA ); mbedtls_mpi_free( &TU ); mbedtls_mpi_free( &U1 ); mbedtls_mpi_free( &U2 );
2868 mbedtls_mpi_free( &G ); mbedtls_mpi_free( &TB ); mbedtls_mpi_free( &TV );
2869 mbedtls_mpi_free( &V1 ); mbedtls_mpi_free( &V2 );
2870
2871 return( ret );
2872 }
2873
2874 #if defined(MBEDTLS_GENPRIME)
2875
2876 static const int small_prime[] =
2877 {
2878 3, 5, 7, 11, 13, 17, 19, 23,
2879 29, 31, 37, 41, 43, 47, 53, 59,
2880 61, 67, 71, 73, 79, 83, 89, 97,
2881 101, 103, 107, 109, 113, 127, 131, 137,
2882 139, 149, 151, 157, 163, 167, 173, 179,
2883 181, 191, 193, 197, 199, 211, 223, 227,
2884 229, 233, 239, 241, 251, 257, 263, 269,
2885 271, 277, 281, 283, 293, 307, 311, 313,
2886 317, 331, 337, 347, 349, 353, 359, 367,
2887 373, 379, 383, 389, 397, 401, 409, 419,
2888 421, 431, 433, 439, 443, 449, 457, 461,
2889 463, 467, 479, 487, 491, 499, 503, 509,
2890 521, 523, 541, 547, 557, 563, 569, 571,
2891 577, 587, 593, 599, 601, 607, 613, 617,
2892 619, 631, 641, 643, 647, 653, 659, 661,
2893 673, 677, 683, 691, 701, 709, 719, 727,
2894 733, 739, 743, 751, 757, 761, 769, 773,
2895 787, 797, 809, 811, 821, 823, 827, 829,
2896 839, 853, 857, 859, 863, 877, 881, 883,
2897 887, 907, 911, 919, 929, 937, 941, 947,
2898 953, 967, 971, 977, 983, 991, 997, -103
2899 };
2900
2901 /*
2902 * Small divisors test (X must be positive)
2903 *
2904 * Return values:
2905 * 0: no small factor (possible prime, more tests needed)
2906 * 1: certain prime
2907 * MBEDTLS_ERR_MPI_NOT_ACCEPTABLE: certain non-prime
2908 * other negative: error
2909 */
mpi_check_small_factors(const mbedtls_mpi * X)2910 static int mpi_check_small_factors( const mbedtls_mpi *X )
2911 {
2912 int ret = 0;
2913 size_t i;
2914 mbedtls_mpi_uint r;
2915
2916 if( ( X->p[0] & 1 ) == 0 )
2917 return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
2918
2919 for( i = 0; small_prime[i] > 0; i++ )
2920 {
2921 if( mbedtls_mpi_cmp_int( X, small_prime[i] ) <= 0 )
2922 return( 1 );
2923
2924 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, small_prime[i] ) );
2925
2926 if( r == 0 )
2927 return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
2928 }
2929
2930 cleanup:
2931 return( ret );
2932 }
2933
2934 /*
2935 * Miller-Rabin pseudo-primality test (HAC 4.24)
2936 */
mpi_miller_rabin(const mbedtls_mpi * X,size_t rounds,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)2937 static int mpi_miller_rabin( const mbedtls_mpi *X, size_t rounds,
2938 int (*f_rng)(void *, unsigned char *, size_t),
2939 void *p_rng )
2940 {
2941 int ret, count;
2942 size_t i, j, k, s;
2943 mbedtls_mpi W, R, T, A, RR;
2944
2945 MPI_VALIDATE_RET( X != NULL );
2946 MPI_VALIDATE_RET( f_rng != NULL );
2947
2948 mbedtls_mpi_init( &W ); mbedtls_mpi_init( &R );
2949 mbedtls_mpi_init( &T ); mbedtls_mpi_init( &A );
2950 mbedtls_mpi_init( &RR );
2951
2952 /*
2953 * W = |X| - 1
2954 * R = W >> lsb( W )
2955 */
2956 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &W, X, 1 ) );
2957 s = mbedtls_mpi_lsb( &W );
2958 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R, &W ) );
2959 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &R, s ) );
2960
2961 for( i = 0; i < rounds; i++ )
2962 {
2963 /*
2964 * pick a random A, 1 < A < |X| - 1
2965 */
2966 count = 0;
2967 do {
2968 MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &A, X->n * ciL, f_rng, p_rng ) );
2969
2970 j = mbedtls_mpi_bitlen( &A );
2971 k = mbedtls_mpi_bitlen( &W );
2972 if (j > k) {
2973 A.p[A.n - 1] &= ( (mbedtls_mpi_uint) 1 << ( k - ( A.n - 1 ) * biL - 1 ) ) - 1;
2974 }
2975
2976 if (count++ > 30) {
2977 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2978 goto cleanup;
2979 }
2980
2981 } while ( mbedtls_mpi_cmp_mpi( &A, &W ) >= 0 ||
2982 mbedtls_mpi_cmp_int( &A, 1 ) <= 0 );
2983
2984 /*
2985 * A = A^R mod |X|
2986 */
2987 MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &A, &A, &R, X, &RR ) );
2988
2989 if( mbedtls_mpi_cmp_mpi( &A, &W ) == 0 ||
2990 mbedtls_mpi_cmp_int( &A, 1 ) == 0 )
2991 continue;
2992
2993 j = 1;
2994 while( j < s && mbedtls_mpi_cmp_mpi( &A, &W ) != 0 )
2995 {
2996 /*
2997 * A = A * A mod |X|
2998 */
2999 MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &A, &A ) );
3000 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &A, &T, X ) );
3001
3002 if( mbedtls_mpi_cmp_int( &A, 1 ) == 0 )
3003 break;
3004
3005 j++;
3006 }
3007
3008 /*
3009 * not prime if A != |X| - 1 or A == 1
3010 */
3011 if( mbedtls_mpi_cmp_mpi( &A, &W ) != 0 ||
3012 mbedtls_mpi_cmp_int( &A, 1 ) == 0 )
3013 {
3014 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
3015 break;
3016 }
3017 }
3018
3019 cleanup:
3020 mbedtls_mpi_free( &W ); mbedtls_mpi_free( &R );
3021 mbedtls_mpi_free( &T ); mbedtls_mpi_free( &A );
3022 mbedtls_mpi_free( &RR );
3023
3024 return( ret );
3025 }
3026
3027 /*
3028 * Pseudo-primality test: small factors, then Miller-Rabin
3029 */
mbedtls_mpi_is_prime_ext(const mbedtls_mpi * X,int rounds,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)3030 int mbedtls_mpi_is_prime_ext( const mbedtls_mpi *X, int rounds,
3031 int (*f_rng)(void *, unsigned char *, size_t),
3032 void *p_rng )
3033 {
3034 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3035 mbedtls_mpi XX;
3036 MPI_VALIDATE_RET( X != NULL );
3037 MPI_VALIDATE_RET( f_rng != NULL );
3038
3039 XX.s = 1;
3040 XX.n = X->n;
3041 XX.p = X->p;
3042
3043 if( mbedtls_mpi_cmp_int( &XX, 0 ) == 0 ||
3044 mbedtls_mpi_cmp_int( &XX, 1 ) == 0 )
3045 return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
3046
3047 if( mbedtls_mpi_cmp_int( &XX, 2 ) == 0 )
3048 return( 0 );
3049
3050 if( ( ret = mpi_check_small_factors( &XX ) ) != 0 )
3051 {
3052 if( ret == 1 )
3053 return( 0 );
3054
3055 return( ret );
3056 }
3057
3058 return( mpi_miller_rabin( &XX, rounds, f_rng, p_rng ) );
3059 }
3060
3061 /*
3062 * Prime number generation
3063 *
3064 * To generate an RSA key in a way recommended by FIPS 186-4, both primes must
3065 * be either 1024 bits or 1536 bits long, and flags must contain
3066 * MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR.
3067 */
mbedtls_mpi_gen_prime(mbedtls_mpi * X,size_t nbits,int flags,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)3068 int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int flags,
3069 int (*f_rng)(void *, unsigned char *, size_t),
3070 void *p_rng )
3071 {
3072 #ifdef MBEDTLS_HAVE_INT64
3073 // ceil(2^63.5)
3074 #define CEIL_MAXUINT_DIV_SQRT2 0xb504f333f9de6485ULL
3075 #else
3076 // ceil(2^31.5)
3077 #define CEIL_MAXUINT_DIV_SQRT2 0xb504f334U
3078 #endif
3079 int ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
3080 size_t k, n;
3081 int rounds;
3082 mbedtls_mpi_uint r;
3083 mbedtls_mpi Y;
3084
3085 MPI_VALIDATE_RET( X != NULL );
3086 MPI_VALIDATE_RET( f_rng != NULL );
3087
3088 if( nbits < 3 || nbits > MBEDTLS_MPI_MAX_BITS )
3089 return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
3090
3091 mbedtls_mpi_init( &Y );
3092
3093 n = BITS_TO_LIMBS( nbits );
3094
3095 if( ( flags & MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR ) == 0 )
3096 {
3097 /*
3098 * 2^-80 error probability, number of rounds chosen per HAC, table 4.4
3099 */
3100 rounds = ( ( nbits >= 1300 ) ? 2 : ( nbits >= 850 ) ? 3 :
3101 ( nbits >= 650 ) ? 4 : ( nbits >= 350 ) ? 8 :
3102 ( nbits >= 250 ) ? 12 : ( nbits >= 150 ) ? 18 : 27 );
3103 }
3104 else
3105 {
3106 /*
3107 * 2^-100 error probability, number of rounds computed based on HAC,
3108 * fact 4.48
3109 */
3110 rounds = ( ( nbits >= 1450 ) ? 4 : ( nbits >= 1150 ) ? 5 :
3111 ( nbits >= 1000 ) ? 6 : ( nbits >= 850 ) ? 7 :
3112 ( nbits >= 750 ) ? 8 : ( nbits >= 500 ) ? 13 :
3113 ( nbits >= 250 ) ? 28 : ( nbits >= 150 ) ? 40 : 51 );
3114 }
3115
3116 while( 1 )
3117 {
3118 MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( X, n * ciL, f_rng, p_rng ) );
3119 /* make sure generated number is at least (nbits-1)+0.5 bits (FIPS 186-4 §B.3.3 steps 4.4, 5.5) */
3120 if( X->p[n-1] < CEIL_MAXUINT_DIV_SQRT2 ) continue;
3121
3122 k = n * biL;
3123 if( k > nbits ) MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( X, k - nbits ) );
3124 X->p[0] |= 1;
3125
3126 if( ( flags & MBEDTLS_MPI_GEN_PRIME_FLAG_DH ) == 0 )
3127 {
3128 ret = mbedtls_mpi_is_prime_ext( X, rounds, f_rng, p_rng );
3129
3130 if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
3131 goto cleanup;
3132 }
3133 else
3134 {
3135 /*
3136 * An necessary condition for Y and X = 2Y + 1 to be prime
3137 * is X = 2 mod 3 (which is equivalent to Y = 2 mod 3).
3138 * Make sure it is satisfied, while keeping X = 3 mod 4
3139 */
3140
3141 X->p[0] |= 2;
3142
3143 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, 3 ) );
3144 if( r == 0 )
3145 MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 8 ) );
3146 else if( r == 1 )
3147 MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 4 ) );
3148
3149 /* Set Y = (X-1) / 2, which is X / 2 because X is odd */
3150 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Y, X ) );
3151 MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &Y, 1 ) );
3152
3153 while( 1 )
3154 {
3155 /*
3156 * First, check small factors for X and Y
3157 * before doing Miller-Rabin on any of them
3158 */
3159 if( ( ret = mpi_check_small_factors( X ) ) == 0 &&
3160 ( ret = mpi_check_small_factors( &Y ) ) == 0 &&
3161 ( ret = mpi_miller_rabin( X, rounds, f_rng, p_rng ) )
3162 == 0 &&
3163 ( ret = mpi_miller_rabin( &Y, rounds, f_rng, p_rng ) )
3164 == 0 )
3165 goto cleanup;
3166
3167 if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
3168 goto cleanup;
3169
3170 /*
3171 * Next candidates. We want to preserve Y = (X-1) / 2 and
3172 * Y = 1 mod 2 and Y = 2 mod 3 (eq X = 3 mod 4 and X = 2 mod 3)
3173 * so up Y by 6 and X by 12.
3174 */
3175 MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 12 ) );
3176 MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &Y, &Y, 6 ) );
3177 }
3178 }
3179 }
3180
3181 cleanup:
3182
3183 mbedtls_mpi_free( &Y );
3184
3185 return( ret );
3186 }
3187
3188 #endif /* MBEDTLS_GENPRIME */
3189
3190 #if defined(MBEDTLS_SELF_TEST)
3191
3192 #define GCD_PAIR_COUNT 3
3193
3194 static const int gcd_pairs[GCD_PAIR_COUNT][3] =
3195 {
3196 { 693, 609, 21 },
3197 { 1764, 868, 28 },
3198 { 768454923, 542167814, 1 }
3199 };
3200
3201 /*
3202 * Checkup routine
3203 */
mbedtls_mpi_self_test(int verbose)3204 int mbedtls_mpi_self_test( int verbose )
3205 {
3206 int ret, i;
3207 mbedtls_mpi A, E, N, X, Y, U, V;
3208
3209 mbedtls_mpi_init( &A ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &N ); mbedtls_mpi_init( &X );
3210 mbedtls_mpi_init( &Y ); mbedtls_mpi_init( &U ); mbedtls_mpi_init( &V );
3211
3212 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &A, 16,
3213 "EFE021C2645FD1DC586E69184AF4A31E" \
3214 "D5F53E93B5F123FA41680867BA110131" \
3215 "944FE7952E2517337780CB0DB80E61AA" \
3216 "E7C8DDC6C5C6AADEB34EB38A2F40D5E6" ) );
3217
3218 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &E, 16,
3219 "B2E7EFD37075B9F03FF989C7C5051C20" \
3220 "34D2A323810251127E7BF8625A4F49A5" \
3221 "F3E27F4DA8BD59C47D6DAABA4C8127BD" \
3222 "5B5C25763222FEFCCFC38B832366C29E" ) );
3223
3224 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &N, 16,
3225 "0066A198186C18C10B2F5ED9B522752A" \
3226 "9830B69916E535C8F047518A889A43A5" \
3227 "94B6BED27A168D31D4A52F88925AA8F5" ) );
3228
3229 MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &X, &A, &N ) );
3230
3231 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
3232 "602AB7ECA597A3D6B56FF9829A5E8B85" \
3233 "9E857EA95A03512E2BAE7391688D264A" \
3234 "A5663B0341DB9CCFD2C4C5F421FEC814" \
3235 "8001B72E848A38CAE1C65F78E56ABDEF" \
3236 "E12D3C039B8A02D6BE593F0BBBDA56F1" \
3237 "ECF677152EF804370C1A305CAF3B5BF1" \
3238 "30879B56C61DE584A0F53A2447A51E" ) );
3239
3240 if( verbose != 0 )
3241 mbedtls_printf( " MPI test #1 (mul_mpi): " );
3242
3243 if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 )
3244 {
3245 if( verbose != 0 )
3246 mbedtls_printf( "failed\n" );
3247
3248 ret = 1;
3249 goto cleanup;
3250 }
3251
3252 if( verbose != 0 )
3253 mbedtls_printf( "passed\n" );
3254
3255 MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &X, &Y, &A, &N ) );
3256
3257 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
3258 "256567336059E52CAE22925474705F39A94" ) );
3259
3260 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &V, 16,
3261 "6613F26162223DF488E9CD48CC132C7A" \
3262 "0AC93C701B001B092E4E5B9F73BCD27B" \
3263 "9EE50D0657C77F374E903CDFA4C642" ) );
3264
3265 if( verbose != 0 )
3266 mbedtls_printf( " MPI test #2 (div_mpi): " );
3267
3268 if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 ||
3269 mbedtls_mpi_cmp_mpi( &Y, &V ) != 0 )
3270 {
3271 if( verbose != 0 )
3272 mbedtls_printf( "failed\n" );
3273
3274 ret = 1;
3275 goto cleanup;
3276 }
3277
3278 if( verbose != 0 )
3279 mbedtls_printf( "passed\n" );
3280
3281 MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &X, &A, &E, &N, NULL ) );
3282
3283 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
3284 "36E139AEA55215609D2816998ED020BB" \
3285 "BD96C37890F65171D948E9BC7CBAA4D9" \
3286 "325D24D6A3C12710F10A09FA08AB87" ) );
3287
3288 if( verbose != 0 )
3289 mbedtls_printf( " MPI test #3 (exp_mod): " );
3290
3291 if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 )
3292 {
3293 if( verbose != 0 )
3294 mbedtls_printf( "failed\n" );
3295
3296 ret = 1;
3297 goto cleanup;
3298 }
3299
3300 if( verbose != 0 )
3301 mbedtls_printf( "passed\n" );
3302
3303 MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &X, &A, &N ) );
3304
3305 MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,
3306 "003A0AAEDD7E784FC07D8F9EC6E3BFD5" \
3307 "C3DBA76456363A10869622EAC2DD84EC" \
3308 "C5B8A74DAC4D09E03B5E0BE779F2DF61" ) );
3309
3310 if( verbose != 0 )
3311 mbedtls_printf( " MPI test #4 (inv_mod): " );
3312
3313 if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 )
3314 {
3315 if( verbose != 0 )
3316 mbedtls_printf( "failed\n" );
3317
3318 ret = 1;
3319 goto cleanup;
3320 }
3321
3322 if( verbose != 0 )
3323 mbedtls_printf( "passed\n" );
3324
3325 if( verbose != 0 )
3326 mbedtls_printf( " MPI test #5 (simple gcd): " );
3327
3328 for( i = 0; i < GCD_PAIR_COUNT; i++ )
3329 {
3330 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &X, gcd_pairs[i][0] ) );
3331 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &Y, gcd_pairs[i][1] ) );
3332
3333 MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &A, &X, &Y ) );
3334
3335 if( mbedtls_mpi_cmp_int( &A, gcd_pairs[i][2] ) != 0 )
3336 {
3337 if( verbose != 0 )
3338 mbedtls_printf( "failed at %d\n", i );
3339
3340 ret = 1;
3341 goto cleanup;
3342 }
3343 }
3344
3345 if( verbose != 0 )
3346 mbedtls_printf( "passed\n" );
3347
3348 cleanup:
3349
3350 if( ret != 0 && verbose != 0 )
3351 mbedtls_printf( "Unexpected error, return code = %08X\n", (unsigned int) ret );
3352
3353 mbedtls_mpi_free( &A ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &N ); mbedtls_mpi_free( &X );
3354 mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &U ); mbedtls_mpi_free( &V );
3355
3356 if( verbose != 0 )
3357 mbedtls_printf( "\n" );
3358
3359 return( ret );
3360 }
3361
3362 #endif /* MBEDTLS_SELF_TEST */
3363
3364 #endif /* MBEDTLS_BIGNUM_C */
3365