util: reimplement Sha256 using security::transform

Change-Id: I4d01638a19867f39380dd0bee922c58148741506
Refs: #3924
diff --git a/src/util/digest.cpp b/src/util/digest.cpp
index 68c53ce..516255f 100644
--- a/src/util/digest.cpp
+++ b/src/util/digest.cpp
@@ -1,5 +1,5 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
-/**
+/*
  * Copyright (c) 2013-2017 Regents of the University of California.
  *
  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
@@ -21,7 +21,11 @@
 
 #include "digest.hpp"
 #include "string-helper.hpp"
-#include "security/detail/openssl.hpp"
+#include "../security/detail/openssl.hpp"
+#include "../security/transform/digest-filter.hpp"
+#include "../security/transform/stream-sink.hpp"
+#include "../security/transform/stream-source.hpp"
+#include "../security/v1/cryptopp.hpp"
 
 #include <sstream>
 
@@ -175,13 +179,118 @@
   return os;
 }
 
-template
-class Digest<CryptoPP::SHA256>;
 
-template
+////////////////////////////////////////
+
+
+Sha256::Sha256()
+{
+  reset();
+}
+
+Sha256::Sha256(std::istream& is)
+  : m_output(make_unique<OBufferStream>())
+  , m_isEmpty(false)
+  , m_isFinalized(true)
+{
+  namespace tr = security::transform;
+
+  tr::streamSource(is) >> tr::digestFilter(DigestAlgorithm::SHA256) >> tr::streamSink(*m_output);
+}
+
+void
+Sha256::reset()
+{
+  namespace tr = security::transform;
+
+  m_input = make_unique<tr::StepSource>();
+  m_output = make_unique<OBufferStream>();
+  m_isEmpty = true;
+  m_isFinalized = false;
+
+  *m_input >> tr::digestFilter(DigestAlgorithm::SHA256) >> tr::streamSink(*m_output);
+}
+
+ConstBufferPtr
+Sha256::computeDigest()
+{
+  if (!m_isFinalized) {
+    BOOST_ASSERT(m_input != nullptr);
+    m_input->end();
+    m_isFinalized = true;
+  }
+
+  return m_output->buf();
+}
+
+bool
+Sha256::operator==(Sha256& digest)
+{
+  const Buffer& lhs = *computeDigest();
+  const Buffer& rhs = *digest.computeDigest();
+
+  if (lhs.size() != rhs.size()) {
+    return false;
+  }
+
+  // constant-time buffer comparison to mitigate timing attacks
+  return CRYPTO_memcmp(lhs.get(), rhs.get(), lhs.size()) == 0;
+}
+
+Sha256&
+Sha256::operator<<(Sha256& src)
+{
+  auto buf = src.computeDigest();
+  update(buf->get(), buf->size());
+  return *this;
+}
+
+Sha256&
+Sha256::operator<<(const std::string& str)
+{
+  update(reinterpret_cast<const uint8_t*>(str.data()), str.size());
+  return *this;
+}
+
+Sha256&
+Sha256::operator<<(const Block& block)
+{
+  update(block.wire(), block.size());
+  return *this;
+}
+
+Sha256&
+Sha256::operator<<(uint64_t value)
+{
+  update(reinterpret_cast<const uint8_t*>(&value), sizeof(uint64_t));
+  return *this;
+}
+
+void
+Sha256::update(const uint8_t* buffer, size_t size)
+{
+  if (m_isFinalized)
+    BOOST_THROW_EXCEPTION(Error("Digest has been already finalized"));
+
+  BOOST_ASSERT(m_input != nullptr);
+  m_input->write(buffer, size);
+  m_isEmpty = false;
+}
+
+std::string
+Sha256::toString()
+{
+  auto buf = computeDigest();
+  return toHex(*buf);
+}
+
 std::ostream&
-operator<<(std::ostream& os, Digest<CryptoPP::SHA256>& digest);
-
+operator<<(std::ostream& os, Sha256& digest)
+{
+  auto buf = digest.computeDigest();
+  printHex(os, *buf);
+  return os;
+}
 
 } // namespace util
 } // namespace ndn
diff --git a/src/util/digest.hpp b/src/util/digest.hpp
index 41e45a5..40d0100 100644
--- a/src/util/digest.hpp
+++ b/src/util/digest.hpp
@@ -1,5 +1,5 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
-/**
+/*
  * Copyright (c) 2013-2017 Regents of the University of California.
  *
  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
@@ -22,10 +22,11 @@
 #ifndef NDN_UTIL_DIGEST_HPP
 #define NDN_UTIL_DIGEST_HPP
 
-#include "../encoding/buffer.hpp"
-#include "../encoding/block.hpp"
-#include "../security/v1/cryptopp.hpp"
 #include "concepts.hpp"
+#include "crypto.hpp"
+#include "../encoding/block.hpp"
+#include "../encoding/buffer-stream.hpp"
+#include "../security/transform/step-source.hpp"
 
 namespace ndn {
 namespace util {
@@ -194,10 +195,153 @@
 std::ostream&
 operator<<(std::ostream& os, Digest<Hash>& digest);
 
+
 /**
- * @brief A digest using SHA256 as the hash function.
+ * @brief Provides stateful SHA-256 digest calculation.
+ *
+ * Example:
+ * @code
+ * Sha256 digest;
+ * digest.update(buf1, size1);
+ * digest.update(buf2, size2);
+ * ...
+ * ConstBufferPtr result = digest.computeDigest();
+ * @endcode
  */
