Browse Source

Merge pull request #367 from libtom/pr/base32-nul

base32_encode - make the output NUL-terminated
karel-m 7 years ago
parent
commit
f72621e276
2 changed files with 13 additions and 12 deletions
  1. 10 9
      src/misc/base32/base32_encode.c
  2. 3 3
      tests/base32_test.c

+ 10 - 9
src/misc/base32/base32_encode.c

@@ -39,20 +39,20 @@ int base32_encode(const unsigned char *in,  unsigned long inlen,
    LTC_ARGCHK(id >= BASE32_RFC4648);
    LTC_ARGCHK(id <= BASE32_CROCKFORD);
 
-   /* no input, nothing to do */
-   if (inlen == 0) {
-      *outlen = 0;
-      return CRYPT_OK;
-   }
-
-   /* check the size of output buffer */
-   x = (8 * inlen + 4) / 5;
+   /* check the size of output buffer +1 byte for terminating NUL */
+   x = (8 * inlen + 4) / 5 + 1;
    if (*outlen < x) {
       *outlen = x;
       return CRYPT_BUFFER_OVERFLOW;
    }
    *outlen = x;
 
+   /* no input, nothing to do */
+   if (inlen == 0) {
+      *out = '\0';
+      return CRYPT_OK;
+   }
+
    codes = alphabet[id];
    x = 5 * (inlen / 5);
    for (i = 0; i < x; i += 5) {
@@ -79,12 +79,13 @@ int base32_encode(const unsigned char *in,  unsigned long inlen,
       }
       if (i+2 < inlen) {
          *out++ = codes[(((c & 0xF) << 1) + (d >> 7)) & 0x1F];
-         *out++ = codes[(d >> 2) & 0x1F];
       }
       if (i+3 < inlen) {
+         *out++ = codes[(d >> 2) & 0x1F];
          *out++ = codes[((d & 0x3) << 3) & 0x1F];
       }
    }
+   *out = '\0';
    return CRYPT_OK;
 }
 

+ 3 - 3
tests/base32_test.c

@@ -37,7 +37,7 @@ int base32_test(void)
          l1 = sizeof(out);
          DO(base32_encode(in, x, out, &l1, testid[idx]));
          l2 = sizeof(tmp);
-         DO(base32_decode(out, l1, tmp, &l2, testid[idx]));
+         DO(base32_decode(out, strlen(out), tmp, &l2, testid[idx]));
          DO(do_compare_testvector(tmp, l2, in, x, "random base32", idx * 100 + x));
       }
    }
@@ -45,9 +45,9 @@ int base32_test(void)
    for (idx = 0; idx < 4; idx++) {
       l1 = sizeof(out);
       DO(base32_encode(testin, sizeof(testin), out, &l1, testid[idx]));
-      DO(do_compare_testvector(out, l1, testout[idx], strlen(testout[idx]), "testout base32", idx));
+      DO(do_compare_testvector(out, strlen(out), testout[idx], strlen(testout[idx]), "testout base32", idx));
       l2 = sizeof(tmp);
-      DO(base32_decode(out, l1, tmp, &l2, testid[idx]));
+      DO(base32_decode(out, strlen(out), tmp, &l2, testid[idx]));
       DO(do_compare_testvector(tmp, l2, testin, sizeof(testin), "testin base32", idx));
    }