@@ -527,26 +527,38 @@ int mbedtls_mpi_read_string( mbedtls_mpi *X, int radix, const char *s )
527
527
}
528
528
529
529
/*
530
- * Helper to write the digits high-order first
530
+ * Helper to write the digits high-order first.
531
531
*/
532
- static int mpi_write_hlp ( mbedtls_mpi * X , int radix , char * * p )
532
+ static int mpi_write_hlp ( mbedtls_mpi * X , int radix ,
533
+ char * * p , const size_t buflen )
533
534
{
534
535
int ret ;
535
536
mbedtls_mpi_uint r ;
537
+ size_t length = 0 ;
538
+ char * p_end = * p + buflen ;
536
539
537
- if ( radix < 2 || radix > 16 )
538
- return ( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
540
+ do
541
+ {
542
+ if ( length >= buflen )
543
+ {
544
+ return ( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
545
+ }
539
546
540
- MBEDTLS_MPI_CHK ( mbedtls_mpi_mod_int ( & r , X , radix ) );
541
- MBEDTLS_MPI_CHK ( mbedtls_mpi_div_int ( X , NULL , X , radix ) );
547
+ MBEDTLS_MPI_CHK ( mbedtls_mpi_mod_int ( & r , X , radix ) );
548
+ MBEDTLS_MPI_CHK ( mbedtls_mpi_div_int ( X , NULL , X , radix ) );
549
+ /*
550
+ * Write the residue in the current position, as an ASCII character.
551
+ */
552
+ if ( r < 0xA )
553
+ * (-- p_end ) = (char )( '0' + r );
554
+ else
555
+ * (-- p_end ) = (char )( 'A' + ( r - 0xA ) );
542
556
543
- if ( mbedtls_mpi_cmp_int ( X , 0 ) != 0 )
544
- MBEDTLS_MPI_CHK ( mpi_write_hlp ( X , radix , p ) );
557
+ length ++ ;
558
+ } while ( mbedtls_mpi_cmp_int ( X , 0 ) != 0 );
545
559
546
- if ( r < 10 )
547
- * (* p )++ = (char )( r + 0x30 );
548
- else
549
- * (* p )++ = (char )( r + 0x37 );
560
+ memmove ( * p , p_end , length );
561
+ * p += length ;
550
562
551
563
cleanup :
552
564
@@ -619,7 +631,7 @@ int mbedtls_mpi_write_string( const mbedtls_mpi *X, int radix,
619
631
if ( T .s == -1 )
620
632
T .s = 1 ;
621
633
622
- MBEDTLS_MPI_CHK ( mpi_write_hlp ( & T , radix , & p ) );
634
+ MBEDTLS_MPI_CHK ( mpi_write_hlp ( & T , radix , & p , buflen ) );
623
635
}
624
636
625
637
* p ++ = '\0' ;
0 commit comments