shill: Base64 encode/decode crypto_util arguments

Initially, I thought this would be easier to do in the shim, where
things might play nicely with OpenSSL.  However, it turns out that the
OpenSSL API for base64 encoding/decoding is far more painful that it's
worth.  Add a convenient wrapper around the raw GLib calls so that
people have less opportunity to shoot themselves in the foot.

BUG=chromium-os:221168
TEST=Unit tests pass.

Change-Id: I69732af03fdf729519783a3440213ef6adf8a630
Reviewed-on: https://gerrit.chromium.org/gerrit/46049
Tested-by: Christopher Wiley <wiley@chromium.org>
Reviewed-by: Paul Stewart <pstew@chromium.org>
Commit-Queue: Christopher Wiley <wiley@chromium.org>
diff --git a/glib.cc b/glib.cc
index 4e99853..d5c0f91 100644
--- a/glib.cc
+++ b/glib.cc
@@ -2,9 +2,15 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include "shill/glib.h"
+
+#include <string>
+
 #include <base/stringprintf.h>
 
-#include "shill/glib.h"
+#include "shill/logging.h"
+
+using std::string;
 
 namespace shill {
 
@@ -28,6 +34,40 @@
   return g_base64_encode(data, len);
 }
 
+bool GLib::B64Decode(const string &input, string *output) {
+  CHECK(output);
+  gsize result_len = 0;
+  guchar *result = Base64Decode(input.c_str(), &result_len);
+  if (!result) {
+    LOG(ERROR) << "Failed in encoding.";
+    return false;
+  }
+
+  if (!result_len) {
+    LOG(ERROR) << "Failed in encoding.";
+    Free(result);
+    return false;
+  }
+
+  output->assign(reinterpret_cast<char *>(result), result_len);
+  Free(result);
+  return true;
+}
+
+bool GLib::B64Encode(const string &input, string *output) {
+  CHECK(output);
+  gchar *result = Base64Encode(
+      reinterpret_cast<const unsigned char *>(input.c_str()), input.length());
+  if (!result) {
+    LOG(ERROR) << "Failed in encoding.";
+    return false;
+  }
+
+  output->assign(result);
+  Free(result);
+  return true;
+}
+
 void GLib::BusUnwatchName(guint watcher_id) {
   g_bus_unwatch_name(watcher_id);
 }