mbedtls_mpi_read_string: make an empty bignum for an empty string

In mbedtls_mpi_read_string, if the string is empty, return an empty bignum
rather than a bignum with one limb with the value 0.

Both representations are correct, so this is not, in principle, a
user-visible change. The change does leak however through
mbedtls_mpi_write_string in base 16 (but not in other bases), as it writes a
bignum with 0 limbs as "" but a bignum with the value 0 and at least one
limb as "00".

This change makes it possible to construct an empty bignum through
mbedtls_mpi_read_string, which is especially useful to construct test
cases (a common use of mbedtls_mpi_read_string, as most formats use in
production encode numbers in binary, to be read with mbedtls_mpi_read_binary
or mbedtls_mpi_read_binary_le).

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
This commit is contained in:
Gilles Peskine 2021-06-08 18:32:34 +02:00
parent 45adf6fca9
commit 7cba859235
2 changed files with 8 additions and 2 deletions

View File

@ -512,6 +512,12 @@ int mbedtls_mpi_read_string( mbedtls_mpi *X, int radix, const char *s )
mbedtls_mpi_init( &T );
if( s[0] == 0 )
{
mbedtls_mpi_free( X );
return( 0 );
}
if( s[0] == '-' )
{
++s;

View File

@ -62,13 +62,13 @@ Test mpi_read_write_string #7
mpi_read_write_string:10:"56125680981752282334141896320372489490613963693556392520816017892111350604111697682705498319512049040516698827829292076808006940873974979584527073481012636016353913462376755556720019831187364993587901952757307830896531678727717924":16:"0941379d00fed1491fe15df284dfde4a142f68aa8d412023195cee66883e6290ffe703f4ea5963bf212713cee46b107c09182b5edcd955adac418bf4918e2889af48e1099d513830cec85c26ac1e158b52620e33ba8692f893efbb2f958b4424":200:0:0
Test mpi_read_write_string #8 (Empty MPI hex -> hex)
mpi_read_write_string:16:"":16:"00":4:0:0
mpi_read_write_string:16:"":16:"":4:0:0
Test mpi_read_write_string #9 (Empty MPI hex -> dec)
mpi_read_write_string:16:"":10:"0":4:0:0
Test mpi_read_write_string #8 (Empty MPI dec -> hex)
mpi_read_write_string:10:"":16:"00":4:0:0
mpi_read_write_string:10:"":16:"":4:0:0
Test mpi_read_write_string #9 (Empty MPI dec -> dec)
mpi_read_write_string:10:"":10:"0":4:0:0