- 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/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 );