pki: Fix Base64Encode behavior on empty input

An empty input is valid so Base64Encode should not return false for it.

Update-Note: Base64Encode in string_util.h now accepts an empty input.

Change-Id: I19137cb802e932689ce136bedac7f09d6a6a6964
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/106530
Auto-Submit: Lily Chen <chlily@google.com>
Commit-Queue: David Benjamin <davidben@google.com>
Reviewed-by: David Benjamin <davidben@google.com>
Presubmit-BoringSSL-Verified: boringssl-scoped@luci-project-accounts.iam.gserviceaccount.com <boringssl-scoped@luci-project-accounts.iam.gserviceaccount.com>
diff --git a/pki/string_util.cc b/pki/string_util.cc
index af27b5c..26ca9d7 100644
--- a/pki/string_util.cc
+++ b/pki/string_util.cc
@@ -126,9 +126,6 @@
   len = EVP_EncodeBlock(reinterpret_cast<uint8_t *>(encoded.data()),
                         reinterpret_cast<const uint8_t *>(input.data()),
                         input.size());
-  if (!len) {
-    return false;
-  }
   output->assign(encoded.data(), len);
   return true;
 }
diff --git a/pki/string_util_unittest.cc b/pki/string_util_unittest.cc
index 9e2a740..6b07e67 100644
--- a/pki/string_util_unittest.cc
+++ b/pki/string_util_unittest.cc
@@ -149,6 +149,34 @@
             std::vector<std::string_view>({"abc", "", "def"}));
 }
 
+TEST(StringUtilTest, Base64Encode) {
+  static constexpr struct {
+    std::string_view input;
+    const char *expected;
+  } kTests[] = {
+      // Default-constructed string_view has null data().
+      {std::string_view(), ""},
+      // Test vectors from RFC 4648, section 10.
+      {"", ""},
+      {"f", "Zg=="},
+      {"fo", "Zm8="},
+      {"foo", "Zm9v"},
+      {"foob", "Zm9vYg=="},
+      {"fooba", "Zm9vYmE="},
+      {"foobar", "Zm9vYmFy"},
+      // Binary data with an embedded NUL and '+'/'/' in the output.
+      {std::string_view("\x00\xff\xfe", 3), "AP/+"},
+  };
+  for (const auto &t : kTests) {
+    SCOPED_TRACE(t.expected);
+    // Pre-populate `out` to verify that `Base64Encode` overwrites it,
+    // including for empty inputs.
+    std::string out = "initial";
+    EXPECT_TRUE(bssl::string_util::Base64Encode(t.input, &out));
+    EXPECT_EQ(out, t.expected);
+  }
+}
+
 }  // namespace
 
 BSSL_NAMESPACE_END