Commit ce98f3675d3b454dafd5812ec31804ac6991e429

Steffen Jaeckel 2019-10-07T16:09:37

Merge pull request #348 from czurnieden/to_radix_returns_length_converted make mp_to_radix return the count of characters of the converted number

diff --git a/bn_deprecated.c b/bn_deprecated.c
index 19b0e49..60b3e16 100644
--- a/bn_deprecated.c
+++ b/bn_deprecated.c
@@ -113,7 +113,10 @@ mp_err mp_toom_sqr(const mp_int *a, mp_int *b)
 #ifdef S_MP_REVERSE_C
 void bn_reverse(unsigned char *s, int len)
 {
-   s_mp_reverse(s, len);
+   if (len < 0) {
+      return MP_VAL;
+   }
+   s_mp_reverse(s, (size_t)len);
 }
 #endif
 #ifdef BN_MP_TC_AND_C
@@ -304,13 +307,13 @@ mp_err mp_toradix_n(const mp_int *a, char *str, int radix, int maxlen)
    if (maxlen < 0) {
       return MP_VAL;
    }
-   return mp_to_radix(a, str, (size_t)maxlen, radix);
+   return mp_to_radix(a, str, (size_t)maxlen, NULL, radix);
 }
 #endif
 #ifdef BN_MP_TORADIX_C
 mp_err mp_toradix(const mp_int *a, char *str, int radix)
 {
-   return mp_to_radix(a, str, SIZE_MAX, radix);
+   return mp_to_radix(a, str, SIZE_MAX, NULL, radix);
 }
 #endif
 #endif
diff --git a/bn_mp_fwrite.c b/bn_mp_fwrite.c
index eaa5d06..abe2e67 100644
--- a/bn_mp_fwrite.c
+++ b/bn_mp_fwrite.c
@@ -9,9 +9,15 @@ mp_err mp_fwrite(const mp_int *a, int radix, FILE *stream)
    char *buf;
    mp_err err;
    int len;
+   size_t written;
 
-   if ((err = mp_radix_size(a, radix, &len)) != MP_OKAY) {
-      return err;
+   /* TODO: this function is not in this PR */
+   if (MP_HAS(MP_RADIX_SIZE_OVERESTIMATE)) {
+      /* if ((err = mp_radix_size_overestimate(&t, base, &len)) != MP_OKAY)      goto LBL_ERR; */
+   } else {
+      if ((err = mp_radix_size(a, radix, &len)) != MP_OKAY) {
+         return err;
+      }
    }
 
    buf = (char *) MP_MALLOC((size_t)len);
@@ -19,16 +25,17 @@ mp_err mp_fwrite(const mp_int *a, int radix, FILE *stream)
       return MP_MEM;
    }
 