-typedef Digest<CryptoPP::SHA256> Sha256;
+class Sha256
+{
+public:
+  class Error : public std::runtime_error
+  {
+  public:
+    explicit
+    Error(const std::string& what)
+      : std::runtime_error(what)
+    {
+    }
+  };
+
+  /**
+   * @brief Create an empty SHA-256 digest.
+   */
+  Sha256();
+
+  /**
+   * @brief Calculate SHA-256 digest of the input stream @p is.
+   */
+  explicit
+  Sha256(std::istream& is);
+
+  /**
+   * @brief Check if digest is empty.
+   *
+   * An empty digest means nothing has been taken into calculation.
+   */
+  bool
+  empty() const
+  {
+    return m_isEmpty;
+  }
+
+  /**
+   * @brief Discard the current state and start a new digest calculation.
+   */
+  void
+  reset();
+
+  /**
+   * @brief Finalize and return the digest based on all previously supplied inputs.
+   */
+  ConstBufferPtr
+  computeDigest();
+
+  /**
+   * @brief Check if the supplied digest is equal to this digest.
+   * @note This method invokes computeDigest() on both operands, finalizing the digest.
+   */
+  bool
+  operator==(Sha256& digest);
+
+  /**
+   * @brief Check if the supplied digest is not equal to this digest.
+   * @note This method invokes computeDigest() on both operands, finalizing the digest.
+   */
+  bool
+  operator!=(Sha256& digest)
+  {
+    return !(*this == digest);
+  }
+
+  /**
+   * @brief Add existing digest to the digest calculation.
+   * @param src digest to combine with
+   *
+   * The result of this combination is `sha256(sha256(...))`
+   *
+   * @note This method invokes computeDigest() on @p src, finalizing the digest.
+   * @throw Error the digest has already been finalized
+   */
+  Sha256&
+  operator<<(Sha256& src);
+
+  /**
+   * @brief Add a string to the digest calculation.
+   * @throw Error the digest has already been finalized
+   */
+  Sha256&
+  operator<<(const std::string& str);
+
+  /**
+   * @brief Add a block to the digest calculation.
+   * @throw Error the digest has already been finalized
+   */
+  Sha256&
+  operator<<(const Block& block);
+
+  /**
+   * @brief Add a uint64_t value to the digest calculation.
+   * @throw Error the digest has already been finalized
+   */
+  Sha256&
+  operator<<(uint64_t value);
+
+  /**
+   * @brief Add a raw buffer to the digest calculation.
+   * @param buffer the input buffer
+   * @param size the size of the input buffer
+   * @throw Error the digest has already been finalized
+   */
+  void
+  update(const uint8_t* buffer, size_t size);
+
+  /**
+   * @brief Convert digest to std::string.
+   * @note This method invokes computeDigest(), finalizing the digest.
+   */
+  std::string
+  toString();
+
+  /**
+   * @brief Compute a one-time SHA-256 digest.
+   * @param buffer the input buffer
+   * @param size the size of the input buffer
+   * @return SHA-256 digest of the input buffer
+   */
+  static ConstBufferPtr
+  computeDigest(const uint8_t* buffer, size_t size)
+  {
+    return crypto::computeSha256Digest(buffer, size);
+  }
+
+private:
+  unique_ptr<security::transform::StepSource> m_input;
+  unique_ptr<OBufferStream> m_output;
+  bool m_isEmpty;
+  bool m_isFinalized;
+};
+
+std::ostream&
+operator<<(std::ostream& os, Sha256& digest);
 
 } // namespace util
 } // namespace ndn
