security: Continue porting security elements to the updated framework

Change-Id: I682156142a8714b2756ca429903a19d2b9064e13
diff --git a/include/ndn-cpp/security/certificate/identity-certificate.hpp b/include/ndn-cpp/security/certificate/identity-certificate.hpp
index 85c8e72..65b07af 100644
--- a/include/ndn-cpp/security/certificate/identity-certificate.hpp
+++ b/include/ndn-cpp/security/certificate/identity-certificate.hpp
@@ -41,6 +41,9 @@
   
   inline void
   wireDecode(const Block &wire);
+
+  inline void
+  setName(const Name &name);
   
   inline const Name &
   getPublicKeyName () const;
@@ -91,6 +94,13 @@
   setPublicKeyName();
 }
 
+inline void
+IdentityCertificate::setName(const Name &name)
+{
+  Certificate::setName(name);
+  setPublicKeyName();
+}
+
 inline const Name &
 IdentityCertificate::getPublicKeyName () const
 {
diff --git a/include/ndn-cpp/security/identity/identity-manager.hpp b/include/ndn-cpp/security/identity/identity-manager.hpp
index 702ad1f..5ed7771 100644
--- a/include/ndn-cpp/security/identity/identity-manager.hpp
+++ b/include/ndn-cpp/security/identity/identity-manager.hpp
@@ -78,6 +78,7 @@
   setDefaultKeyForIdentity(const Name& keyName, const Name& identityName = Name())
   {
     info().setDefaultKeyNameForIdentity(keyName, identityName);
+    defaultCertificate_.reset();
   }
 
   /**
@@ -218,7 +219,10 @@
   {
     return info().getDefaultCertificateNameForIdentity(getDefaultIdentity());
   }
-        
+
+  void
+  sign(Data &data);
+  
   /**
    * Sign the byte array data based on the certificate name.
    * @param buffer The byte array to be signed.
@@ -240,6 +244,9 @@
   void 
   signByCertificate(Data& data, const Name& certificateName);
 
+  void
+  signByCertificate(Data& data, const IdentityCertificate& certificate);
+
   /**
    * Generate a self-signed certificate for a public key.
    * @param keyName The name of the public key.
@@ -253,11 +260,11 @@
    */
   void
   selfSign (IdentityCertificate& cert);
-  
+
 public:
   static const ptr_lib::shared_ptr<IdentityStorage>   DefaultIdentityStorage;
   static const ptr_lib::shared_ptr<PrivateKeyStorage> DefaultPrivateKeyStorage;
-  
+
 private:
   /**
    * Generate a key pair for the specified identity.
@@ -276,6 +283,8 @@
 private:
   ptr_lib::shared_ptr<IdentityStorage>   identityStorage_;
   ptr_lib::shared_ptr<PrivateKeyStorage> privateKeyStorage_;
+
+  ptr_lib::shared_ptr<IdentityCertificate> defaultCertificate_;
 };
 
 inline IdentityStorage&
@@ -312,8 +321,6 @@
     throw Error("PrivateKeyStorage is not assigned to IdentityManager");
   return *privateKeyStorage_;
 }
-  
-  
 
 }
 
diff --git a/include/ndn-cpp/security/identity/memory-identity-storage.hpp b/include/ndn-cpp/security/identity/memory-identity-storage.hpp
index 5027a73..57f8050 100644
--- a/include/ndn-cpp/security/identity/memory-identity-storage.hpp
+++ b/include/ndn-cpp/security/identity/memory-identity-storage.hpp
@@ -21,6 +21,8 @@
  */
 class MemoryIdentityStorage : public IdentityStorage {
 public:
+  struct Error : public std::runtime_error { Error(const std::string &what) : std::runtime_error(what) {} };
+
   /**
    * The virtual Destructor.
    */
@@ -64,14 +66,14 @@
    * @param publicKeyDer A blob of the public key DER to be added.
    */
   virtual void 
-  addKey(const Name& keyName, KeyType keyType, const Blob& publicKeyDer);
+  addKey(const Name& keyName, KeyType keyType, const PublicKey& publicKeyDer);
 
   /**
    * Get the public key DER blob from the identity storage.
    * @param keyName The name of the requested public key.
    * @return The DER Blob.  If not found, return a Blob with a null pointer.
    */
-  virtual Blob
+  virtual ptr_lib::shared_ptr<PublicKey>
   getKey(const Name& keyName);
 
   /**
@@ -109,7 +111,7 @@
    * @param allowAny If false, only a valid certificate will be returned, otherwise validity is disregarded.
    * @return The requested certificate.  If not found, return a shared_ptr with a null pointer.
    */
-  virtual ptr_lib::shared_ptr<Data> 
+  virtual ptr_lib::shared_ptr<IdentityCertificate> 
   getCertificate(const Name &certificateName, bool allowAny = false);
 
 
@@ -182,24 +184,30 @@
 private:
   class KeyRecord {
   public:
-    KeyRecord(KeyType keyType, const Blob &keyDer)
-    : keyType_(keyType), keyDer_(keyDer)
+    KeyRecord(KeyType keyType, const PublicKey &key)
+    : keyType_(keyType), key_(key)
     {
     }
     
     const KeyType getKeyType() const { return keyType_; }
     
-    const Blob& getKeyDer() { return keyDer_; }
+    const PublicKey& getKey() { return key_; }
     
   private:
-    KeyType keyType_;
-    Blob keyDer_;
+    KeyType   keyType_;
+    PublicKey key_;
   };
   
   std::vector<std::string> identityStore_; /**< A list of name URI. */
   std::string defaultIdentity_;            /**< The default identity in identityStore_, or "" if not defined. */
-  std::map<std::string, ptr_lib::shared_ptr<KeyRecord> > keyStore_; /**< The map key is the keyName.toUri() */
-  std::map<std::string, Blob> certificateStore_;                    /**< The map key is the certificateName.toUri() */
+  Name defaultKeyName_;
+  Name defaultCert_;
+
+  typedef std::map< std::string, ptr_lib::shared_ptr<KeyRecord> > KeyStore; /**< The map key is the keyName.toUri() */
+  typedef std::map< std::string, ptr_lib::shared_ptr<IdentityCertificate> > CertificateStore; /**< The map key is the certificateName.toUri() */
+  
+  KeyStore keyStore_; 
+  CertificateStore certificateStore_;                    
 };
 
 }