-   if ((err = mp_to_radix(a, buf, (size_t)len, radix)) != MP_OKAY) {
+   if ((err = mp_to_radix(a, buf, (size_t)len, &written, radix)) != MP_OKAY) {
       goto LBL_ERR;
    }
 
-   if (fwrite(buf, (size_t)len, 1uL, stream) != 1uL) {
+   if (fwrite(buf, written, 1uL, stream) != 1uL) {
       err = MP_ERR;
       goto LBL_ERR;
    }
    err = MP_OKAY;
 
+
 LBL_ERR:
    MP_FREE_BUFFER(buf, (size_t)len);
    return err;
diff --git a/bn_mp_radix_size.c b/bn_mp_radix_size.c
index 339b21b..b96f487 100644
--- a/bn_mp_radix_size.c
+++ b/bn_mp_radix_size.c
@@ -3,11 +3,11 @@
 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
 /* SPDX-License-Identifier: Unlicense */
 
-/* returns size of ASCII reprensentation */
+/* returns size of ASCII representation */
 mp_err mp_radix_size(const mp_int *a, int radix, int *size)
 {
    mp_err  err;
-   int     digs;
+   int digs;
    mp_int   t;
    mp_digit d;
 
@@ -25,7 +25,7 @@ mp_err mp_radix_size(const mp_int *a, int radix, int *size)
 
    /* special case for binary */
    if (radix == 2) {
-      *size = mp_count_bits(a) + ((a->sign == MP_NEG) ? 1 : 0) + 1;
+      *size = (mp_count_bits(a) + ((a->sign == MP_NEG) ? 1 : 0) + 1);
       return MP_OKAY;
    }
 
diff --git a/bn_mp_to_radix.c b/bn_mp_to_radix.c
index 0af0bb7..ad12142 100644
--- a/bn_mp_to_radix.c
+++ b/bn_mp_to_radix.c
@@ -5,9 +5,10 @@
 
 /* stores a bignum as a ASCII string in a given radix (2..64)
  *
- * Stores upto maxlen-1 chars and always a NULL byte
+ * Stores upto "size - 1" chars and always a NULL byte, puts the number of characters
+ * written, including the '\0', in "written".
  */
-mp_err mp_to_radix(const mp_int *a, char *str, size_t maxlen, int radix)
+mp_err mp_to_radix(const mp_int *a, char *str, size_t maxlen, size_t *written, int radix)
 {
    size_t  digs;
    mp_err  err;
@@ -15,7 +16,13 @@ mp_err mp_to_radix(const mp_int *a, char *str, size_t maxlen, int radix)
    mp_digit d;
    char   *_s = str;
 
-   /* check range of the maxlen, radix */
+
+   /* If we want to fill a bucket we need a bucket in the first place. */
+   if (str == NULL) {
+      return MP_VAL;
+   }
+
+   /* check range of radix and size*/
    if ((maxlen < 2u) || (radix < 2) || (radix > 64)) {
       return MP_VAL;
    }
@@ -24,6 +31,9 @@ mp_err mp_to_radix(const mp_int *a, char *str, size_t maxlen, int radix)
    if (MP_IS_ZERO(a)) {
       *str++ = '0';
       *str = '\0';
+      if (written != NULL) {
+         *written = 2u;
+      }
       return MP_OKAY;
    }
 
@@ -43,11 +53,12 @@ mp_err mp_to_radix(const mp_int *a, char *str, size_t maxlen, int radix)
       /* subtract a char */
       --maxlen;
    }
-
    digs = 0u;
    while (!MP_IS_ZERO(&t)) {
       if (--maxlen < 1u) {
          /* no more room */
+         /* TODO: It could mimic mp_to_radix_n if that is not an error
+                  or at least not this error (MP_ITER or a new one?). */
          err = MP_VAL;
          break;
       }
@@ -57,7 +68,6 @@ mp_err mp_to_radix(const mp_int *a, char *str, size_t maxlen, int radix)
       *str++ = mp_s_rmap[d];
       ++digs;
    }
-
    /* reverse the digits of the string.  In this case _s points
     * to the first digit [exluding the sign] of the number
     */
@@ -65,6 +75,10 @@ mp_err mp_to_radix(const mp_int *a, char *str, size_t maxlen, int radix)
 
    /* append a NULL so the string is properly terminated */
    *str = '\0';
+   digs++;
+   if (written != NULL) {
+      *written = (a->sign == MP_NEG) ? digs + 1u: digs;
+   }
 
 LBL_ERR:
    mp_clear(&t);
diff --git a/demo/shared.c b/demo/shared.c
index 2e2b1f9..dc8e05a 100644
--- a/demo/shared.c
+++ b/demo/shared.c
@@ -2,7 +2,7 @@
 
 void ndraw(mp_int *a, const char *name)
 {
-   char *buf;
+   char *buf = NULL;
    int size;
 
    mp_radix_size(a, 10, &size);
diff --git a/demo/test.c b/demo/test.c
index 7d4f065..f19345d 100644
--- a/demo/test.c
+++ b/demo/test.c
@@ -1189,6 +1189,8 @@ static int test_mp_montgomery_reduce(void)
    int ix, i, n;
    char buf[4096];
 
+   /* size_t written; */
+
    mp_int a, b, c, d, e;
    if (mp_init_multi(&a, &b, &c, &d, &e, NULL)!= MP_OKAY) {
       return EXIT_FAILURE;
@@ -1225,6 +1227,7 @@ static int test_mp_montgomery_reduce(void)
                mp_to_decimal(&e, buf, sizeof(buf)); printf("e = %s\n", buf);
                mp_to_decimal(&d, buf, sizeof(buf)); printf("d = %s\n", buf);
                mp_to_decimal(&c, buf, sizeof(buf)); printf("c = %s\n", buf);
+
                printf("compare no compare!\n"); goto LBL_ERR;
 /* *INDENT-ON* */
             }
@@ -1250,31 +1253,67 @@ LBL_ERR:
 static int test_mp_read_radix(void)
 {
    char buf[4096];
+   size_t written;
+   mp_err err;
 
    mp_int a;
-   if (mp_init_multi(&a, NULL)!= MP_OKAY) {
-      return EXIT_FAILURE;
-   }
+   if (mp_init_multi(&a, NULL)!= MP_OKAY)                                       goto LTM_ERR;
+
+   if ((err = mp_read_radix(&a, "123456", 10)) != MP_OKAY)                     goto LTM_ERR;
+   /* Must fail */
+   if ((err = mp_to_radix(&a, NULL, SIZE_MAX, NULL, 10)) != MP_VAL)             goto LTM_ERR;
+
+   if ((err = mp_to_radix(&a, buf, SIZE_MAX, &written, 10)) != MP_OKAY)        goto LTM_ERR;
+   printf(" '123456' a == %s, length = %zu\n", buf, written);
+
+   /* See comment in bn_mp_to_radix.c */
+   /*
+      if( (err = mp_to_radix(&a, buf, 3u, &written, 10) ) != MP_OKAY)              goto LTM_ERR;
+      printf(" '56' a == %s, length = %zu\n", buf, written);
+
+      if( (err = mp_to_radix(&a, buf, 4u, &written, 10) ) != MP_OKAY)              goto LTM_ERR;
+      printf(" '456' a == %s, length = %zu\n", buf, written);
+      if( (err = mp_to_radix(&a, buf, 30u, &written, 10) ) != MP_OKAY)             goto LTM_ERR;
+      printf(" '123456' a == %s, length = %zu, error = %s\n",
+             buf, written, mp_error_to_string(err));
+   */
+   if ((err = mp_read_radix(&a, "-123456", 10)) != MP_OKAY)                    goto LTM_ERR;
+   if ((err = mp_to_radix(&a, buf, SIZE_MAX, &written, 10)) != MP_OKAY)        goto LTM_ERR;
+   printf(" '-123456' a == %s, length = %zu\n", buf, written);
+
+   if ((err = mp_read_radix(&a, "0", 10)) != MP_OKAY)                          goto LTM_ERR;
+   if ((err = mp_to_radix(&a, buf, SIZE_MAX, &written, 10)) != MP_OKAY)        goto LTM_ERR;
+   printf(" '0' a == %s, length = %zu\n", buf, written);
 
-   mp_read_radix(&a, "123456", 10);
-   mp_to_radix(&a, buf, 3, 10);
+
+
+   /* Although deprecated it needs to function as long as it isn't dropped */
+   /*
+   printf("Testing deprecated mp_toradix_n\n");
+   if( (err = mp_read_radix(&a, "-123456", 10) ) != MP_OKAY)                    goto LTM_ERR;
+   if( (err = mp_toradix_n(&a, buf, 10, 3) ) != MP_OKAY)                        goto LTM_ERR;
    printf("a == %s\n", buf);
-   mp_to_radix(&a, buf, 4, 10);
+   if( (err = mp_toradix_n(&a, buf, 10, 4) ) != MP_OKAY)                        goto LTM_ERR;
    printf("a == %s\n", buf);
-   mp_to_radix(&a, buf, 30, 10);
+   if( (err = mp_toradix_n(&a, buf, 10, 30) ) != MP_OKAY)                       goto LTM_ERR;
    printf("a == %s\n", buf);
+   */
+
 
    while (0) {
       char *s = fgets(buf, sizeof(buf), stdin);
       if (s != buf) break;
       mp_read_radix(&a, buf, 10);
       mp_prime_next_prime(&a, 5, 1);
-      mp_to_radix(&a, buf, sizeof(buf), 10);
+      mp_to_radix(&a, buf, sizeof(buf), NULL, 10);
       printf("%s, %lu\n", buf, (unsigned long)a.dp[0] & 3uL);
    }
 
-   mp_clear_multi(&a, NULL);
+   mp_clear(&a);
    return EXIT_SUCCESS;
+LTM_ERR:
+   mp_clear(&a);
+   return EXIT_FAILURE;
 }
 
 static int test_mp_cnt_lsb(void)
@@ -1444,6 +1483,7 @@ static int test_mp_reduce_2k_l(void)
    mp_int a, b, c, d;
    int cnt;
    char buf[4096];
+   size_t length[1];
    if (mp_init_multi(&a, &b, NULL)!= MP_OKAY) {
       return EXIT_FAILURE;
    }
@@ -1463,9 +1503,9 @@ static int test_mp_reduce_2k_l(void)
 #      else
 #         error oops
 #      endif
-
-   mp_to_decimal(&a, buf, sizeof(buf));
-   printf("\n\np==%s\n", buf);
+   *length = sizeof(buf);
+   mp_to_radix(&a, buf, length, 10);
+   printf("\n\np==%s, length = %zu\n", buf, *length);
    /* now mp_reduce_is_2k_l() should return */
    if (mp_reduce_is_2k_l(&a) != 1) {
       printf("mp_reduce_is_2k_l() return 0, should be 1\n");
@@ -1824,6 +1864,7 @@ LTM_ERR:
    All numbers as strings to simplifiy things, especially for the
    low-mp branch.
 */
+
 static int test_mp_root_u32(void)
 {
    mp_int a, c, r;
diff --git a/doc/bn.tex b/doc/bn.tex
index 850e1ce..09dea7a 100644
--- a/doc/bn.tex
+++ b/doc/bn.tex
@@ -100,7 +100,7 @@ also build in MSVC, Borland C out of the box.  For any other ISO C compiler a ma
 developer. Please consider to commit such a makefile to the LibTomMath developers, currently residing at
 \url{http://github.com/libtom/libtommath}, if successfully done so.
 
-Intel's C-compiler (ICC) is sufficiently compatible with GCC, at least the newer versions, to replace GCC for building the static and the shared library. Editing the makfiles is not needed, just set the shell variable \texttt{CC} as shown below.
+Intel's C-compiler (ICC) is sufficiently compatible with GCC, at least the newer versions, to replace GCC for building the static and the shared library. Editing the makefiles is not needed, just set the shell variable \texttt{CC} as shown below.
 \begin{alltt}
 CC=/home/czurnieden/intel/bin/icc make
 \end{alltt}
@@ -2098,18 +2098,21 @@ The random number generated with these two functions is cryptographically secure
 \chapter{Input and Output}
 \section{ASCII Conversions}
 \subsection{To ASCII}
-\index{mp\_toradix}
+\index{mp\_to\_radix}
 \begin{alltt}
-int mp_to_radix (mp_int * a, char *str, size_t maxlen, int radix);
+int mp_to_radix (mp_int *a, char *str, size_t maxlen, size_t *written, int radix);
 \end{alltt}
-This stores $a$ in ``str'' of maximum length ``maxlen'' as a base-``radix'' string of ASCII chars.
-This function appends a NUL character to terminate the string.
-Valid values of ``radix'' line in the range $[2, 64]$.
+This stores $a$ in \texttt{str} of maximum length \texttt{maxlen} as a base-\texttt{radix} string of ASCII chars and appends a \texttt{NUL} character to terminate the string.
 
-If ``str'' is not big enough to hold $a$, ``str' will be filled with the least-significant digits
-of length ``maxlen-1'', then ``str' will be NUL terminated and the error \texttt{MP\_VAL} is returned.
+Valid values of \texttt{radix} line in the range $[2, 64]$.
+
+The exact number of characters in \texttt{str} plus the \texttt{NUL} will be put in \texttt{written} if that variable is not set to \texttt{NULL}.
+
+If \texttt{str} is not big enough to hold $a$, \texttt{str} will be filled with the least-significant digits
+of length \texttt{maxlen-1}, then \texttt{str} will be \texttt{NUL} terminated and the error \texttt{MP\_VAL} is returned.
+
+Please be aware that this function cannot evaluate the actual size of the buffer, it relies on the correctness of \texttt{maxlen}!
 
-To determine the size (exact) required by the conversion before storing any data use the following function.
 
 \index{mp\_radix\_size}
 \begin{alltt}
diff --git a/tommath.h b/tommath.h
index 8c67c0e..0b04a5c 100644
--- a/tommath.h
+++ b/tommath.h
@@ -718,7 +718,7 @@ mp_err mp_to_sbin(const mp_int *a, unsigned char *buf, size_t maxlen, size_t *wr
 mp_err mp_read_radix(mp_int *a, const char *str, int radix) MP_WUR;
 MP_DEPRECATED(mp_to_radix) mp_err mp_toradix(const mp_int *a, char *str, int radix) MP_WUR;
 MP_DEPRECATED(mp_to_radix) mp_err mp_toradix_n(const mp_int *a, char *str, int radix, int maxlen) MP_WUR;
-mp_err mp_to_radix(const mp_int *a, char *str, size_t maxlen, int radix) MP_WUR;
+mp_err mp_to_radix(const mp_int *a, char *str, size_t maxlen, size_t *written, int radix) MP_WUR;
 mp_err mp_radix_size(const mp_int *a, int radix, int *size) MP_WUR;
 
 #ifndef MP_NO_FILE
@@ -738,10 +738,10 @@ mp_err mp_fwrite(const mp_int *a, int radix, FILE *stream) MP_WUR;
 #define mp_todecimal(M, S) (MP_DEPRECATED_PRAGMA("replaced by mp_to_decimal") mp_toradix((M), (S), 10))
 #define mp_tohex(M, S)     (MP_DEPRECATED_PRAGMA("replaced by mp_to_hex")     mp_toradix((M), (S), 16))
 
-#define mp_to_binary(M, S, N)  mp_to_radix((M), (S), (N), 2)
-#define mp_to_octal(M, S, N)   mp_to_radix((M), (S), (N), 8)
-#define mp_to_decimal(M, S, N) mp_to_radix((M), (S), (N), 10)
-#define mp_to_hex(M, S, N)     mp_to_radix((M), (S), (N), 16)
+#define mp_to_binary(M, S, N)  mp_to_radix((M), (S), (N), NULL, 2)
+#define mp_to_octal(M, S, N)   mp_to_radix((M), (S), (N), NULL, 8)
+#define mp_to_decimal(M, S, N) mp_to_radix((M), (S), (N), NULL, 10)
+#define mp_to_hex(M, S, N)     mp_to_radix((M), (S), (N), NULL, 16)
 
 #ifdef __cplusplus
 }