diff --git a/tests/unit-tests/util/digest.t.cpp b/tests/unit-tests/util/digest.t.cpp
index 25f75dd..36a72e2 100644
--- a/tests/unit-tests/util/digest.t.cpp
+++ b/tests/unit-tests/util/digest.t.cpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
-/**
- * Copyright (c) 2013-2016 Regents of the University of California.
+/*
+ * Copyright (c) 2013-2017 Regents of the University of California.
  *
  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
  *
@@ -20,7 +20,6 @@
  */
 
 #include "util/digest.hpp"
-#include "util/crypto.hpp"
 #include "util/string-helper.hpp"
 
 #include "boost-test.hpp"
@@ -30,65 +29,47 @@
 namespace test {
 
 BOOST_AUTO_TEST_SUITE(Util)
-BOOST_AUTO_TEST_SUITE(TestDigest)
+BOOST_AUTO_TEST_SUITE(TestSha256)
 
-BOOST_AUTO_TEST_CASE(Sha256Digest)
+BOOST_AUTO_TEST_CASE(Basic)
 {
-  uint8_t origin[4] = {0x01, 0x02, 0x03, 0x04};
-  ConstBufferPtr digest1 = crypto::computeSha256Digest(origin, 4);
+  const uint8_t origin[] = {0x01, 0x02, 0x03, 0x04};
+  ConstBufferPtr digest1 = crypto::computeSha256Digest(origin, sizeof(origin));
 
   Sha256 statefulSha256;
+  BOOST_CHECK_EQUAL(statefulSha256.empty(), true);
+
   statefulSha256.update(origin, 1);
   statefulSha256.update(origin + 1, 1);
   statefulSha256.update(origin + 2, 1);
   statefulSha256.update(origin + 3, 1);
   ConstBufferPtr digest2 = statefulSha256.computeDigest();
-
-  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(),
-                                digest1->buf() + digest1->size(),
-                                digest2->buf(),
-                                digest2->buf() + digest2->size());
-}
-
-BOOST_AUTO_TEST_CASE(Compute)
-{
-  std::string input = "Hello, World!";
-  ConstBufferPtr digest1 = crypto::computeSha256Digest(reinterpret_cast<const uint8_t*>(input.data()),
-                                                       input.size());
-
-  Sha256 hashObject;
-  hashObject << input;
-  BOOST_CHECK_EQUAL(hashObject.toString(), "DFFD6021BB2BD5B0AF676290809EC3A53191DD81C7F70A4B28688A362182986F");
-  ConstBufferPtr digest2 = hashObject.computeDigest();
-  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(),
-                                digest1->buf() + digest1->size(),
-                                digest2->buf(),
-                                digest2->buf() + digest2->size());
-
+  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(), digest1->buf() + digest1->size(),
+                                digest2->buf(), digest2->buf() + digest2->size());
 }
 
 BOOST_AUTO_TEST_CASE(ConstructFromStream)
 {
-  std::string input = "Hello, World!";
+  const std::string input = "Hello, World!";
   ConstBufferPtr digest1 = crypto::computeSha256Digest(reinterpret_cast<const uint8_t*>(input.data()),
                                                        input.size());
 
   std::istringstream is(input);
-  Sha256 hashObject(is);
-  BOOST_CHECK_EQUAL(hashObject.toString(), "DFFD6021BB2BD5B0AF676290809EC3A53191DD81C7F70A4B28688A362182986F");
-  ConstBufferPtr digest2 = hashObject.computeDigest();
-  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(),
-                                digest1->buf() + digest1->size(),
-                                digest2->buf(),
-                                digest2->buf() + digest2->size());
+  Sha256 sha(is);
+  BOOST_CHECK_EQUAL(sha.empty(), false);
+  BOOST_CHECK_EQUAL(sha.toString(), "DFFD6021BB2BD5B0AF676290809EC3A53191DD81C7F70A4B28688A362182986F");
+
+  ConstBufferPtr digest2 = sha.computeDigest();
+  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(), digest1->buf() + digest1->size(),
+                                digest2->buf(), digest2->buf() + digest2->size());
 }
 
 BOOST_AUTO_TEST_CASE(Compare)
 {
-  uint8_t origin[4] = {0x01, 0x02, 0x03, 0x04};
+  const uint8_t origin[] = {0x01, 0x02, 0x03, 0x04};
 
   Sha256 digest;
-  digest.update(origin, 4);
+  digest.update(origin, sizeof(origin));
   digest.computeDigest();
 
   Sha256 digest2;
@@ -98,51 +79,46 @@
   digest2.update(origin + 3, 1);
   digest2.computeDigest();
 
-  BOOST_CHECK(digest == digest2);
+  BOOST_CHECK_EQUAL(digest == digest2, true);
   BOOST_CHECK_EQUAL(digest != digest2, false);
 }
 
