security: Add SignatureSha256

Change-Id: Id9a61f898d12a6b289a24adb594471b26d3513d6
diff --git a/src/security/certificate-cache-ttl.cpp b/src/security/certificate-cache-ttl.cpp
index 0892789..6f831d0 100644
--- a/src/security/certificate-cache-ttl.cpp
+++ b/src/security/certificate-cache-ttl.cpp
@@ -11,7 +11,7 @@
 
 #include "../util/logging.hpp"
 
-INIT_LOGGER("CertificateCacheTtl")
+INIT_LOGGER("ndn.CertificateCacheTtl")
 
 using namespace std;
 
diff --git a/src/security/certificate.cpp b/src/security/certificate.cpp
index f0dfdf2..0312fd5 100644
--- a/src/security/certificate.cpp
+++ b/src/security/certificate.cpp
@@ -19,7 +19,7 @@
 
 #include "../encoding/cryptopp/asn_ext.hpp"
 
-INIT_LOGGER("ndn.security.Certificate");
+INIT_LOGGER("ndn.Certificate");
 
 using namespace std;
 
diff --git a/src/security/key-chain.hpp b/src/security/key-chain.hpp
index e1fcb79..28642ae 100644
--- a/src/security/key-chain.hpp
+++ b/src/security/key-chain.hpp
@@ -12,9 +12,11 @@
 #include "identity-certificate.hpp"
 #include "public-key.hpp"
 #include "signature-sha256-with-rsa.hpp"
+#include "signature-sha256.hpp"
 #include "secured-bag.hpp"
 #include "../interest.hpp"
 #include "../util/random.hpp"
+#include "../util/crypto.hpp"
 
 //PublicInfo
 #include "sec-public-info-sqlite3.hpp"
@@ -288,7 +290,7 @@
     // We either get or create the signing certificate, sign packet! (no exception unless fatal error in TPM)
     sign(packet, signingCertificateName);
   }
-
+  
   /**
    * @brief Sign the byte array using the default certificate of a particular identity.
    *
@@ -316,6 +318,24 @@
   }
 
   /**
+   * @brief Set Sha256 weak signature.
+   *
+   * @param data.
+   */
+  void
+  signWithSha256(Data& data)
+  {
+    SignatureSha256 sig;
+    data.setSignature(sig);
+
+    Block sigValue(Tlv::SignatureValue, 
+                   crypto::sha256(data.wireEncode().value(), 
+                                  data.wireEncode().value_size() - data.getSignature().getValue().size()));
+    data.setSignatureValue(sigValue);
+
+  }
+
+  /**
    * @brief Generate a self-signed certificate for a public key.
    *
    * @param keyName The name of the public key.
diff --git a/src/security/sec-public-info-sqlite3.cpp b/src/security/sec-public-info-sqlite3.cpp
index 3cf24a8..16041d3 100644
--- a/src/security/sec-public-info-sqlite3.cpp
+++ b/src/security/sec-public-info-sqlite3.cpp
@@ -26,7 +26,7 @@
 
 
 
-INIT_LOGGER("BasicKeyMetaInfo");
+INIT_LOGGER("ndn.SecPublicInfoSqlite3");
 
 using namespace std;
 
diff --git a/src/security/sec-rule-relative.cpp b/src/security/sec-rule-relative.cpp
index db3e653..1fdfa7d 100644
--- a/src/security/sec-rule-relative.cpp
+++ b/src/security/sec-rule-relative.cpp
@@ -14,7 +14,7 @@
 
 #include "../util/logging.hpp"
 
-INIT_LOGGER ("SecRuleRelative");
+INIT_LOGGER ("ndn.SecRuleRelative");
 
 using namespace std;
 
diff --git a/src/security/sec-tpm-osx.cpp b/src/security/sec-tpm-osx.cpp
index 383f021..6436b5a 100644
--- a/src/security/sec-tpm-osx.cpp
+++ b/src/security/sec-tpm-osx.cpp
@@ -26,7 +26,7 @@
 
 using namespace std;
 
-INIT_LOGGER("SecTpmOsx");
+INIT_LOGGER("ndn.SecTpmOsx");
 
 namespace ndn {
 
diff --git a/src/security/signature-sha256-with-rsa.hpp b/src/security/signature-sha256-with-rsa.hpp
index c9db4a3..e04ef78 100644
--- a/src/security/signature-sha256-with-rsa.hpp
+++ b/src/security/signature-sha256-with-rsa.hpp
@@ -1,7 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
 /**
  * Copyright (C) 2013 Regents of the University of California.
- * @author: Jeff Thompson <jefft0@remap.ucla.edu>
  * See COPYING for copyright and distribution information.
  */
 
