aboutsummaryrefslogtreecommitdiff
path: root/library/bignum.c
diff options
context:
space:
mode:
Diffstat (limited to 'library/bignum.c')
-rw-r--r--library/bignum.c22
1 files changed, 16 insertions, 6 deletions
diff --git a/library/bignum.c b/library/bignum.c
index d3a150c..d27c130 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -63,6 +63,11 @@ static void mbedtls_mpi_zeroize( mbedtls_mpi_uint *v, size_t n ) {
volatile mbedtls_mpi_uint *p = v; while( n-- ) *p++ = 0;
}
+/* Implementation that should never be optimized out by the compiler */
+static void mbedtls_zeroize( void *v, size_t n ) {
+ volatile unsigned char *p = v; while( n-- ) *p++ = 0;
+}
+
#define ciL (sizeof(mbedtls_mpi_uint)) /* chars in limb */
#define biL (ciL << 3) /* bits in limb */
#define biH (ciL << 2) /* half limb size */
@@ -672,16 +677,20 @@ cleanup:
int mbedtls_mpi_read_binary( mbedtls_mpi *X, const unsigned char *buf, size_t buflen )
{
int ret;
- size_t i, j, n;
+ size_t i, j;
+ size_t const limbs = CHARS_TO_LIMBS( buflen );
- for( n = 0; n < buflen; n++ )
- if( buf[n] != 0 )
- break;
+ /* Ensure that target MPI has exactly the necessary number of limbs */
+ if( X->n != limbs )
+ {
+ mbedtls_mpi_free( X );
+ mbedtls_mpi_init( X );
+ MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, limbs ) );
+ }
- MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, CHARS_TO_LIMBS( buflen - n ) ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );
- for( i = buflen, j = 0; i > n; i--, j++ )
+ for( i = buflen, j = 0; i > 0; i--, j++ )
X->p[j / ciL] |= ((mbedtls_mpi_uint) buf[i - 1]) << ((j % ciL) << 3);
cleanup:
@@ -1882,6 +1891,7 @@ int mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size,
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( X, buf, size ) );
cleanup:
+ mbedtls_zeroize( buf, sizeof( buf ) );
return( ret );
}