util: Add stateful digest

Change-Id: I6ed564dc9146d180cec2848a73ec9e8e8f10d921
Refs: #1934
diff --git a/src/util/concepts.hpp b/src/util/concepts.hpp
index dee15d3..94baeaa 100644
--- a/src/util/concepts.hpp
+++ b/src/util/concepts.hpp
@@ -49,6 +49,23 @@
   }
 };
 
+template<class X>
+class Hashable
+{
+public:
+  BOOST_CONCEPT_USAGE(Hashable)
+  {
+    X hash;
+
+    uint8_t* buf = 0;
+    size_t size = hash.DigestSize();
+
+    hash.Update(buf, size);
+    hash.Final(buf);
+    hash.Restart();
+  }
+};
+
 } // namespace ndn
 
 #endif // NDN_UTIL_CONCEPTS_HPP
diff --git a/src/util/digest.cpp b/src/util/digest.cpp
new file mode 100644
index 0000000..bb2201d
--- /dev/null
+++ b/src/util/digest.cpp
@@ -0,0 +1,136 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2014 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#include "digest.hpp"
+
+namespace ndn {
+namespace util {
+
+template<typename Hash>
+Digest<Hash>::Digest()
+{
+  reset();
+}
+
+template<typename Hash>
+void
+Digest<Hash>::reset()
+{
+  m_hash.Restart();
+  m_buffer = make_shared<Buffer>(m_hash.DigestSize());
+  m_isInProcess = false;
+  m_isFinalized = false;
+}
+
+template<typename Hash>
+void
+Digest<Hash>::finalize()
+{
+  // return immediately if Digest is finalized already.
+  if (m_isFinalized)
+    return;
+
+  m_hash.Final(m_buffer->get());
+
+  m_isFinalized = true;
+}
+
+template<typename Hash>
+ConstBufferPtr
+Digest<Hash>::computeDigest()
+{
+  finalize();
+  return m_buffer;
+}
+
+template<typename Hash>
+bool
+Digest<Hash>::operator==(Digest<Hash>& digest)
+{
+  return *computeDigest() == *digest.computeDigest();
+}
+
+template<typename Hash>
+Digest<Hash>&
+Digest<Hash>::operator<<(Digest<Hash>& src)
+{
+  ConstBufferPtr buffer = src.computeDigest();
+  update(buffer->get(), buffer->size());
+
+  return *this;
+}
+
+template<typename Hash>
+Digest<Hash>&
+Digest<Hash>::operator<<(const std::string& str)
+{
+  update(reinterpret_cast<const uint8_t*>(str.c_str()), str.size());
+
+  return *this;
+}
+
+template<typename Hash>
+Digest<Hash>&
+Digest<Hash>::operator<<(const Block& block)
+{
+  update(block.wire(), block.size());
+
+  return *this;
+}
+
+template<typename Hash>
+Digest<Hash>&
+Digest<Hash>::operator<<(uint64_t value)
+{
+  update(reinterpret_cast<const uint8_t*>(&value), sizeof(uint64_t));
+
+  return *this;
+}
+
+template<typename Hash>
+void
+Digest<Hash>::update(const uint8_t* buffer, size_t size)
+{
+  // cannot update Digest when it has been finalized
+  if (m_isFinalized)
+    throw Error("Digest has been already finalized");
+
+  m_hash.Update(buffer, size);
+
+  m_isInProcess = true;
+}
+
+template<typename Hash>
+ConstBufferPtr
+Digest<Hash>::computeDigest(const uint8_t* buffer, size_t size)
+{
+  Hash hash;
+  BufferPtr result = make_shared<Buffer>(hash.DigestSize());
+  hash.Update(buffer, size);
+  hash.Final(result->get());
+
+  return result;
+}
+
+template class Digest<CryptoPP::SHA256>;
+
+} // namespace util
+} // namespace ndn
diff --git a/src/util/digest.hpp b/src/util/digest.hpp
new file mode 100644
index 0000000..39ff811
--- /dev/null
+++ b/src/util/digest.hpp
@@ -0,0 +1,191 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2014 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#ifndef NDN_UTIL_DIGEST_HPP
+#define NDN_UTIL_DIGEST_HPP
+
+#include "../encoding/buffer.hpp"
+#include "../encoding/block.hpp"
+#include "../security/cryptopp.hpp"
+#include "concepts.hpp"
+
+namespace ndn {
+namespace util {
+
+/**
+ * @brief provides a  digest calculation
+ *
+ * Take SHA256 as an example:
+ *
+ *   Digest<CryptoPP::SHA256> digest;
+ *   digest.update(buf1, size1);
+ *   digest.update(buf2, size2);
+ *   ...
+ *   ConstBufferPtr result = digest.computeDigest();
+ *
+ * @sa http://redmine.named-data.net/issues/1934
+ */
+template<typename Hash>
+class Digest
+{
+public:
+  BOOST_CONCEPT_ASSERT((Hashable<Hash>));
+
+  typedef Hash HashFunction;
+
+  class Error : public std::runtime_error
+  {
+  public:
+    explicit
+    Error(const std::string& what)
+      : std::runtime_error(what)
+    {
+    }
+  };
+
+  Digest();
+
+  /**
+   * @brief Discard the current state and start a new digest.
+   */
+  void
+  reset();
+
+  /**
+   * @brief Check if digest is empty.
+   *
+   * An empty digest means nothing has been taken into calculation.
+   */
+  bool
+  empty() const
+  {
+    return !m_isInProcess;
+  }
+
+  /**
+   * @brief Obtain the digest
+   *
+   * Note this digest is finalized once this method is invoked.
+   */
+  ConstBufferPtr
+  computeDigest();
+
+  /**
+   * @brief Check if supplied digest equal to this digest
+   *
+   * Note that this method will invoke computeDigest().
+   * Once this method is invoked, both this digest and the supplied digest are finalized.
+   */
+  bool
+  operator==(Digest<Hash>& digest);
+
+  /**
+   * @brief Check if supplied digest is not equal to this digest
+   *
+   * Note that this method will invoke computeDigest().
+   * Once this method is invoked, both this digest and the supplied digest are finalized.
+   */
+  bool
+  operator!=(Digest<Hash>& digest)
+  {
+    return !(*this == digest);
+  }
+
+  /**
+   * @brief Add existing digest to digest calculation
+   * @param src digest to combine with
+   *
+   * The result of this combination is  hash (hash (...))
+   * Note that this method will invoke computeDigest().
+   * Once this method is invoked, the supplied digest is fixed.
+   */
+  Digest<Hash>&
+  operator<<(Digest<Hash>& src);
+
+  /**
+   * @brief Add string to digest calculation
+   * @param str string to put into digest
+   */
+  Digest<Hash>&
+  operator<<(const std::string& str);
+
+  /**
+   * @brief Add block to digest calculation
+   * @param block to put into digest
+   */
+  Digest<Hash>&
+  operator<<(const Block& block);
+
+  /**
+   * @brief Add uint64_t value to digest calculation
+   * @param value uint64_t value to put into digest
+   */
+  Digest<Hash>&
+  operator<<(uint64_t value);
+
+  /**
+   * @brief Add a buffer to digest calculation
+   *
+   * Update the state of the digest if it is not finalized
+   * and mark the digest as InProcess.
+   *
+   * @param buffer the input buffer
+   * @param size the size of the input buffer.
+   * @throws Error if the digest has been finalized.
+   */
+  void
+  update(const uint8_t* buffer, size_t size);
+
+  /**
+   * @brief Compute one-time digest
+   * @param buffer the input buffer
+   * @param size the size of the input buffer.
+   * @return digest computed according to the HashAlgorithm
+   */
+  static ConstBufferPtr
+  computeDigest(const uint8_t* buffer, size_t size);
+
+
+private:
+  /**
+   * @brief Finalize digest.
+   *
+   * All subsequent calls to "operator<<" will throw an exception
+   */
+  void
+  finalize();
+
+private:
+  Hash m_hash;
+  BufferPtr m_buffer;
+  bool m_isInProcess;
+  bool m_isFinalized;
+};
+
+/**
+ * @brief A digest using SHA256 as the hash function.
+ */
+typedef Digest<CryptoPP::SHA256> Sha256;
+
+} // namespace util
+} // namespace ndn
+
+#endif // NDN_UTIL_DIGEST_HPP
diff --git a/tests/unit-tests/util/test-digest.cpp b/tests/unit-tests/util/test-digest.cpp
new file mode 100644
index 0000000..e38dad2
--- /dev/null
+++ b/tests/unit-tests/util/test-digest.cpp
@@ -0,0 +1,187 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2014 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#include "util/digest.hpp"
+#include "util/crypto.hpp"
+
+#include "boost-test.hpp"
+
+namespace ndn {
+namespace util {
+namespace test {
+
+BOOST_AUTO_TEST_SUITE(UtilTestDigest)
+
+BOOST_AUTO_TEST_CASE(Sha256Digest)
+{
+  uint8_t origin[4] = {0x01, 0x02, 0x03, 0x04};
+  ConstBufferPtr digest1 = crypto::sha256(origin, 4);
+
+  Sha256 statefulSha256;
+  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(Compare)
+{
+  uint8_t origin[4] = {0x01, 0x02, 0x03, 0x04};
+
+  Sha256 digest;
+  digest.update(origin, 4);
+  digest.computeDigest();
+
+  Sha256 digest2;
+  digest2.update(origin, 1);
+  digest2.update(origin + 1, 1);
+  digest2.update(origin + 2, 1);
+  digest2.update(origin + 3, 1);
+  digest2.computeDigest();
+
+  BOOST_CHECK(digest == digest2);
+  BOOST_CHECK_EQUAL(digest != digest2, false);
+}
+
+BOOST_AUTO_TEST_CASE(OperatorDigest)
+{
+  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::sha256(origin, 32);
+
+  std::string str("TEST");
+  Sha256 metaDigest;
+  metaDigest << str;
+
+  Sha256 statefulSha256;
+  statefulSha256 << metaDigest;
+  ConstBufferPtr digest2 = statefulSha256.computeDigest();
+
+  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(),
+                                digest1->buf() + digest1->size(),
+                                digest2->buf(),
+                                digest2->buf() + digest2->size());
+}
+
+BOOST_AUTO_TEST_CASE(OperatorString)
+{
+  uint8_t origin[4] = {0x54, 0x45, 0x53, 0x54};
+  ConstBufferPtr digest1 = crypto::sha256(origin, 4);
+
+  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_AUTO_TEST_CASE(OperatorBlock)
+{
+  uint8_t origin[] = {
+    0x16, 0x1b, // SignatureInfo
+      0x1b, 0x01, // SignatureType
+        0x01, // Sha256WithRsa
+      0x1c, 0x16, // KeyLocator
+        0x07, 0x14, // Name
+          0x08, 0x04,
+            0x74, 0x65, 0x73, 0x74,
+          0x08, 0x03,
+            0x6b, 0x65, 0x79,
+          0x08, 0x07,
+            0x6c, 0x6f, 0x63, 0x61, 0x74, 0x6f, 0x72
+  };
+  ConstBufferPtr digest1 = crypto::sha256(origin, sizeof(origin));
+
+  Sha256 statefulSha256;
+  Block block(origin, sizeof(origin));
+  statefulSha256 << block;
+  ConstBufferPtr digest2 = statefulSha256.computeDigest();
+
+  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(),
+                                digest1->buf() + digest1->size(),
+                                digest2->buf(),
+                                digest2->buf() + digest2->size());
+}
+
+BOOST_AUTO_TEST_CASE(OperatorUint64t)
+{
+  uint64_t origin[4] = {1, 2, 3, 4};
+  ConstBufferPtr digest1 = crypto::sha256(reinterpret_cast<uint8_t*>(origin), 32);
+
+  Sha256 statefulSha256;
+  statefulSha256 << origin[0];
+  statefulSha256 << origin[1];
+  statefulSha256 << origin[2];
+  statefulSha256 << origin[3];
+  ConstBufferPtr digest2 = statefulSha256.computeDigest();
+
+  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(),
+                                digest1->buf() + digest1->size(),
+                                digest2->buf(),
+                                digest2->buf() + digest2->size());
+}
+
+
+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();
+}
+
+BOOST_AUTO_TEST_CASE(ComputeDigest)
+{
+  uint8_t origin[4] = {0x01, 0x02, 0x03, 0x04};
+  ConstBufferPtr digest1 = crypto::sha256(origin, 4);
+
+  ConstBufferPtr digest2 = Sha256::computeDigest(origin, 4);
+
+  BOOST_CHECK_EQUAL_COLLECTIONS(digest1->buf(),
+                                digest1->buf() + digest1->size(),
+                                digest2->buf(),
+                                digest2->buf() + digest2->size());
+}
+
+BOOST_AUTO_TEST_SUITE_END()
+
+} // namespace test
+} // namespace util
+} // namespace ndn