util: Add toString and operator<< for util::Digest

Change-Id: Id3695ad1d66dcc93f08085ee42556c71e3eb419c
diff --git a/src/util/digest.cpp b/src/util/digest.cpp
index bb2201d..ec27804 100644
--- a/src/util/digest.cpp
+++ b/src/util/digest.cpp
@@ -130,7 +130,36 @@
   return result;
 }
 
-template class Digest<CryptoPP::SHA256>;
+template<typename Hash>
+std::string
+Digest<Hash>::toString()
+{
+  std::ostringstream os;
+  os << *this;
+
+  return os.str();
+}
+
+template<typename Hash>
+std::ostream&
+operator<<(std::ostream& os, Digest<Hash>& digest)
+{
+  using namespace CryptoPP;
+
+  std::string output;
+  ConstBufferPtr buffer = digest.computeDigest();
+  StringSource(buffer->buf(), buffer->size(), true, new HexEncoder(new FileSink(os)));
+
+  return os;
+}
+
+template
+class Digest<CryptoPP::SHA256>;
+
+template
+std::ostream&
+operator<<(std::ostream& os, Digest<CryptoPP::SHA256>& digest);
+
 
 } // namespace util
 } // namespace ndn
diff --git a/src/util/digest.hpp b/src/util/digest.hpp
index 39ff811..db9ccc1 100644
--- a/src/util/digest.hpp
+++ b/src/util/digest.hpp
@@ -163,6 +163,14 @@
   static ConstBufferPtr
   computeDigest(const uint8_t* buffer, size_t size);
 
+  /**
+   * @brief Convert digest to std::string
+   *
+   * Note that this method will invoke computeDigest().
+   * Once this method is invoked, the digest is finalized.
+   */
+  std::string
+  toString();
 
 private:
   /**
@@ -180,6 +188,10 @@
   bool m_isFinalized;
 };
 
+template<typename Hash>
+std::ostream&
+operator<<(std::ostream& os, Digest<Hash>& digest);
+
 /**
  * @brief A digest using SHA256 as the hash function.
  */
diff --git a/tests/unit-tests/util/test-digest.cpp b/tests/unit-tests/util/test-digest.cpp
index e38dad2..6a43067 100644
--- a/tests/unit-tests/util/test-digest.cpp
+++ b/tests/unit-tests/util/test-digest.cpp
@@ -180,6 +180,30 @@
                                 digest2->buf() + digest2->size());
 }
 
+BOOST_AUTO_TEST_CASE(Print)
+{
+  using namespace CryptoPP;
+
+  uint8_t origin[32] = {0x94, 0xEE, 0x05, 0x93, 0x35, 0xE5, 0x87, 0xE5,
+                        0x01, 0xCC, 0x4B, 0xF9, 0x06, 0x13, 0xE0, 0x81,
+                        0x4F, 0x00, 0xA7, 0xB0, 0x8B, 0xC7, 0xC6, 0x48,
+                        0xFD, 0x86, 0x5A, 0x2A, 0xF6, 0xA2, 0x2C, 0xC2};
+
+  std::string hexString;
+  StringSource(origin, 32, true, new HexEncoder(new StringSink(hexString)));
+
+  std::string str("TEST");
+  Sha256 digest;
+  digest << str;
+
+  std::ostringstream os;
+  os << digest;
+
+  BOOST_CHECK_EQUAL(os.str(), hexString);
+  BOOST_CHECK_EQUAL(digest.toString(), hexString);
+
+}
+
 BOOST_AUTO_TEST_SUITE_END()
 
 } // namespace test