security: Added initial KeyChain.signData and verifyData
diff --git a/ndn-cpp/node.cpp b/ndn-cpp/node.cpp
index 2cf881f..e132970 100644
--- a/ndn-cpp/node.cpp
+++ b/ndn-cpp/node.cpp
@@ -88,8 +88,11 @@
   Data data;
   data.setContent(content);
   data.getMetaInfo().setTimestampMilliseconds(time(NULL) * 1000.0);
-  // TODO: Should we sign with a different key?
+#if 0
   KeyChain::defaultSign(data);
+#else
+#warning "Should we have the application use KeyChain.signData?"
+#endif
   Blob encodedData = data.wireEncode();
   
   // Create an interest where the name has the encoded Data packet.
diff --git a/ndn-cpp/security/key-chain.cpp b/ndn-cpp/security/key-chain.cpp
index da8108c..b280c41 100644
--- a/ndn-cpp/security/key-chain.cpp
+++ b/ndn-cpp/security/key-chain.cpp
@@ -15,6 +15,7 @@
 
 namespace ndn {
 
+#if 1
 static unsigned char DEFAULT_PUBLIC_KEY_DER[] = {
 0x30, 0x81, 0x9F, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81,
 0x8D, 0x00, 0x30, 0x81, 0x89, 0x02, 0x81, 0x81, 0x00, 0xE1, 0x7D, 0x30, 0xA7, 0xD8, 0x28, 0xAB, 0x1B, 0x84, 0x0B, 0x17,
@@ -26,128 +27,56 @@
 0x17, 0x1B, 0x4D, 0xEE, 0x58, 0x5C, 0x18, 0x28, 0x29, 0x5B, 0x53, 0x95, 0xEB, 0x4A, 0x17, 0x77, 0x9F, 0x02, 0x03, 0x01,
 0x00, 01  
 };
+#endif
 
-static unsigned char DEFAULT_PRIVATE_KEY_DER[] = {
-0x30, 0x82, 0x02, 0x5d, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, 0x00, 0xe1, 0x7d, 0x30, 0xa7, 0xd8, 0x28, 0xab, 0x1b, 0x84,
-0x0b, 0x17, 0x54, 0x2d, 0xca, 0xf6, 0x20, 0x7a, 0xfd, 0x22, 0x1e, 0x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,
-0xb6, 0xf6, 0x50, 0x66, 0xb0, 0x40, 0x24, 0x6a, 0xaf, 0x98, 0x21, 0x45, 0x30, 0x01, 0x59, 0xd0, 0xc3, 0xfc, 0x7b, 0xae,
-0x30, 0x18, 0xeb, 0x90, 0xfb, 0x17, 0xd3, 0xce, 0xb5
-};
-
-/**
- * Encode the fields of the Data object and set digest to the sha-256 digest of the signed portion.
- * @param data The Data object with the fields to digest.
- * @param digest A pointer to a buffer of size SHA256_DIGEST_LENGTH to receive the data.
- */
-static void 
-dataSignedPortionSha256(const Data& data, WireFormat& wireFormat, unsigned char *digest)
+static bool 
+verifySignature(const Data& data /*, const Publickey& publickey */)
 {
-  unsigned int signedPortionBeginOffset, signedPortionEndOffset;
-  Blob encoding = wireFormat.encodeData(data, &signedPortionBeginOffset, &signedPortionEndOffset);
-  
-  ndn_digestSha256(encoding.buf() + signedPortionBeginOffset, signedPortionEndOffset - signedPortionBeginOffset, digest);
-}
+#if 0
+  using namespace CryptoPP;
 
-void 
-KeyChain::sign
-  (Data& data, const unsigned char *publicKeyDer, unsigned int publicKeyDerLength, 
-   const unsigned char *privateKeyDer, unsigned int privateKeyDerLength, WireFormat& wireFormat)
-{
-  data.setSignature(Sha256WithRsaSignature());
-  Sha256WithRsaSignature *signature = dynamic_cast<Sha256WithRsaSignature*>(data.getSignature());
-  
-  // Set the public key.
-  unsigned char publicKeyDigest[SHA256_DIGEST_LENGTH];
-  ndn_digestSha256(publicKeyDer, publicKeyDerLength, publicKeyDigest);
-  signature->getPublisherPublicKeyDigest().setPublisherPublicKeyDigest(publicKeyDigest, sizeof(publicKeyDigest));
-  signature->getKeyLocator().setType(ndn_KeyLocatorType_KEY);
-  signature->getKeyLocator().setKeyData(publicKeyDer, publicKeyDerLength);
+  Blob unsignedData(data.getSignedBlob()->signed_buf(), data.getSignedBlob()->signed_size());
+  bool result = false;
+    
+  // Temporarily hardwire.  It should be assigned by Signature.getAlgorithm().
+  DigestAlgorithm digestAlg = DIGEST_SHA256;
+  // Temporarily hardwire.  It should be assigned by Publickey.getKeyType().
+  KeyType keyType = KEY_TYPE_RSA; 
+  if (keyType == KEY_TYPE_RSA) {
+    RSA::PublicKey pubKey;
+    ByteQueue queue;
 
-  // Sign the fields.
-  unsigned char signedPortionDigest[SHA256_DIGEST_LENGTH];
-  dataSignedPortionSha256(data, wireFormat, signedPortionDigest);
-  // TODO: use RSA_size to get the proper size of the signature buffer.
-  unsigned char signatureBits[1000];
-  unsigned int signatureBitsLength;
-  // Use a temporary pointer since d2i updates it.
-  const unsigned char *derPointer = privateKeyDer;
-  RSA *privateKey = d2i_RSAPrivateKey(NULL, &derPointer, privateKeyDerLength);
-  if (!privateKey)
-    throw std::runtime_error("Error decoding private key in d2i_RSAPrivateKey");
-  int success = RSA_sign(NID_sha256, signedPortionDigest, sizeof(signedPortionDigest), signatureBits, &signatureBitsLength, privateKey);
-  // Free the private key before checking for success.
-  RSA_free(privateKey);
-  if (!success)
-    throw std::runtime_error("Error in RSA_sign");
-  
-  signature->setSignature(signatureBits, signatureBitsLength);
-}
+    queue.Put((const byte*)publickey.getKeyBlob ().buf (), publickey.getKeyBlob ().size ());
+    pubKey.Load(queue);
 
-void 
-KeyChain::defaultSign(Data& data, WireFormat& wireFormat)
-{
-  sign(data, DEFAULT_PUBLIC_KEY_DER, sizeof(DEFAULT_PUBLIC_KEY_DER), DEFAULT_PRIVATE_KEY_DER, sizeof(DEFAULT_PRIVATE_KEY_DER), wireFormat);
-}
+    if (DIGEST_SHA256 == digestAlg) {
+      Ptr<const signature::Sha256WithRsa> sigPtr = boost::dynamic_pointer_cast<const signature::Sha256WithRsa> (data.getSignature());
+      const Blob & sigBits = sigPtr->getSignatureBits();
 
-bool 
-KeyChain::selfVerifyData(const unsigned char *input, unsigned int inputLength, WireFormat& wireFormat)
-{
-  // Decode the data packet and digest the data fields.
-  Data data;
-  unsigned int signedPortionBeginOffset, signedPortionEndOffset;
-  wireFormat.decodeData(data, input, inputLength, &signedPortionBeginOffset, &signedPortionEndOffset);
-  Sha256WithRsaSignature *signature = dynamic_cast<Sha256WithRsaSignature*>(data.getSignature());
+      RSASS<PKCS1v15, SHA256>::Verifier verifier (pubKey);
+      result = verifier.VerifyMessage((const byte*) unsignedData.buf(), unsignedData.size(), (const byte*)sigBits.buf(), sigBits.size());            
+      _LOG_DEBUG("Signature verified? " << data.getName() << " " << boolalpha << result);      
+    }
+  }
+   
+ return result;
+#else
+  const Sha256WithRsaSignature *signature = dynamic_cast<const Sha256WithRsaSignature*>(data.getSignature());
   if (!signature)
-    throw std::runtime_error("signature is not Sha256WithRsaSignature");
+    throw std::runtime_error("signature is not Sha256WithRsaSignature.");
   
   if (signature->getDigestAlgorithm().size() != 0)
     // TODO: Allow a non-default digest algorithm.
-    throw std::runtime_error("Cannot verify a data packet with a non-default digest algorithm");
+    throw std::runtime_error("Cannot verify a data packet with a non-default digest algorithm.");
+  if (!data.getWireEncoding())
+    throw std::runtime_error("The Data wireEncoding is null.");
   unsigned char signedPortionDigest[SHA256_DIGEST_LENGTH];
-  ndn_digestSha256(input + signedPortionBeginOffset, signedPortionEndOffset - signedPortionBeginOffset, signedPortionDigest);
+  ndn_digestSha256(data.getWireEncoding().signedBuf(), data.getWireEncoding().signedSize(), signedPortionDigest);
   
-  // Find the public key.
-  const unsigned char *publicKeyDer;
-  unsigned int publicKeyDerLength;
-  if (signature->getKeyLocator().getType() == ndn_KeyLocatorType_KEY) {
-    publicKeyDer = signature->getKeyLocator().getKeyData().buf();
-    publicKeyDerLength = signature->getKeyLocator().getKeyData().size();
-  }
-  else
-    // Can't find a public key.
-    return false;
-
   // Verify the signedPortionDigest.
   // Use a temporary pointer since d2i updates it.
-  const unsigned char *derPointer = publicKeyDer;
-  RSA *publicKey = d2i_RSA_PUBKEY(NULL, &derPointer, publicKeyDerLength);
+  const unsigned char *derPointer = DEFAULT_PUBLIC_KEY_DER;
+  RSA *publicKey = d2i_RSA_PUBKEY(NULL, &derPointer, sizeof(DEFAULT_PUBLIC_KEY_DER));
   if (!publicKey)
     throw std::runtime_error("Error decoding public key in d2i_RSAPublicKey");
   int success = RSA_verify
@@ -157,6 +86,51 @@
   RSA_free(publicKey);
   
   return (success == 1);
+#endif
+}
+
+void 
+KeyChain::signData(Data& data, const Name& signerName, bool byKeyName, WireFormat& wireFormat)
+{
+  Name certificateName;
+    
+#if 0
+  if(signerName.getComponentCount() == 0)
+    certificateName = m_identityManager->getDefaultCertificateNameByIdentity(m_policyManager->inferSigningIdentity (data.getName ()));
+  else {
+    if (byKeyName)
+      certificateName = m_identityManager->getDefaultCertificateNameByIdentity(signerName);
+    else
+      certificateName = signerName;
+  }
+
+  if (certificateName.getComponentCount() == 0)
+    throw std::runtime_error("No qualified certificate name found!");
+
+  if (!m_policyManager->checkSigningPolicy (data.getName (), certificateName))
+    throw std::runtime_error("Signing Cert name does not comply with signing policy");
+#endif
+  
+  identityManager_->signByCertificate(data, certificateName, wireFormat);  
+}
+
+void
+KeyChain::verifyData(const ptr_lib::shared_ptr<Data>& data, const OnVerified& onVerified, const OnVerifyFailed& onVerifyFailed)
+{
+#if 0
+  _LOG_TRACE("Enter Verify");
+#endif
+
+#if 0
+  if (m_policyManager->requireVerify(*dataPtr))
+    stepVerify(dataPtr, true, m_maxStep, onVerified, onVerifyFailed);
+  else if(m_policyManager->skipVerify(*dataPtr))
+#else
+  if (verifySignature(*data))
+#endif
+    onVerified(data);
+  else
+    onVerifyFailed();
 }
 
 }