diff --git a/include/ndn-cpp/security/identity/memory-private-key-storage.hpp b/include/ndn-cpp/security/identity/memory-private-key-storage.hpp
index 6184c94..f267583 100644
--- a/include/ndn-cpp/security/identity/memory-private-key-storage.hpp
+++ b/include/ndn-cpp/security/identity/memory-private-key-storage.hpp
@@ -21,6 +21,8 @@
  */
 class MemoryPrivateKeyStorage : public PrivateKeyStorage {
 public:
+  struct Error : public std::runtime_error { Error(const std::string &what) : std::runtime_error(what) {} };
+
   /**
    * The virtual destructor
    */    
@@ -35,9 +37,9 @@
    * @param privateKeyDer The private key DER byte array.
    * @param privateKeyDerLength The length of privateKeyDer.
    */
-  void setKeyPairForKeyName
-    (const Name& keyName, uint8_t *publicKeyDer, size_t publicKeyDerLength, uint8_t *privateKeyDer, 
-     size_t privateKeyDerLength);
+  void setKeyPairForKeyName(const Name& keyName,
+                            uint8_t *publicKeyDer, size_t publicKeyDerLength,
+                            uint8_t *privateKeyDer, size_t privateKeyDerLength);
   
   /**
    * Generate a pair of asymmetric keys.
@@ -64,9 +66,12 @@
    * @param digestAlgorithm the digest algorithm.
    * @return The signature, or a null pointer if signing fails.
    */  
-  virtual Blob 
-  sign(const uint8_t *data, size_t dataLength, const Name& keyName, DigestAlgorithm digestAlgorithm);
-    
+  virtual Block 
+  sign(const uint8_t *data, size_t dataLength, const Signature &signature, const Name& keyName, DigestAlgorithm digestAlgorithm);
+
+  virtual Block 
+  sign(const Data &data, const Signature &signature, const Name& keyName, DigestAlgorithm digestAlgorithm);
+  
   /**
    * Decrypt data.
    * @param keyName The name of the decrypting key.
@@ -75,7 +80,7 @@
    * @param isSymmetric If true symmetric encryption is used, otherwise asymmetric decryption is used.
    * @return The decrypted data.
    */
-  virtual Blob 
+  virtual ConstBufferPtr 
   decrypt(const Name& keyName, const uint8_t* data, size_t dataLength, bool isSymmetric);
 
   /**
@@ -86,7 +91,7 @@
    * @param isSymmetric If true symmetric encryption is used, otherwise asymmetric decryption is used.
    * @return The encrypted data.
    */
-  virtual Blob
+  virtual ConstBufferPtr
   encrypt(const Name& keyName, const uint8_t* data, size_t dataLength, bool isSymmetric);
 
   /**
@@ -108,23 +113,13 @@
   doesKeyExist(const Name& keyName, KeyClass keyClass);  
   
 private:
-  /**
-   * RsaPrivateKey is a simple class to hold an RSA private key.
-   */
-  class RsaPrivateKey {
-  public:
-    RsaPrivateKey(uint8_t *keyDer, size_t keyDerLength);
-    
-    ~RsaPrivateKey();
-    
-    struct rsa_st* getPrivateKey() { return privateKey_; }
-    
-  private:
-    struct rsa_st* privateKey_;
-  };
-    
-  std::map<std::string, ptr_lib::shared_ptr<PublicKey> > publicKeyStore_;      /**< The map key is the keyName.toUri() */
-  std::map<std::string, ptr_lib::shared_ptr<RsaPrivateKey> > privateKeyStore_; /**< The map key is the keyName.toUri() */
+  class RsaPrivateKey;
+
+  typedef std::map<std::string, ptr_lib::shared_ptr<PublicKey> >     PublicKeyStore;
+  typedef std::map<std::string, ptr_lib::shared_ptr<RsaPrivateKey> > PrivateKeyStore;
+  
+  PublicKeyStore  publicKeyStore_;  /**< The map key is the keyName.toUri() */
+  PrivateKeyStore privateKeyStore_; /**< The map key is the keyName.toUri() */
 };
 
 }
