libbrillo: Blob to/from std::string conversions

Add routines that allow dumping Blob contents into an
std::string, and, vice versa, constructing Blob from
such a string.

These helpers should simplify writing code that works
with Blob's, and consequently help transitioning away from
SecureBlob (as the latter provides the same capabilities).

BUG=chromium:728047
TEST=new unit test (BlobTest.StringConversions)

Change-Id: I18223a99899216fe07cbf948bef86dce86777f69
Reviewed-on: https://chromium-review.googlesource.com/1076629
Commit-Ready: Maksim Ivanov <emaxx@chromium.org>
Tested-by: Maksim Ivanov <emaxx@chromium.org>
Reviewed-by: Jorge Lucangeli Obes <jorgelo@chromium.org>
diff --git a/brillo/secure_blob.cc b/brillo/secure_blob.cc
index 8b4a8b1..70c6f6e 100644
--- a/brillo/secure_blob.cc
+++ b/brillo/secure_blob.cc
@@ -10,6 +10,14 @@
 
 namespace brillo {
 
+std::string BlobToString(const Blob& blob) {
+  return std::string(blob.begin(), blob.end());
+}
+
+Blob BlobFromString(const std::string& bytes) {
+  return Blob(bytes.begin(), bytes.end());
+}
+
 SecureBlob::SecureBlob(const Blob& blob)
     : SecureBlob(blob.begin(), blob.end()) {}
 
diff --git a/brillo/secure_blob.h b/brillo/secure_blob.h
index 914093a..41a5cc6 100644
--- a/brillo/secure_blob.h
+++ b/brillo/secure_blob.h
@@ -15,6 +15,11 @@
 
 using Blob = std::vector<uint8_t>;
 
+// Conversion of Blob to/from std::string, where the string holds raw byte
+// contents.
+BRILLO_EXPORT std::string BlobToString(const Blob& blob);
+BRILLO_EXPORT Blob BlobFromString(const std::string& bytes);
+
 // SecureBlob erases the contents on destruction.  It does not guarantee erasure
 // on resize, assign, etc.
 class BRILLO_EXPORT SecureBlob : public Blob {
diff --git a/brillo/secure_blob_unittest.cc b/brillo/secure_blob_unittest.cc
index e4ed486..b1c2d94 100644
--- a/brillo/secure_blob_unittest.cc
+++ b/brillo/secure_blob_unittest.cc
@@ -9,6 +9,7 @@
 
 #include <algorithm>
 #include <iterator>
+#include <limits>
 #include <numeric>
 
 #include <base/logging.h>
@@ -17,6 +18,18 @@
 namespace brillo {
 using std::string;
 
+// Tests BlobToString() and BlobFromString().
+TEST(BlobTest, StringConversions) {
+  const char kTestBytes[] = {'\0', '\x1', 'a', std::numeric_limits<char>::min(),
+                             std::numeric_limits<char>::max()};
+  const Blob blob(std::begin(kTestBytes), std::end(kTestBytes));
+  const string obtained_string = BlobToString(blob);
+  EXPECT_EQ(string(std::begin(kTestBytes), std::end(kTestBytes)),
+            obtained_string);
+  const Blob obtained_blob = BlobFromString(obtained_string);
+  EXPECT_EQ(blob, obtained_blob);
+}
+
 class SecureBlobTest : public ::testing::Test {
  public:
   SecureBlobTest() {}