diff --git a/src/security/signature-sha256.hpp b/src/security/signature-sha256.hpp
new file mode 100644
index 0000000..99b550d
--- /dev/null
+++ b/src/security/signature-sha256.hpp
@@ -0,0 +1,38 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/**
+ * Copyright (C) 2013 Regents of the University of California.
+ * See COPYING for copyright and distribution information.
+ */
+
+#ifndef NDN_SECURITY_SIGNATURE_SHA256_HPP
+#define NDN_SECURITY_SIGNATURE_SHA256_HPP
+
+#include "../data.hpp"
+#include "../encoding/tlv.hpp"
+
+namespace ndn {
+
+/**
+ * Representing of SHA256 signature in a data packet.
+ */
+class SignatureSha256 : public Signature {
+public:
+  SignatureSha256()
+  {
+    info_ = Block(Tlv::SignatureInfo);
+    
+    type_ = Signature::Sha256;
+    info_.push_back(nonNegativeIntegerBlock(Tlv::SignatureType, Tlv::DigestSha256));
+  }
+  
+  SignatureSha256(const Signature &signature)
+    : Signature(signature)
+  {
+    if (getType() != Signature::Sha256)
+      throw Signature::Error("Incorrect signature type");
+  }
+};
+
+} // namespace ndn
+
+#endif //NDN_SECURITY_SIGNATURE_SHA256_HPP
diff --git a/src/security/validator-regex.cpp b/src/security/validator-regex.cpp
index 85fb534..ec22de8 100644
--- a/src/security/validator-regex.cpp
+++ b/src/security/validator-regex.cpp
@@ -13,7 +13,7 @@
 
 #include "../util/logging.hpp"
 
-INIT_LOGGER("ndn::ValidatorRegex");
+INIT_LOGGER("ndn.ValidatorRegex");
 
 using namespace std;
 
diff --git a/src/security/validator.cpp b/src/security/validator.cpp
index cabd082..1e5aedc 100644
--- a/src/security/validator.cpp
+++ b/src/security/validator.cpp
@@ -10,12 +10,16 @@
 
 #include "validator.hpp"
 #include "../util/logging.hpp"
+#include "../util/crypto.hpp"
 
 #include <cryptopp/rsa.h>
+#include <cryptopp/files.h>
+#include <cryptopp/hex.h>
+
 
 using namespace std;
 
-INIT_LOGGER("ndn::Validator");
+INIT_LOGGER("ndn.Validator");
 
 namespace ndn {
 
@@ -137,7 +141,7 @@
 }
 
 bool
-Validator::verifySignature(const Interest &interest, const PublicKey &key)
+Validator::verifySignature(const Interest& interest, const PublicKey& key)
 {
   const Name &interestName = interest.getName();
 
@@ -181,7 +185,7 @@
 }
 
 bool
-Validator::verifySignature(const Buffer &data, const Signature &sig, const PublicKey &key)
+Validator::verifySignature(const Buffer& data, const Signature& sig, const PublicKey& key)
 {
   try
     {
@@ -207,7 +211,7 @@
 }
 
 bool
-Validator::verifySignature(const uint8_t* buf, const size_t size, const SignatureSha256WithRsa &sig, const PublicKey &key)
+Validator::verifySignature(const uint8_t* buf, const size_t size, const SignatureSha256WithRsa& sig, const PublicKey& key)
 {
   try
     {
@@ -229,4 +233,35 @@
     }
 }
 
+bool
+Validator::verifySignature(const uint8_t* buf, const size_t size, const SignatureSha256& sig)
+{
+  try
+    {
+      ConstBufferPtr buffer = crypto::sha256(buf, size);
+      const Block& sigValue = sig.getValue();
+
+      if(static_cast<bool>(buffer) 
+         && buffer->size() == sigValue.value_size()
+         && buffer->size() == crypto::SHA256_DIGEST_LENGTH)
+        {
+
+          const uint8_t* p1 = buffer->buf();
+          const uint8_t* p2 = sigValue.value();
+
+          for(int i = 0; i < crypto::SHA256_DIGEST_LENGTH; i++)
+            if(p1[i] != p2[i]) 
+              return false;
+          return true;
+        }
+      else
+        return false;
+    }
+  catch(CryptoPP::Exception& e)
+    {
+      _LOG_DEBUG("verifySignature: " << e.what());
+      return false;
+    }
+}
+
 } // namespace ndn
