From f968857a82fbe43097e0618fa8cca28f4a75ef28 Mon Sep 17 00:00:00 2001 From: Paul Bakker Date: Thu, 5 May 2011 10:00:45 +0000 Subject: [PATCH] - Removed conversions to int when not needed to prevent signed / unsigned situations - Maximized mpi limb size --- include/polarssl/bignum.h | 7 ++++++- library/bignum.c | 13 ++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/include/polarssl/bignum.h b/include/polarssl/bignum.h index 00164e03f0..a6d7d4a5a2 100644 --- a/include/polarssl/bignum.h +++ b/include/polarssl/bignum.h @@ -40,6 +40,11 @@ #define MPI_CHK(f) if( ( ret = f ) != 0 ) goto cleanup +/* + * Maximum size MPIs are allowed to grow to in number of limbs. + */ +#define POLARSSL_MPI_MAX_LIMBS 10000 + /* * Define the base integer type, architecture-wise */ @@ -526,7 +531,7 @@ int mpi_is_prime( mpi *X, int (*f_rng)(void *), void *p_rng ); * \brief Prime number generation * * \param X Destination MPI - * \param nbits Required size of X in bits + * \param nbits Required size of X in bits ( 3 <= nbits <= 4096 ) * \param dh_flag If 1, then (X-1)/2 will be prime too * \param f_rng RNG function * \param p_rng RNG parameter diff --git a/library/bignum.c b/library/bignum.c index 8f29324e47..2b6e234950 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -40,7 +40,7 @@ #include #include -#define ciL ((int) sizeof(t_uint)) /* chars in limb */ +#define ciL (sizeof(t_uint)) /* chars in limb */ #define biL (ciL << 3) /* bits in limb */ #define biH (ciL << 2) /* half limb size */ @@ -105,6 +105,9 @@ int mpi_grow( mpi *X, size_t nblimbs ) { t_uint *p; + if( nblimbs > POLARSSL_MPI_MAX_LIMBS ) + return( 1 ); + if( X->n < nblimbs ) { if( ( p = (t_uint *) malloc( nblimbs * ciL ) ) == NULL ) @@ -192,7 +195,7 @@ size_t mpi_lsb( const mpi *X ) size_t i, j, count = 0; for( i = 0; i < X->n; i++ ) - for( j = 0; j < (int) biL; j++, count++ ) + for( j = 0; j < biL; j++, count++ ) if( ( ( X->p[i] >> j ) & 1 ) != 0 ) return( count ); @@ -528,7 +531,7 @@ int mpi_shift_l( mpi *X, size_t count ) i = mpi_msb( X ) + count; - if( X->n * (int) biL < i ) + if( X->n * biL < i ) MPI_CHK( mpi_grow( X, BITS_TO_LIMBS( i ) ) ); ret = 0; @@ -1041,7 +1044,7 @@ int mpi_div_mpi( mpi *Q, mpi *R, const mpi *A, const mpi *B ) MPI_CHK( mpi_grow( &T2, 3 ) ); k = mpi_msb( &Y ) % biL; - if( k < (int) biL - 1 ) + if( k < biL - 1 ) { k = biL - 1 - k; MPI_CHK( mpi_shift_l( &X, k ) ); @@ -1833,7 +1836,7 @@ int mpi_gen_prime( mpi *X, size_t nbits, int dh_flag, size_t k, n; mpi Y; - if( nbits < 3 ) + if( nbits < 3 || nbits > 4096 ) return( POLARSSL_ERR_MPI_BAD_INPUT_DATA ); mpi_init( &Y, NULL );