- Fixed incorrect handling of negative first input value in mpi_mod_mpi() and mpi_mod_int(). Resulting change also affects mpi_write_string() (found by code coverage tests).

diff --git a/ChangeLog b/ChangeLog
index 4a35a21..5dc686e 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -8,6 +8,10 @@
      value in mpi_add_abs() (found by code coverage tests).

    * Fixed incorrect handling of negative first input

      value in mpi_sub_abs() (found by code coverage tests).

+   * Fixed incorrect handling of negative first input

+     value in mpi_mod_mpi() and mpi_mod_int(). Resulting

+	 change also affects mpi_write_string() (found by code

+	 coverage tests).

 

 = Version 0.11.1 released on 2009-05-17

    * Fixed missing functionality for SHA-224, SHA-256, SHA384,

diff --git a/include/polarssl/bignum.h b/include/polarssl/bignum.h
index e6abd59..9c06a3f 100644
--- a/include/polarssl/bignum.h
+++ b/include/polarssl/bignum.h
@@ -308,6 +308,8 @@
 
 /**
  * \brief          Baseline multiplication: X = A * b
+ *                 Note: b is an unsigned integer type, thus
+ *                 Negative values of b are ignored.
  *
  * \return         0 if successful,
  *                 1 if memory allocation failed
@@ -341,7 +343,8 @@
  *
  * \return         0 if successful,
  *                 1 if memory allocation failed,
- *                 POLARSSL_ERR_MPI_DIVISION_BY_ZERO if B == 0
+ *                 POLARSSL_ERR_MPI_DIVISION_BY_ZERO if B == 0,
+ *                 POLARSSL_ERR_MPI_NEGATIVE_VALUE if B < 0
  */
 int mpi_mod_mpi( mpi *R, mpi *A, mpi *B );
 
@@ -350,7 +353,8 @@
  *
  * \return         0 if successful,
  *                 1 if memory allocation failed,
- *                 POLARSSL_ERR_MPI_DIVISION_BY_ZERO if b == 0
+ *                 POLARSSL_ERR_MPI_DIVISION_BY_ZERO if b == 0,
+ *                 POLARSSL_ERR_MPI_NEGATIVE_VALUE if b < 0
  */
 int mpi_mod_int( t_int *r, mpi *A, int b );
 
diff --git a/library/bignum.c b/library/bignum.c
index 9f11a70..d1646f0 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -382,6 +382,10 @@
     else
     {
         MPI_CHK( mpi_copy( &T, X ) );
+
+        if( T.s == -1 )
+            T.s = 1;
+
         MPI_CHK( mpi_write_hlp( &T, radix, &p ) );
     }
 
@@ -1180,6 +1184,9 @@
 {
     int ret;
 
+    if( mpi_cmp_int( B, 0 ) < 0 )
+        return POLARSSL_ERR_MPI_NEGATIVE_VALUE;
+
     MPI_CHK( mpi_div_mpi( NULL, R, A, B ) );
 
     while( mpi_cmp_int( R, 0 ) < 0 )
@@ -1205,7 +1212,7 @@
         return( POLARSSL_ERR_MPI_DIVISION_BY_ZERO );
 
     if( b < 0 )
-        b = -b;
+        return POLARSSL_ERR_MPI_NEGATIVE_VALUE;
 
     /*
      * handle trivial cases
@@ -1238,6 +1245,13 @@
         y -= z * b;
     }
 
+    /*
+     * If A is negative, then the current y represents a negative value.
+     * Flipping it to the positive side.
+     */
+    if( A->s < 0 && y != 0 )
+        y = b - y;
+
     *r = y;
 
     return( 0 );