diff --git a/include/ndn-cpp/security/identity/private-key-storage.hpp b/include/ndn-cpp/security/identity/private-key-storage.hpp
index 29461bb..9777d64 100644
--- a/include/ndn-cpp/security/identity/private-key-storage.hpp
+++ b/include/ndn-cpp/security/identity/private-key-storage.hpp
@@ -20,6 +20,8 @@
 
 class PrivateKeyStorage {
 public:
+  struct Error : public std::runtime_error { Error(const std::string &what) : std::runtime_error(what) {} };
+
   /**
    * The virtual destructor.
    */    
@@ -51,12 +53,12 @@
    * @param digestAlgorithm the digest algorithm.
    * @return The signature, or a null pointer if signing fails.
    */  
-  virtual ConstBufferPtr
+  virtual Block
   sign(const uint8_t *data, size_t dataLength,
        const Signature &signature,
        const Name& keyName, DigestAlgorithm digestAlgorithm = DIGEST_ALGORITHM_SHA256) = 0;
 
-  virtual ConstBufferPtr
+  virtual Block
   sign(const Data &data,
        const Signature &signature,
        const Name& keyName, DigestAlgorithm digestAlgorithm = DIGEST_ALGORITHM_SHA256) = 0;
diff --git a/include/ndn-cpp/security/key-chain.hpp b/include/ndn-cpp/security/key-chain.hpp
index da470f7..c39736e 100644
--- a/include/ndn-cpp/security/key-chain.hpp
+++ b/include/ndn-cpp/security/key-chain.hpp
@@ -85,6 +85,9 @@
    *              Sign/Verify              *
    *****************************************/
 
+  inline void 
+  sign(Data& data);
+  
   /**
    * Wire encode the Data object, sign it and set its signature.
    * Note: the caller must make sure the timestamp is correct, for example with 
@@ -92,7 +95,7 @@
    * @param data The Data object to be signed.  This updates its signature and key locator field and wireEncoding.
    * @param certificateName The certificate name of the key to use for signing.  If omitted, infer the signing identity from the data packet name.
    */
-  void 
+  inline void 
   sign(Data& data, const Name& certificateName);
   
   /**
@@ -102,7 +105,7 @@
    * @param certificateName The certificate name used to get the signing key and which will be put into KeyLocator.
    * @return The Signature.
    */
-  Signature
+  inline Signature
   sign(const uint8_t* buffer, size_t bufferLength, const Name& certificateName);
 
   /**
@@ -167,6 +170,24 @@
   const int maxSteps_;
 };
 
+void 
+KeyChain::sign(Data& data)
+{
+  identities().sign(data);
+}
+
+void 
+KeyChain::sign(Data& data, const Name& certificateName)
+{
+  identities().signByCertificate(data, certificateName);
+}
+
+Signature
+KeyChain::sign(const uint8_t* buffer, size_t bufferLength, const Name& certificateName)
+{
+  return identities().signByCertificate(buffer, bufferLength, certificateName);
+}
+
 }
 
 #endif
diff --git a/src/security/identity/identity-manager.cpp b/src/security/identity/identity-manager.cpp
index ce90cc5..1befdcd 100644
--- a/src/security/identity/identity-manager.cpp
+++ b/src/security/identity/identity-manager.cpp
@@ -90,6 +90,8 @@
 Name
 IdentityManager::generateRSAKeyPairAsDefault(const Name& identityName, bool isKsk, int keySize)
 {
+  defaultCertificate_.reset();
+  
   Name keyName = generateKeyPair(identityName, isKsk, KEY_TYPE_RSA, keySize);
 
   info().setDefaultKeyNameForIdentity(keyName, identityName);
@@ -104,10 +106,14 @@
                                            const MillisecondsSince1970& notAfter)
 {
   Name keyName = getKeyNameFromCertificatePrefix(certificatePrefix);
+
+  ptr_lib::shared_ptr<PublicKey> pubKey = info().getKey(keyName);
+  if (!pubKey)
+    throw Error("Requested public key [" + keyName.toUri() + "] doesn't exist");
   
   ptr_lib::shared_ptr<IdentityCertificate> certificate =
     createIdentityCertificate(certificatePrefix,
-                              *info().getKey(keyName),
+                              *pubKey,
                               signerCertificateName,
                               notBefore, notAfter);
 
@@ -148,11 +154,15 @@
   
   Name certificateName = keyName.getSubName(0, keyName.size() - 1);
   certificateName.append("KEY").append(keyName.get(keyName.size() - 1)).append("ID-CERT").appendVersion();
+
+  ptr_lib::shared_ptr<PublicKey> pubKey = info().getKey(keyName);
+  if (!pubKey)
+    throw Error("Requested public key [" + keyName.toUri() + "] doesn't exist");
   
   certificate->setName(certificateName);
   certificate->setNotBefore(ndn_getNowMilliseconds());
   certificate->setNotAfter(ndn_getNowMilliseconds() + 630720000 /* 20 years*/);
