From c1fa6cdab6a75ea4bcf75505fce27a936da25142 Mon Sep 17 00:00:00 2001 From: Hanno Becker Date: Mon, 4 Feb 2019 09:45:07 +0000 Subject: [PATCH] Improve documentation of mbedtls_mpi_write_string() --- library/bignum.c | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/library/bignum.c b/library/bignum.c index 467c3aa4b..9aed59c5e 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -582,15 +582,20 @@ int mbedtls_mpi_write_string( const mbedtls_mpi *X, int radix, if( radix < 2 || radix > 16 ) return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); - n = mbedtls_mpi_bitlen( X ); - if( radix >= 4 ) n >>= 1; - if( radix >= 16 ) n >>= 1; - /* - * Round up the buffer length to an even value to ensure that there is - * enough room for hexadecimal values that can be represented in an odd - * number of digits. - */ - n += 3 + ( ( n + 1 ) & 1 ); + n = mbedtls_mpi_bitlen( X ); /* Number of bits necessary to present `n`. */ + if( radix >= 4 ) n >>= 1; /* Number of 4-adic digits necessary to present + * `n`. If radix > 4, this might be a strict + * overapproximation of the number of + * radix-adic digits needed to present `n`. */ + if( radix >= 16 ) n >>= 1; /* Number of hexadecimal digits necessary to + * present `n`. */ + + n += 1; /* NULL termination */ + n += 1; /* Compensate for the divisions above, which round down `n` + * in case it's not even. */ + n += 1; /* Potential '-'-sign. */ + n += ( n & 1 ); /* Make n even to have enough space for hexadecimal writing, + * which always uses an even number of hex-digits. */ if( buflen < n ) {