-BOOST_AUTO_TEST_CASE(OperatorDigest)
+BOOST_AUTO_TEST_CASE(InsertionOperatorSha256)
 {
-  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};
-  ConstBufferPtr digest1 = crypto::computeSha256Digest(origin, 32);
+  const uint8_t origin[] = {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};
+  ConstBufferPtr digest1 = crypto::computeSha256Digest(origin, sizeof(origin));
 
-  std::string str("TEST");
-  Sha256 metaDigest;
-  metaDigest << str;
+  Sha256 innerDigest;
+  innerDigest << "TEST";
 
   Sha256 statefulSha256;
-  statefulSha256 << metaDigest;
+  statefulSha256 << innerDigest;
   ConstBufferPtr digest2 = statefulSha256.computeDigest();
 
-  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(),
-                                digest1->buf() + digest1->size(),
-                                digest2->buf(),
-                                digest2->buf() + digest2->size());
+  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(), digest1->buf() + digest1->size(),
+                                digest2->buf(), digest2->buf() + digest2->size());
 }
 
-BOOST_AUTO_TEST_CASE(OperatorString)
+BOOST_AUTO_TEST_CASE(InsertionOperatorString)
 {
-  uint8_t origin[4] = {0x54, 0x45, 0x53, 0x54};
-  ConstBufferPtr digest1 = crypto::computeSha256Digest(origin, 4);
+  const std::string str = "Hello, World!";
+  ConstBufferPtr digest1 = crypto::computeSha256Digest(reinterpret_cast<const uint8_t*>(str.data()),
+                                                       str.size());
 
-  std::string str("TEST");
   Sha256 statefulSha256;
   statefulSha256 << str;
   ConstBufferPtr digest2 = statefulSha256.computeDigest();
 
-  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(),
-                                digest1->buf() + digest1->size(),
-                                digest2->buf(),
-                                digest2->buf() + digest2->size());
+  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(), digest1->buf() + digest1->size(),
+                                digest2->buf(), digest2->buf() + digest2->size());
 }
 
-BOOST_AUTO_TEST_CASE(OperatorBlock)
+BOOST_AUTO_TEST_CASE(InsertionOperatorBlock)
 {
-  uint8_t origin[] = {
+  const uint8_t origin[] = {
     0x16, 0x1b, // SignatureInfo
       0x1b, 0x01, // SignatureType
         0x01, // Sha256WithRsa
@@ -162,16 +138,15 @@
   statefulSha256 << block;
   ConstBufferPtr digest2 = statefulSha256.computeDigest();
 
-  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(),
-                                digest1->buf() + digest1->size(),
-                                digest2->buf(),
-                                digest2->buf() + digest2->size());
+  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(), digest1->buf() + digest1->size(),
+                                digest2->buf(), digest2->buf() + digest2->size());
 }
 