-  certificate->setPublicKeyInfo(*info().getKey(keyName));
+  certificate->setPublicKeyInfo(*pubKey);
   certificate->addSubjectDescription(CertificateSubjectDescription("2.5.4.41", keyName.toUri()));
   certificate->encode();
 
@@ -183,6 +193,8 @@
 void
 IdentityManager::setDefaultCertificateForKey(const IdentityCertificate& certificate)
 {
+  defaultCertificate_.reset();
+  
   Name keyName = certificate.getPublicKeyName();
   
   if(!info().doesKeyExist(keyName))
@@ -190,11 +202,30 @@
 
   info().setDefaultCertificateNameForKey(keyName, certificate.getName());
 }
-  
+
+void
+IdentityManager::sign(Data &data)
+{
+  if (!defaultCertificate_)
+    {
+      defaultCertificate_ = info().getCertificate(
+                                                  info().getDefaultCertificateNameForIdentity(
+                                                                                              info().getDefaultIdentity()));
+
+      if(!defaultCertificate_)
+        throw Error("Default IdentityCertificate cannot be determined");
+    }
+
+  signByCertificate(data, *defaultCertificate_);
+}
+
 Signature
 IdentityManager::signByCertificate(const uint8_t* buffer, size_t bufferLength, const Name& certificateName)
 {
   ptr_lib::shared_ptr<IdentityCertificate> cert = info().getCertificate(certificateName);
+  if (!cert)
+    throw Error("Requested certificate [" + certificateName.toUri() + "] doesn't exist");
+
   SignatureSha256WithRsa signature;
   signature.setKeyLocator(certificateName.getPrefix(-1)); // implicit conversion should take care
 
@@ -207,6 +238,9 @@
 IdentityManager::signByCertificate(Data &data, const Name &certificateName)
 {
   ptr_lib::shared_ptr<IdentityCertificate> cert = info().getCertificate(certificateName);
+  if (!cert)
+    throw Error("Requested certificate [" + certificateName.toUri() + "] doesn't exist");
+
   SignatureSha256WithRsa signature;
   signature.setKeyLocator(certificateName.getPrefix(-1)); // implicit conversion should take care
 
@@ -216,6 +250,17 @@
 }
 
 void
+IdentityManager::signByCertificate(Data& data, const IdentityCertificate& certificate)
+{
+  SignatureSha256WithRsa signature;
+  signature.setKeyLocator(certificate.getName().getPrefix(-1));
+
+  // For temporary usage, we support RSA + SHA256 only, but will support more.
+  signature.setValue(tpm().sign(data, signature, certificate.getPublicKeyName(), DIGEST_ALGORITHM_SHA256));
+  data.setSignature(signature);
+}
+
+void
 IdentityManager::selfSign (IdentityCertificate& cert)
 {
   SignatureSha256WithRsa signature;
diff --git a/src/security/identity/memory-identity-storage.cpp b/src/security/identity/memory-identity-storage.cpp
index fae1f14..117ca35 100644
--- a/src/security/identity/memory-identity-storage.cpp
+++ b/src/security/identity/memory-identity-storage.cpp
@@ -138,17 +138,13 @@
 Name 
 MemoryIdentityStorage::getDefaultKeyNameForIdentity(const Name& identityName)
 {
-#if 1
-  throw runtime_error("MemoryIdentityStorage::getDefaultKeyNameForIdentity not implemented");
-#endif
+  return defaultKeyName_;
 }
 
 Name 
 MemoryIdentityStorage::getDefaultCertificateNameForKey(const Name& keyName)
 {
-#if 1
-  throw runtime_error("MemoryIdentityStorage::getDefaultCertificateNameForKey not implemented");
-#endif
+  return defaultCert_;
 }
 
 void 
@@ -165,17 +161,13 @@
 void 
 MemoryIdentityStorage::setDefaultKeyNameForIdentity(const Name& keyName, const Name& identityNameCheck)
 {
-#if 1
-  throw runtime_error("MemoryIdentityStorage::setDefaultKeyNameForIdentity not implemented");
-#endif
+  defaultKeyName_ = identityNameCheck;
 }
 
 void 
 MemoryIdentityStorage::setDefaultCertificateNameForKey(const Name& keyName, const Name& certificateName)  
 {
-#if 1
-  throw runtime_error("MemoryIdentityStorage::setDefaultCertificateNameForKey not implemented");
-#endif
+  defaultCert_ = certificateName;
 }
 
 
diff --git a/src/security/key-chain.cpp b/src/security/key-chain.cpp
index 017a462..ba9060d 100644
--- a/src/security/key-chain.cpp
+++ b/src/security/key-chain.cpp
@@ -62,17 +62,6 @@
 // #endif
 }
 
-void 
-KeyChain::sign(Data& data, const Name& certificateName)
-{
-  identities().signByCertificate(data, certificateName);
-}
-
-Signature
-KeyChain::sign(const uint8_t* buffer, size_t bufferLength, const Name& certificateName)
-{
-  return identities().signByCertificate(buffer, bufferLength, certificateName);
-}
 
 void 
 KeyChain::signByIdentity(Data& data, const Name& identityName)
@@ -95,7 +84,7 @@
   if (!policyManager_->checkSigningPolicy(data.getName(), signingCertificateName))
     throw Error("Signing Cert name does not comply with signing policy");
 
-  identities().signByCertificate(data, signingCertificateName);  
+  identities().signByCertificate(data, signingCertificateName);
 }
 
 Signature