diff --git a/src/security/validator.hpp b/src/security/validator.hpp
index 4aae107..5147dd7 100644
--- a/src/security/validator.hpp
+++ b/src/security/validator.hpp
@@ -15,6 +15,7 @@
 #include "../face.hpp"
 #include "public-key.hpp"
 #include "signature-sha256-with-rsa.hpp"
+#include "signature-sha256.hpp"
 #include "validation-request.hpp"
 
 namespace ndn {
@@ -59,15 +60,15 @@
 
   /// @brief Verify the data using the publicKey.
   static bool
-  verifySignature (const Data &data, const PublicKey &publicKey);
+  verifySignature (const Data& data, const PublicKey& publicKey);
 
   /// @brief Verify the signed Interest using the publicKey.
   static bool
-  verifySignature (const Interest &interest, const PublicKey &publicKey);
+  verifySignature (const Interest& interest, const PublicKey& publicKey);
 
   /// @brief Verify the blob using the publicKey against the signature.
   static bool
-  verifySignature (const Buffer &blob, const Signature &sig, const PublicKey &publicKey);
+  verifySignature (const Buffer& blob, const Signature& sig, const PublicKey& publicKey);
 
   /// @brief Verify the data using the publicKey against the SHA256-RSA signature.
   static bool
@@ -78,13 +79,31 @@
 
   /// @brief Verify the blob using the publicKey against the SHA256-RSA signature.
   static bool
-  verifySignature (const Buffer &blob, const SignatureSha256WithRsa &sig, const PublicKey &publicKey)
+  verifySignature (const Buffer& blob, const SignatureSha256WithRsa& sig, const PublicKey& publicKey)
   { return verifySignature (blob.buf(), blob.size(), sig, publicKey); }
   
   /// @brief Verify the blob using the publicKey against the SHA256-RSA signature.
   static bool
   verifySignature (const uint8_t* buf, const size_t size, const SignatureSha256WithRsa &sig, const PublicKey &publicKey);
 
+
+  /// @brief Verify the data against the SHA256 signature.
+  static bool
+  verifySignature (const Data& data, const SignatureSha256& sig)
+  { return verifySignature (data.wireEncode().value(), 
+                            data.wireEncode().value_size() - data.getSignature().getValue().size(), 
+                            sig); }
+
+  /// @brief Verify the blob against the SHA256 signature.
+  static bool
+  verifySignature (const Buffer& blob, const SignatureSha256& sig)
+  { return verifySignature (blob.buf(), blob.size(), sig); }
+  
+  /// @brief Verify the blob against the SHA256 signature.
+  static bool
+  verifySignature (const uint8_t* buf, const size_t size, const SignatureSha256& sig);
+
+
 protected:
   /**
    * @brief Check the Data against validation policy and return the next validation step if necessary.
diff --git a/src/util/command-interest-validator.hpp b/src/util/command-interest-validator.hpp
index 8c5ecc3..af8c796 100644
--- a/src/util/command-interest-validator.hpp
+++ b/src/util/command-interest-validator.hpp
@@ -116,7 +116,7 @@
     }
   if(inScope == false)
     return onValidationFailed(interest.shared_from_this(), 
-                              "Signer cannot be authorized for the command: " + interest.getName().toUri());
+                              "Signer cannot be authorized for the command: " + keyName.toUri());
 
   //Check if timestamp is valid
   uint64_t timestamp = interestName.get(POS_TIMESTAMP).toNumber();
diff --git a/src/util/crypto.cpp b/src/util/crypto.cpp
index 8967523..b0767fa 100644
--- a/src/util/crypto.cpp
+++ b/src/util/crypto.cpp
@@ -1,21 +1,54 @@
 /**
  * Copyright (C) 2013 Regents of the University of California.
- * @author: Jeff Thompson <jefft0@remap.ucla.edu>
  * See COPYING for copyright and distribution information.
  */
 
-#include "common.hpp"
+#include "../common.hpp"
 
 #include "crypto.hpp"
+#include <cryptopp/sha.h>
+#include <cryptopp/filters.h>
+#include <cryptopp/files.h>
 
 namespace ndn {
 
 void ndn_digestSha256(const uint8_t *data, size_t dataLength, uint8_t *digest)
 {
-  SHA256_CTX sha256;
-  SHA256_Init(&sha256);
-  SHA256_Update(&sha256, data, dataLength);
-  SHA256_Final(digest, &sha256);
+  try
+    {
+      using namespace CryptoPP;
+      
+      CryptoPP::SHA256 hash;
+      OBufferStream os;
+      StringSource(data, dataLength, true, new HashFilter(hash, new ArraySink(digest, crypto::SHA256_DIGEST_LENGTH)));
+    }
+  catch(CryptoPP::Exception& e)
+    {
+      return;
+    }
+
 }
 
+namespace crypto {
+
+ConstBufferPtr
+sha256(const uint8_t *data, size_t dataLength)
+{
+  try
+    {
+      using namespace CryptoPP;
+      
+      SHA256 hash;
+      OBufferStream os;
+      StringSource(data, dataLength, true, new HashFilter(hash, new FileSink(os)));
+      return os.buf();
+    }
+  catch(CryptoPP::Exception& e)
+    {
+      return ConstBufferPtr();
+    }
+}
+
+} // namespace crypto
+
 } // namespace ndn
diff --git a/src/util/crypto.hpp b/src/util/crypto.hpp
index 8d4aa0b..21e1e71 100644
--- a/src/util/crypto.hpp
+++ b/src/util/crypto.hpp
@@ -1,6 +1,5 @@
 /**
  * Copyright (C) 2013 Regents of the University of California.
- * @author: Jeff Thompson <jefft0@remap.ucla.edu>
  * See COPYING for copyright and distribution information.
  */
 
@@ -8,9 +7,7 @@
 #define NDN_UTIL_CRYPTO_HPP
 
 #include "../common.hpp"
-
-#include <openssl/ssl.h>
-#include <openssl/rsa.h>
+#include "../encoding/buffer.hpp"
 
 namespace ndn {
 
@@ -22,6 +19,21 @@
  */
 void ndn_digestSha256(const uint8_t *data, size_t dataLength, uint8_t *digest);
 
+namespace crypto {
+
+static size_t SHA256_DIGEST_LENGTH = 32;
+
+/**
+ * Compute the sha-256 digest of data.
+ * @param data Pointer to the input byte array.
+ * @param dataLength The length of data.
+ * @return A pointer to a buffer of SHA256_DIGEST.
+ */
+ConstBufferPtr
+sha256(const uint8_t *data, size_t dataLength);
+
+} // namespace crypto
+
 } // namespace ndn
 
 #endif // NDN_UTIL_CRYPTO_HPP
diff --git a/src/util/regex/regex-top-matcher.cpp b/src/util/regex/regex-top-matcher.cpp
index 2c93f17..38f1a5a 100644
--- a/src/util/regex/regex-top-matcher.cpp
+++ b/src/util/regex/regex-top-matcher.cpp
@@ -10,10 +10,6 @@
 #include "regex-backref-manager.hpp"
 #include "regex-pattern-list-matcher.hpp"
 
-// #include "../logging.hpp"
-
-// INIT_LOGGER ("RegexTopMatcher");
-
 namespace ndn {
 
 RegexTopMatcher::RegexTopMatcher(const std::string& expr, const std::string& expand)
@@ -21,13 +17,9 @@
     m_expand(expand),
     m_secondaryUsed(false)
 {
-  // _LOG_TRACE ("Enter RegexTopMatcher Constructor");
-
   m_primaryBackRefManager = make_shared<RegexBackrefManager>();
   m_secondaryBackRefManager = make_shared<RegexBackrefManager>();
   compile();
-
-  // _LOG_TRACE ("Exit RegexTopMatcher Constructor");
 }
 
 RegexTopMatcher::~RegexTopMatcher()
@@ -38,8 +30,6 @@
 void 
 RegexTopMatcher::compile()
 {
-  // _LOG_TRACE ("Enter RegexTopMatcher::compile");
-
   std::string errMsg = "Error: RegexTopMatcher.Compile(): ";
 
   std::string expr = m_expr;
@@ -55,19 +45,13 @@
   else
     expr = expr.substr(1, expr.size()-1);
 
-  // _LOG_DEBUG ("reconstructed expr: " << expr);
-
   m_primaryMatcher = make_shared<RegexPatternListMatcher>(boost::cref(expr),
                                                           boost::cref(m_primaryBackRefManager));
-
-  // _LOG_TRACE ("Exit RegexTopMatcher::compile");
 }
 
 bool 
 RegexTopMatcher::match(const Name & name)
 {
-  // _LOG_DEBUG("Enter RegexTopMatcher::match");
-
   m_secondaryUsed = false;
 
   m_matchResult.clear();
@@ -98,8 +82,6 @@
 Name 
 RegexTopMatcher::expand (const std::string& expandStr)
 {
-  // _LOG_TRACE("Enter RegexTopMatcher::expand");
-
   Name result;
     
   shared_ptr<RegexBackrefManager> backRefManager = (m_secondaryUsed ? m_secondaryBackRefManager : m_primaryBackRefManager);
@@ -149,7 +131,6 @@
 std::string
 RegexTopMatcher::getItemFromExpand(const std::string& expand, int & offset)
 {
-  // _LOG_TRACE("Enter RegexTopMatcher::getItemFromExpand ");
   int begin = offset;
 
   if(expand[offset] == '\\')
diff --git a/tests/security/test-signature-sha256.cpp b/tests/security/test-signature-sha256.cpp
new file mode 100644
index 0000000..bb1b756
--- /dev/null
+++ b/tests/security/test-signature-sha256.cpp
@@ -0,0 +1,56 @@
+/**
+ * Copyright (C) 2013 Regents of the University of California.
+ * @author: Yingdi Yu <yingdi0@cs.ucla.edu>
+ * See COPYING for copyright and distribution information.
+ */
+
+#include <boost/test/unit_test.hpp>
+
+#include "security/key-chain.hpp"
+#include "security/validator.hpp"
+
+#include <cryptopp/base64.h>
+#include <cryptopp/hex.h>
+#include <cryptopp/files.h>
+
+using namespace std;
+namespace ndn {
+
+BOOST_AUTO_TEST_SUITE(TestSignatureSha256)
+
+string SHA256_RESULT("a883dafc480d466ee04e0d6da986bd78eb1fdd2178d04693723da3a8f95d42f4");
+
+BOOST_AUTO_TEST_CASE (Sha256)
+{
+  using namespace CryptoPP;
+
+  char content[6] = "1234\n";
+  ConstBufferPtr buf = crypto::sha256(reinterpret_cast<uint8_t*>(content), 5);
+  string result;
+  StringSource(buf->buf(), buf->size(), true, new HexEncoder(new StringSink(result), false));
+
+  BOOST_REQUIRE_EQUAL(SHA256_RESULT, result);
+}
+
+BOOST_AUTO_TEST_CASE (Signature)
+{
+  using namespace CryptoPP;
+
+  Name name("/TestSignatureSha/Basic");
+  Data testData(name);
+  char content[5] = "1234";
+  testData.setContent(reinterpret_cast<uint8_t*>(content), 5);
+  
+  KeyChainImpl<SecPublicInfoSqlite3, SecTpmFile> keychain;
+  keychain.signWithSha256(testData);
+
+  testData.wireEncode();
+
+  SignatureSha256 sig(testData.getSignature());
+  
+  BOOST_REQUIRE(Validator::verifySignature(testData, sig));
+}
+
+BOOST_AUTO_TEST_SUITE_END()
+
+} // namespace ndn