-BOOST_AUTO_TEST_CASE(OperatorUint64t)
+BOOST_AUTO_TEST_CASE(InsertionOperatorUint64t)
 {
-  uint64_t origin[4] = {1, 2, 3, 4};
-  ConstBufferPtr digest1 = crypto::computeSha256Digest(reinterpret_cast<uint8_t*>(origin), 32);
+  const uint64_t origin[] = {1, 2, 3, 4};
+  ConstBufferPtr digest1 = crypto::computeSha256Digest(reinterpret_cast<const uint8_t*>(origin),
+                                                       sizeof(origin));
 
   Sha256 statefulSha256;
   statefulSha256 << origin[0];
@@ -180,61 +155,58 @@
   statefulSha256 << origin[3];
   ConstBufferPtr digest2 = statefulSha256.computeDigest();
 
-  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(),
-                                digest1->buf() + digest1->size(),
-                                digest2->buf(),
-                                digest2->buf() + digest2->size());
+  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(), digest1->buf() + digest1->size(),
+                                digest2->buf(), digest2->buf() + digest2->size());
+}
+
+BOOST_AUTO_TEST_CASE(Reset)
+{
+  Sha256 sha;
+  BOOST_CHECK_EQUAL(sha.empty(), true);
+
+  sha << 42;
+  BOOST_CHECK_EQUAL(sha.empty(), false);
+
+  sha.computeDigest(); // finalize
+  sha.reset();
+  BOOST_CHECK_EQUAL(sha.empty(), true);
+  BOOST_CHECK_NO_THROW(sha << 42);
 }
 
 BOOST_AUTO_TEST_CASE(Error)
 {
-  uint64_t origin = 256;
-
-  Sha256 digest;
-  BOOST_CHECK(digest.empty());
-
-  digest << origin;
-
-  BOOST_CHECK_NO_THROW(digest.computeDigest());
-  BOOST_CHECK_THROW(digest << origin, Sha256::Error);
-
-  digest.reset();
+  Sha256 sha;
+  sha << 42;
+  sha.computeDigest(); // finalize
+  BOOST_CHECK_THROW(sha << 42, Sha256::Error);
 }
 
-BOOST_AUTO_TEST_CASE(ComputeDigest)
+BOOST_AUTO_TEST_CASE(StaticComputeDigest)
 {
-  uint8_t origin[4] = {0x01, 0x02, 0x03, 0x04};
-  ConstBufferPtr digest1 = crypto::computeSha256Digest(origin, 4);
-
-  ConstBufferPtr digest2 = Sha256::computeDigest(origin, 4);
-
-  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(),
-                                digest1->buf() + digest1->size(),
-                                digest2->buf(),
-                                digest2->buf() + digest2->size());
+  const uint8_t origin[] = {0x01, 0x02, 0x03, 0x04};
+  ConstBufferPtr digest1 = crypto::computeSha256Digest(origin, sizeof(origin));
+  ConstBufferPtr digest2 = Sha256::computeDigest(origin, sizeof(origin));
+  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(), digest1->buf() + digest1->size(),
+                                digest2->buf(), digest2->buf() + digest2->size());
 }
 
 BOOST_AUTO_TEST_CASE(Print)
 {
-  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};
+  const uint8_t origin[] = {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 = toHex(origin, sizeof(origin));
 
-  std::string hexString = toHex(origin, 32);
-
-  std::string str("TEST");
   Sha256 digest;
-  digest << str;
-
+  digest << "TEST";
   std::ostringstream os;
   os << digest;
-
   BOOST_CHECK_EQUAL(os.str(), hexString);
   BOOST_CHECK_EQUAL(digest.toString(), hexString);
 }
 
-BOOST_AUTO_TEST_SUITE_END() // TestDigest
+BOOST_AUTO_TEST_SUITE_END() // TestSha256
 BOOST_AUTO_TEST_SUITE_END() // Util
 
 } // namespace test