diff --git a/ndn-cpp/security/key-chain.hpp b/ndn-cpp/security/key-chain.hpp
index 7cfa64e..9a0468e 100644
--- a/ndn-cpp/security/key-chain.hpp
+++ b/ndn-cpp/security/key-chain.hpp
@@ -8,54 +8,61 @@
 #define NDN_KEY_CHAIN_HPP
 
 #include "../data.hpp"
+#include "../face.hpp"
+#include "identity/identity-manager.hpp"
 
 namespace ndn {
 
+/**
+ * An OnVerified function object is used to pass a callback to verifyData to report a successful verification.
+ */
+typedef func_lib::function<void(const ptr_lib::shared_ptr<Data>& data)> OnVerified;
+
+/**
+ * An OnVerifyFailed function object is used to pass a callback to verifyData to report a failed verification.
+ */
+typedef func_lib::function<void()> OnVerifyFailed;
+
 class KeyChain {
 public:
+  KeyChain(ptr_lib::shared_ptr<IdentityManager> identityManager)
+  : identityManager_(identityManager), face_(0), maxSteps_(100)
+  {  
+  }
+
   /**
-   * In data, set the meta info publisher public key digest and key locator key to the public key and set the 
-   * signature using the private key.
+   * Wire encode the Data object, sign it and set its signature.
    * Note: the caller must make sure the timestamp is correct, for example with 
    * data.getMetaInfo().setTimestampMilliseconds(time(NULL) * 1000.0).
-   * @param data The Data object to sign and set the key and signature.
-   * @param publicKeyDer A pointer to a buffer with the DER-encoded public key.
-   * @param publicKeyDerLength The number of bytes in publicKeyDer.
-   * @param privateKeyDer A pointer to a buffer with the DER-encoded private key.
-   * @param privateKeyDerLength The number of bytes in privateKeyDer.
-   * @param wireFormat The WireFormat for calling encodeData.
+   * @param data The Data object to be signed.  This updates its signature and key locator field and wireEncoding.
+   * @param signerName The signing identity or certificate name, depending on byKeyName. If omitted, infer the certificate name from data.getName().
+   * @param byKeyName If true, the signerName is the key name, otherwise it is the certificate name. If omitted, the default is true.
+   * @param wireFormat
    */
-  static void 
-  sign
-    (Data& data, const unsigned char *publicKeyDer, unsigned int publicKeyDerLength, 
-     const unsigned char *privateKeyDer, unsigned int privateKeyDerLength, WireFormat& wireFormat);
+  void 
+  signData(Data& data, const Name& signerName = Name(), bool byKeyName = true, WireFormat& wireFormat = *WireFormat::getDefaultWireFormat());
 
   /**
-   * Call sign with the default public and private keys.
+   * Check the signature on the Data object and call either onVerify or onVerifyFailed. 
+   * We use callback functions because verify may fetch information to check the signature.
    * @param data
-   * @param wireFormat The WireFormat for calling encodeData, or WireFormat::getDefaultWireFormat() if omitted.
+   * @param onVerified
+   * @param onVerifyFailed
    */
-  static void 
-  defaultSign(Data& data, WireFormat& wireFormat = *WireFormat::getDefaultWireFormat());
+  void
+  verifyData(const ptr_lib::shared_ptr<Data>& data, const OnVerified& onVerified, const OnVerifyFailed& onVerifyFailed);
 
   /**
-   * Use the WireFormat to decode the input as a Data packet and use the public key in the key locator to 
-   * verify the signature.
-   * This does just uses the public key without checking whether it is certified.
-   * @param input A pointer to the input buffer to decode.
-   * @param inputLength The number of bytes in input.
-   * @param wireFormat The WireFormat for calling decodeData.
-   * @return true if the public key in the Data object verifies the object, false if not or if the Data object
-   * doesn't have a public key.
+   * Set the Face which will be used to fetch required certificates.
+   * @param face A pointer to the Face object.
    */
-  static bool 
-  selfVerifyData(const unsigned char *input, unsigned int inputLength, WireFormat& wireFormat);
-  
-  static bool 
-  selfVerifyData(const unsigned char *input, unsigned int inputLength)
-  {
-    return selfVerifyData(input, inputLength, *WireFormat::getDefaultWireFormat());
-  }
+  void
+  setFace(Face* face) { face_ = face; }
+
+private:
+  ptr_lib::shared_ptr<IdentityManager> identityManager_;
+  Face* face_;
+  const int maxSteps_;
 };
 
 }