security: Pair-up Tpm and Pib in KeyChain

In this commit, we also change the HOME setting for test cases.

Change-Id: I7fa15461555b3519d9d2005c6956c167ed07d66f
Refs: #2242
Refs: #2260
diff --git a/src/security/key-chain.cpp b/src/security/key-chain.cpp
index f22c5a9..9360671 100644
--- a/src/security/key-chain.cpp
+++ b/src/security/key-chain.cpp
@@ -41,96 +41,177 @@
 const RsaKeyParams KeyChain::DEFAULT_KEY_PARAMS;
 
 KeyChain::KeyChain()
-  : m_pib(0)
-  , m_tpm(0)
+  : m_pib(nullptr)
+  , m_tpm(nullptr)
   , m_lastTimestamp(time::toUnixTimestamp(time::system_clock::now()))
 {
+  initialize("", "", false);
+}
 
-  ConfigFile config;
-  const ConfigFile::Parsed& parsed = config.getParsedConfiguration();
-
-  std::string pibName;
-  try
-    {
-      pibName = parsed.get<std::string>("pib");
-    }
-  catch (boost::property_tree::ptree_bad_path& error)
-    {
-      // pib is not specified, take the default
-    }
-  catch (boost::property_tree::ptree_bad_data& error)
-    {
-      throw ConfigFile::Error(error.what());
-    }
-
-  std::string tpmName;
-  try
-    {
-      tpmName = parsed.get<std::string>("tpm");
-    }
-  catch (boost::property_tree::ptree_bad_path& error)
-    {
-      // tpm is not specified, take the default
-    }
-  catch (boost::property_tree::ptree_bad_data& error)
-    {
-      throw ConfigFile::Error(error.what());
-    }
-
-
-  if (pibName.empty() || pibName == "sqlite3")
-    m_pib = new SecPublicInfoSqlite3;
-  else
-    throw Error("PIB type '" + pibName + "' is not supported");
-
-  if (tpmName.empty())
-#if defined(NDN_CXX_HAVE_OSX_SECURITY) and defined(NDN_CXX_WITH_OSX_KEYCHAIN)
-    m_tpm = new SecTpmOsx();
-#else
-    m_tpm = new SecTpmFile();
-#endif // defined(NDN_CXX_HAVE_OSX_SECURITY) and defined(NDN_CXX_WITH_OSX_KEYCHAIN)
-  else if (tpmName == "osx-keychain")
-#if defined(NDN_CXX_HAVE_OSX_SECURITY)
-    m_tpm = new SecTpmOsx();
-#else
-    throw Error("TPM type '" + tpmName + "' is not supported on this platform");
-#endif // NDN_CXX_HAVE_OSX_SECURITY
-  else if (tpmName == "file")
-    m_tpm = new SecTpmFile();
-  else
-    throw Error("TPM type '" + tpmName + "' is not supported");
+template<class T>
+inline
+KeyChain::KeyChain(T traits)
+  : m_pib(new typename T::Pib)
+  , m_tpm(nullptr)
+  , m_lastTimestamp(time::toUnixTimestamp(time::system_clock::now()))
+{
+  initialize(T::Pib::SCHEME, T::Tpm::SCHEME, false);
 }
 
 KeyChain::KeyChain(const std::string& pibName,
-                   const std::string& tpmName)
-  : m_pib(0)
-  , m_tpm(0)
+                   const std::string& tpmName,
+                   bool allowReset)
+  : m_pib(nullptr)
+  , m_tpm(nullptr)
   , m_lastTimestamp(time::toUnixTimestamp(time::system_clock::now()))
 {
-  if (pibName == "sqlite3")
-    m_pib = new SecPublicInfoSqlite3;
-  else
-    throw Error("PIB type '" + pibName + "' is not supported");
+  std::string pibLocator;
+  std::string tpmLocator;
 
   if (tpmName == "file")
-    m_tpm = new SecTpmFile;
+    tpmLocator = SecTpmFile::SCHEME;
 #if defined(NDN_CXX_HAVE_OSX_SECURITY)
   else if (tpmName == "osx-keychain")
-    m_tpm = new SecTpmOsx();
+    tpmLocator = SecTpmOsx::SCHEME;
 #endif //NDN_CXX_HAVE_OSX_SECURITY
   else
-    throw Error("TPM type '" + tpmName + "' is not supported");
+    tpmLocator = tpmName;
+
+  if (pibName == "sqlite3")
+    pibLocator = SecPublicInfoSqlite3::SCHEME;
+  else
+    pibLocator = pibName;
+
+  initialize(pibLocator, tpmLocator, allowReset);
 }
 
 KeyChain::~KeyChain()
 {
-  if (m_pib != 0)
+  if (m_pib != nullptr)
     delete m_pib;
 
-  if (m_tpm != 0)
+  if (m_tpm != nullptr)
     delete m_tpm;
 }
 
+void
+KeyChain::initialize(const std::string& pib,
+                     const std::string& tpm,
+                     bool allowReset)
+{
+  ConfigFile config;
+  const ConfigFile::Parsed& parsed = config.getParsedConfiguration();
+
+  std::string defaultTpmLocator;
+  try {
+    defaultTpmLocator = parsed.get<std::string>("tpm");
+  }
+  catch (boost::property_tree::ptree_bad_path&) {
+    // tpm is not specified, take the default
+  }
+  catch (boost::property_tree::ptree_bad_data& error) {
+    throw ConfigFile::Error(error.what());
+  }
+
+  if (defaultTpmLocator.empty())
+#if defined(NDN_CXX_HAVE_OSX_SECURITY) and defined(NDN_CXX_WITH_OSX_KEYCHAIN)
+    defaultTpmLocator = SecTpmOsx::SCHEME;
+#else
+    defaultTpmLocator = SecTpmFile::SCHEME;
+#endif // defined(NDN_CXX_HAVE_OSX_SECURITY) and defined(NDN_CXX_WITH_OSX_KEYCHAIN)
+  else if (defaultTpmLocator == "osx-keychain")
+#if defined(NDN_CXX_HAVE_OSX_SECURITY)
+    defaultTpmLocator = SecTpmOsx::SCHEME;
+#else
+    throw Error("TPM Locator '" + defaultTpmLocator + "' is not supported on this platform");
+#endif // NDN_CXX_HAVE_OSX_SECURITY
+  else if (defaultTpmLocator == "file")
+    defaultTpmLocator = SecTpmFile::SCHEME;
+
+  std::string defaultPibLocator;
+  try {
+    defaultPibLocator = parsed.get<std::string>("pib");
+  }
+  catch (boost::property_tree::ptree_bad_path&) {
+    // pib is not specified, take the default
+  }
+  catch (boost::property_tree::ptree_bad_data& error) {
+    throw ConfigFile::Error(error.what());
+  }
+
+  if (defaultPibLocator.empty() || defaultPibLocator == "sqlite3")
+    defaultPibLocator = SecPublicInfoSqlite3::SCHEME;
+
+  std::string pibLocator = pib;
+  std::string tpmLocator = tpm;
+
+  if (pibLocator == "")
+    pibLocator = defaultPibLocator;
+
+  if (defaultPibLocator == pibLocator)
+    tpmLocator = defaultTpmLocator;
+
+  initializePib(pibLocator);
+
+  std::string currentTpmLocator;
+  try {
+    currentTpmLocator = m_pib->getTpmLocator();
+
+    if (currentTpmLocator != tpmLocator) {
+      if (!allowReset) {
+        // Tpm mismatch, but we do not want to reset PIB
+        throw MismatchError("TPM locator supplied and TPM locator in PIB mismatch: " +
+                            currentTpmLocator + " != " + tpmLocator);
+      }
+      else {
+        // reset is explicitly required
+        tpmLocator = currentTpmLocator;
+      }
+    }
+  }
+  catch (SecPublicInfo::Error&) {
+    // TPM locator is not set in PIB yet.
+  }
+
+  initializeTpm(tpmLocator); // note that key mismatch may still happen
+                             // if the TPM locator is initially set to a wrong one
+                             // or if the PIB was shared by more than one TPMs before.
+                             // This is due to the old PIB does not have TPM info,
+                             // new pib should not have this problem.
+
+  m_pib->setTpmLocator(tpmLocator);
+}
+
+void
+KeyChain::initializeTpm(const std::string& locator)
+{
+  size_t pos = locator.find(':');
+  std::string type = locator.substr(0, pos + 1);
+  std::string location = locator.substr(pos + 1);
+
+  if (type == SecTpmFile::SCHEME)
+    m_tpm = new SecTpmFile(location);
+#if defined(NDN_CXX_HAVE_OSX_SECURITY) and defined(NDN_CXX_WITH_OSX_KEYCHAIN)
+  else if (type == SecTpmOsx::SCHEME)
+    m_tpm = new SecTpmOsx(location);
+#endif
+  else
+    throw Error("Tpm locator error: Unsupported Tpm type: " + type);
+}
+
+void
+KeyChain::initializePib(const std::string& locator)
+{
+  size_t pos = locator.find(':');
+  std::string type = locator.substr(0, pos + 1);
+  std::string location = locator.substr(pos + 1);
+
+  if (type == SecPublicInfoSqlite3::SCHEME)
+    m_pib = new SecPublicInfoSqlite3(location);
+  else
+    throw Error("Pib locator error: Unsupported Pib type: " + type);
+}
+
 Name
 KeyChain::createIdentity(const Name& identityName, const KeyParams& params)
 {
@@ -171,6 +252,20 @@
 }
 
 Name
+KeyChain::generateRsaKeyPair(const Name& identityName, bool isKsk, uint32_t keySize)
+{
+  RsaKeyParams params(keySize);
+  return generateKeyPair(identityName, isKsk, params);
+}
+
+Name
+KeyChain::generateEcdsaKeyPair(const Name& identityName, bool isKsk, uint32_t keySize)
+{
+  EcdsaKeyParams params(keySize);
+  return generateKeyPair(identityName, isKsk, params);
+}
+
+Name
 KeyChain::generateRsaKeyPairAsDefault(const Name& identityName, bool isKsk, uint32_t keySize)
 {
   RsaKeyParams params(keySize);
@@ -414,7 +509,7 @@
 
   shared_ptr<PublicKey> pubKey = m_tpm->getPublicKeyFromTpm(keyName.toUri());
   // HACK! We should set key type according to the pkcs8 info.
-  m_pib->addPublicKey(keyName, KEY_TYPE_RSA, *pubKey);
+  m_pib->addKey(keyName, *pubKey);
   m_pib->setDefaultKeyNameForIdentity(keyName);
 
   // Add cert
diff --git a/src/security/key-chain.hpp b/src/security/key-chain.hpp
index 5d348c4..28de735 100644
--- a/src/security/key-chain.hpp
+++ b/src/security/key-chain.hpp
@@ -60,10 +60,19 @@
     }
   };
 
-  static const Name DEFAULT_PREFIX;
-
-  // RsaKeyParams is set to be default for backward compatibility.
-  static const RsaKeyParams DEFAULT_KEY_PARAMS;
+  /**
+   * This error is thrown when the TPM locator retrieved from PIB is
+   * different from what is supplied to the KeyChain constructor.
+   */
+  class MismatchError : public Error
+  {
+  public:
+    explicit
+    MismatchError(const std::string& what)
+      : Error(what)
+    {
+    }
+  };
 
   KeyChain();
 
@@ -71,8 +80,19 @@
   explicit
   KeyChain(KeyChainTraits traits);
 
-  KeyChain(const std::string& pibName,
-           const std::string& tpmName);
+  /**
+   * @brief KeyChain constructor
+   *
+   * @sa  http://redmine.named-data.net/issues/2260
+   *
+   * @param pibLocator
+   * @param tpmLocator
+   * @param allowReset if true, the PIB will be reset when the supplied tpmLocator
+   *        mismatches the one in PIB
+   */
+  KeyChain(const std::string& pibLocator,
+           const std::string& tpmLocator,
+           bool allowReset = false);
 
   virtual
   ~KeyChain();
@@ -96,10 +116,10 @@
    * @param keySize The size of the key.
    * @return The generated key name.
    */
-  inline Name
+  Name
   generateRsaKeyPair(const Name& identityName, bool isKsk = false, uint32_t keySize = 2048);
 
-  inline Name
+  Name
   generateEcdsaKeyPair(const Name& identityName, bool isKsk = false, uint32_t keySize = 256);
   /**
    * @brief Generate a pair of RSA keys for the specified identity and set it as default key for
@@ -356,7 +376,7 @@
   void
   addPublicKey(const Name& keyName, KeyType keyType, const PublicKey& publicKeyDer)
   {
-    return m_pib->addPublicKey(keyName, keyType, publicKeyDer);
+    return m_pib->addKey(keyName, publicKeyDer);
   }
 
   void
@@ -643,6 +663,17 @@
   }
 
 private:
+  void
+  initialize(const std::string& pibLocator,
+             const std::string& tpmLocator,
+             bool needReset);
+
+  void
+  initializeTpm(const std::string& locator);
+
+  void
+  initializePib(const std::string& locator);
+
   /**
    * @brief Determine signature type
    *
@@ -707,6 +738,10 @@
   signPacketWrapper(Interest& interest, const Signature& signature,
                     const Name& keyName, DigestAlgorithm digestAlgorithm);
 
+public:
+  static const Name DEFAULT_PREFIX;
+  // RsaKeyParams is set to be default for backward compatibility.
+  static const RsaKeyParams DEFAULT_KEY_PARAMS;
 
 private:
   SecPublicInfo* m_pib;
@@ -714,29 +749,6 @@
   time::milliseconds m_lastTimestamp;
 };
 
-template<class T>
-inline
-KeyChain::KeyChain(T)
-  : m_pib(new typename T::Pib)
-  , m_tpm(new typename T::Tpm)
-  , m_lastTimestamp(time::toUnixTimestamp(time::system_clock::now()))
-{
-}
-
-inline Name
-KeyChain::generateRsaKeyPair(const Name& identityName, bool isKsk, uint32_t keySize)
-{
-  RsaKeyParams params(keySize);
-  return generateKeyPair(identityName, isKsk, params);
-}
-
-inline Name
-KeyChain::generateEcdsaKeyPair(const Name& identityName, bool isKsk, uint32_t keySize)
-{
-  EcdsaKeyParams params(keySize);
-  return generateKeyPair(identityName, isKsk, params);
-}
-
 template<typename T>
 void
 KeyChain::sign(T& packet)
diff --git a/src/security/sec-public-info-sqlite3.cpp b/src/security/sec-public-info-sqlite3.cpp
index 946eb56..58d6267 100644
--- a/src/security/sec-public-info-sqlite3.cpp
+++ b/src/security/sec-public-info-sqlite3.cpp
@@ -40,71 +40,84 @@
 using std::string;
 using std::vector;
 
-static const string INIT_ID_TABLE = "\
-CREATE TABLE IF NOT EXISTS                                           \n \
-  Identity(                                                          \n \
-      identity_name     BLOB NOT NULL,                               \n \
-      default_identity  INTEGER DEFAULT 0,                           \n \
-                                                                     \
-      PRIMARY KEY (identity_name)                                    \n \
-  );                                                                 \n \
-                                                                     \
-CREATE INDEX identity_index ON Identity(identity_name);              \n \
-";
+const std::string SecPublicInfoSqlite3::SCHEME("pib-sqlite3:");
 
-static const string INIT_KEY_TABLE = "\
-CREATE TABLE IF NOT EXISTS                                           \n \
-  Key(                                                               \n \
-      identity_name     BLOB NOT NULL,                               \n \
-      key_identifier    BLOB NOT NULL,                               \n \
-      key_type          INTEGER,                                     \n \
-      public_key        BLOB,                                        \n \
-      default_key       INTEGER DEFAULT 0,                           \n \
-      active            INTEGER DEFAULT 0,                           \n \
-                                                                     \
-      PRIMARY KEY (identity_name, key_identifier)                    \n \
-  );                                                                 \n \
-                                                                     \
-CREATE INDEX key_index ON Key(identity_name);                        \n \
-";
+static const string INIT_TPM_INFO_TABLE =
+  "CREATE TABLE IF NOT EXISTS                "
+  "  TpmInfo(                                "
+  "      tpm_locator           BLOB NOT NULL,"
+  "      PRIMARY KEY (tpm_locator)           "
+  "  );                                      ";
 
-static const string INIT_CERT_TABLE = "\
-CREATE TABLE IF NOT EXISTS                                           \n \
-  Certificate(                                                       \n \
-      cert_name         BLOB NOT NULL,                               \n \
-      cert_issuer       BLOB NOT NULL,                               \n \
-      identity_name     BLOB NOT NULL,                               \n \
-      key_identifier    BLOB NOT NULL,                               \n \
-      not_before        TIMESTAMP,                                   \n \
-      not_after         TIMESTAMP,                                   \n \
-      certificate_data  BLOB NOT NULL,                               \n \
-      valid_flag        INTEGER DEFAULT 1,                           \n \
-      default_cert      INTEGER DEFAULT 0,                           \n \
-                                                                     \
-      PRIMARY KEY (cert_name)                                        \n \
-  );                                                                 \n \
-                                                                     \
-CREATE INDEX cert_index ON Certificate(cert_name);           \n \
-CREATE INDEX subject ON Certificate(identity_name);          \n \
-";
+static const string INIT_ID_TABLE =
+  "CREATE TABLE IF NOT EXISTS                             "
+  "  Identity(                                            "
+  "      identity_name     BLOB NOT NULL,                 "
+  "      default_identity  INTEGER DEFAULT 0,             "
+  "      PRIMARY KEY (identity_name)                      "
+  "  );                                                   "
+  "CREATE INDEX identity_index ON Identity(identity_name);";
+
+static const string INIT_KEY_TABLE =
+  "CREATE TABLE IF NOT EXISTS                       "
+  "  Key(                                           "
+  "      identity_name     BLOB NOT NULL,           "
+  "      key_identifier    BLOB NOT NULL,           "
+  "      key_type          INTEGER,                 "
+  "      public_key        BLOB,                    "
+  "      default_key       INTEGER DEFAULT 0,       "
+  "      active            INTEGER DEFAULT 0,       "
+  "      PRIMARY KEY (identity_name, key_identifier)"
+  "  );                                             "
+  "CREATE INDEX key_index ON Key(identity_name);    ";
+
+
+static const string INIT_CERT_TABLE =
+  "CREATE TABLE IF NOT EXISTS                         "
+  "  Certificate(                                     "
+  "      cert_name         BLOB NOT NULL,             "
+  "      cert_issuer       BLOB NOT NULL,             "
+  "      identity_name     BLOB NOT NULL,             "
+  "      key_identifier    BLOB NOT NULL,             "
+  "      not_before        TIMESTAMP,                 "
+  "      not_after         TIMESTAMP,                 "
+  "      certificate_data  BLOB NOT NULL,             "
+  "      valid_flag        INTEGER DEFAULT 1,         "
+  "      default_cert      INTEGER DEFAULT 0,         "
+  "      PRIMARY KEY (cert_name)                      "
+  "  );                                               "
+  "CREATE INDEX cert_index ON Certificate(cert_name); "
+  "CREATE INDEX subject ON Certificate(identity_name);";
 
 /**
  * A utility function to call the normal sqlite3_bind_text where the value and length are
  * value.c_str() and value.size().
  */
 static int
-sqlite3_bind_text(sqlite3_stmt* statement,
-                  int index,
-                  const string& value,
-                  void(*destructor)(void*))
+sqlite3_bind_string(sqlite3_stmt* statement,
+                    int index,
+                    const string& value,
+                    void(*destructor)(void*))
 {
   return sqlite3_bind_text(statement, index, value.c_str(), value.size(), destructor);
 }
 
-SecPublicInfoSqlite3::SecPublicInfoSqlite3()
-  : m_database(nullptr)
+static string
+sqlite3_column_string(sqlite3_stmt* statement, int column)
 {
-  boost::filesystem::path identityDir = boost::filesystem::path(getenv("HOME")) / ".ndn";
+  return string(reinterpret_cast<const char*>(sqlite3_column_text(statement, column)),
+                sqlite3_column_bytes(statement, column));
+}
+
+SecPublicInfoSqlite3::SecPublicInfoSqlite3(const std::string& dir)
+  : SecPublicInfo(dir)
+  , m_database(nullptr)
+{
+  boost::filesystem::path identityDir;
+  if (dir == "")
+    identityDir = boost::filesystem::path(getenv("HOME")) / ".ndn";
+  else
+    identityDir = boost::filesystem::path(dir) / ".ndn";
   boost::filesystem::create_directories(identityDir);
 
   /// @todo Add define for windows/unix in wscript. The following may completely fail on windows
@@ -119,71 +132,13 @@
   if (res != SQLITE_OK)
     throw Error("identity DB cannot be opened/created");
 
+
   BOOST_ASSERT(m_database != nullptr);
 
-  //Check if Key table exists;
-  sqlite3_stmt* statement;
-  sqlite3_prepare_v2(m_database,
-                     "SELECT name FROM sqlite_master WHERE type='table' And name='Identity'",
-                     -1, &statement, 0);
-  res = sqlite3_step(statement);
-
-  bool idTableExists = false;
-  if (res == SQLITE_ROW)
-    idTableExists = true;
-
-  sqlite3_finalize(statement);
-
-  if (!idTableExists) {
-    char* errorMessage = 0;
-    res = sqlite3_exec(m_database, INIT_ID_TABLE.c_str(), NULL, NULL, &errorMessage);
-
-    if (res != SQLITE_OK && errorMessage != 0) {
-      sqlite3_free(errorMessage);
-    }
-  }
-
-  //Check if Key table exists;
-  sqlite3_prepare_v2(m_database,
-                     "SELECT name FROM sqlite_master WHERE type='table' And name='Key'",
-                     -1, &statement, 0);
-  res = sqlite3_step(statement);
-
-  bool keyTableExists = false;
-  if (res == SQLITE_ROW)
-    keyTableExists = true;
-
-  sqlite3_finalize(statement);
-
-  if (!keyTableExists) {
-    char* errorMessage = 0;
-    res = sqlite3_exec(m_database, INIT_KEY_TABLE.c_str(), NULL, NULL, &errorMessage);
-
-    if (res != SQLITE_OK && errorMessage != 0) {
-      sqlite3_free(errorMessage);
-    }
-  }
-
-  //Check if Certificate table exists;
-  sqlite3_prepare_v2(m_database,
-                     "SELECT name FROM sqlite_master WHERE type='table' And name='Certificate'",
-                     -1, &statement, 0);
-  res = sqlite3_step(statement);
-
-  bool idCertificateTableExists = false;
-  if (res == SQLITE_ROW)
-    idCertificateTableExists = true;
-
-  sqlite3_finalize(statement);
-
-  if (!idCertificateTableExists) {
-    char* errorMessage = 0;
-    res = sqlite3_exec(m_database, INIT_CERT_TABLE.c_str(), NULL, NULL, &errorMessage);
-
-    if (res != SQLITE_OK && errorMessage != 0) {
-      sqlite3_free(errorMessage);
-    }
-  }
+  initializeTable("TpmInfo", INIT_TPM_INFO_TABLE); // Check if TpmInfo table exists;
+  initializeTable("Identity", INIT_ID_TABLE);      // Check if Identity table exists;
+  initializeTable("Key", INIT_KEY_TABLE);          // Check if Key table exists;
+  initializeTable("Certificate", INIT_CERT_TABLE); // Check if Certificate table exists;
 }
 
 SecPublicInfoSqlite3::~SecPublicInfoSqlite3()
@@ -193,6 +148,126 @@
 }
 
 bool
+SecPublicInfoSqlite3::doesTableExist(const string& tableName)
+{
+  // Check if the table exists;
+  bool doesTableExist = false;
+  string checkingString =
+    "SELECT name FROM sqlite_master WHERE type='table' AND name='" + tableName + "'";
+
+  sqlite3_stmt* statement;
+  sqlite3_prepare_v2(m_database, checkingString.c_str(), -1, &statement, 0);
+
+  int result = sqlite3_step(statement);
+  if (result == SQLITE_ROW)
+    doesTableExist = true;
+  sqlite3_finalize(statement);
+
+  return doesTableExist;
+}
+
+bool
+SecPublicInfoSqlite3::initializeTable(const string& tableName, const string& initCommand)
+{
+  // Create the table if it does not exist
+  if (!doesTableExist(tableName)) {
+    char* errorMessage = 0;
+    int result = sqlite3_exec(m_database, initCommand.c_str(), NULL, NULL, &errorMessage);
+
+    if (result != SQLITE_OK && errorMessage != 0) {
+      sqlite3_free(errorMessage);
+      return false;
+    }
+  }
+
+  return true;
+}
+
+void
+SecPublicInfoSqlite3::deleteTable(const string& tableName)
+{
+  string query = "DROP TABLE IF EXISTS " + tableName;
+
+  sqlite3_stmt* statement;
+  sqlite3_prepare_v2(m_database, query.c_str(), -1, &statement, 0);
+
+  sqlite3_step(statement);
+  sqlite3_finalize(statement);
+}
+
+void
+SecPublicInfoSqlite3::setTpmLocator(const string& tpmLocator)
+{
+  string currentTpm;
+  try {
+    currentTpm = getTpmLocator();
+  }
+  catch (SecPublicInfo::Error&) {
+    setTpmLocatorInternal(tpmLocator, false); // set tpmInfo without resetting
+    return;
+  }
+
+  if (currentTpm == tpmLocator)
+    return; // if the same, nothing will be changed
+
+  setTpmLocatorInternal(tpmLocator, true); // set tpmInfo and reset pib
+}
+
+string
+SecPublicInfoSqlite3::getTpmLocator()
+{
+  sqlite3_stmt* statement;
+  sqlite3_prepare_v2(m_database, "SELECT tpm_locator FROM TpmInfo", -1, &statement, 0);
+
+  int res = sqlite3_step(statement);
+
+  if (res == SQLITE_ROW) {
+    string tpmLocator = sqlite3_column_string(statement, 0);
+    sqlite3_finalize(statement);
+    return tpmLocator;
+  }
+  else {
+    sqlite3_finalize(statement);
+    throw SecPublicInfo::Error("TPM info does not exist");
+  }
+}
+
+void
+SecPublicInfoSqlite3::setTpmLocatorInternal(const string& tpmLocator, bool needReset)
+{
+  sqlite3_stmt* statement;
+
+  if (needReset) {
+    deleteTable("Identity");
+    deleteTable("Key");
+    deleteTable("Certificate");
+
+    initializeTable("Identity", INIT_ID_TABLE);
+    initializeTable("Key", INIT_KEY_TABLE);
+    initializeTable("Certificate", INIT_CERT_TABLE);
+
+    sqlite3_prepare_v2(m_database, "UPDATE TpmInfo SET tpm_locator = ?",
+                       -1, &statement, 0);
+    sqlite3_bind_string(statement, 1, tpmLocator, SQLITE_TRANSIENT);
+  }
+  else {
+    // no reset implies there is no tpmLocator record, insert one
+    sqlite3_prepare_v2(m_database, "INSERT INTO TpmInfo (tpm_locator) VALUES (?)",
+                       -1, &statement, 0);
+    sqlite3_bind_string(statement, 1, tpmLocator, SQLITE_TRANSIENT);
+  }
+
+  sqlite3_step(statement);
+  sqlite3_finalize(statement);
+}
+
+std::string
+SecPublicInfoSqlite3::getPibLocator()
+{
+  return string("pib-sqlite3:").append(m_location);
+}
+
+bool
 SecPublicInfoSqlite3::doesIdentityExist(const Name& identityName)
 {
   bool result = false;
@@ -202,7 +277,7 @@
                      "SELECT count(*) FROM Identity WHERE identity_name=?",
                      -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
   int res = sqlite3_step(statement);
 
   if (res == SQLITE_ROW) {
@@ -228,7 +303,7 @@
                      "INSERT OR REPLACE INTO Identity (identity_name) values (?)",
                      -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
 
   sqlite3_step(statement);
 
@@ -256,8 +331,8 @@
                      "SELECT count(*) FROM Key WHERE identity_name=? AND key_identifier=?",
                      -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(statement, 2, keyId, SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 2, keyId, SQLITE_TRANSIENT);
 
   int res = sqlite3_step(statement);
 
@@ -295,8 +370,8 @@
                       values (?, ?, ?, ?)",
                      -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(statement, 2, keyId, SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 2, keyId, SQLITE_TRANSIENT);
   sqlite3_bind_int(statement, 3, publicKeyDer.getKeyType());
   sqlite3_bind_blob(statement, 4,
                     publicKeyDer.get().buf(),
@@ -324,8 +399,8 @@
                      "SELECT public_key FROM Key WHERE identity_name=? AND key_identifier=?",
                      -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(statement, 2, keyId, SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 2, keyId, SQLITE_TRANSIENT);
 
   int res = sqlite3_step(statement);
 
@@ -359,8 +434,8 @@
                      "SELECT key_type FROM Key WHERE identity_name=? AND key_identifier=?",
                      -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(statement, 2, keyId, SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 2, keyId, SQLITE_TRANSIENT);
 
   int res = sqlite3_step(statement);
 
@@ -386,7 +461,7 @@
                      "SELECT count(*) FROM Certificate WHERE cert_name=?",
                      -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, certificateName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, certificateName.toUri(), SQLITE_TRANSIENT);
 
   int res = sqlite3_step(statement);
 
@@ -479,22 +554,22 @@
                       values (?, ?, ?, ?, datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), ?)",
                       -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, certificateName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, certificateName.toUri(), SQLITE_TRANSIENT);
 
   try
     {
       // this will throw an exception if the signature is not the standard one
       // or there is no key locator present
       std::string signerName = certificate.getSignature().getKeyLocator().getName().toUri();
-      sqlite3_bind_text(statement, 2, signerName, SQLITE_TRANSIENT);
+      sqlite3_bind_string(statement, 2, signerName, SQLITE_TRANSIENT);
     }
   catch (tlv::Error& e)
     {
       return;
     }
 
-  sqlite3_bind_text(statement, 3, identity.toUri(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(statement, 4, keyId, SQLITE_STATIC);
+  sqlite3_bind_string(statement, 3, identity.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 4, keyId, SQLITE_STATIC);
 
   sqlite3_bind_int64(statement, 5,
                      static_cast<sqlite3_int64>(
@@ -522,7 +597,7 @@
                      "SELECT certificate_data FROM Certificate WHERE cert_name=?",
                      -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, certificateName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, certificateName.toUri(), SQLITE_TRANSIENT);
 
   int res = sqlite3_step(statement);
 
@@ -554,8 +629,7 @@
 
   if (res == SQLITE_ROW)
     {
-      Name identity(string(reinterpret_cast<const char *>(sqlite3_column_text(statement, 0)),
-                           sqlite3_column_bytes(statement, 0)));
+      Name identity(sqlite3_column_string(statement, 0));
       sqlite3_finalize(statement);
       return identity;
     }
@@ -589,7 +663,7 @@
                      "UPDATE Identity SET default_identity=1 WHERE identity_name=?",
                      -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
 
   sqlite3_step(statement);
 
@@ -604,7 +678,7 @@
                      "SELECT key_identifier FROM Key WHERE identity_name=? AND default_key=1",
                      -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
 
   int res = sqlite3_step(statement);
 
@@ -639,7 +713,7 @@
                      "UPDATE Key SET default_key=0 WHERE default_key=1 and identity_name=?",
                      -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
 
   while (sqlite3_step(statement) == SQLITE_ROW)
     ;
@@ -651,8 +725,8 @@
                      "UPDATE Key SET default_key=1 WHERE identity_name=? AND key_identifier=?",
                      -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(statement, 2, keyId, SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 2, keyId, SQLITE_TRANSIENT);
 
   sqlite3_step(statement);
 
@@ -674,8 +748,8 @@
                       WHERE identity_name=? AND key_identifier=? AND default_cert=1",
                      -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(statement, 2, keyId, SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 2, keyId, SQLITE_TRANSIENT);
 
   int res = sqlite3_step(statement);
 
@@ -711,8 +785,8 @@
                       WHERE default_cert=1 AND identity_name=? AND key_identifier=?",
                      -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(statement, 2, keyId, SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 2, keyId, SQLITE_TRANSIENT);
 
   while (sqlite3_step(statement) == SQLITE_ROW)
     ;
@@ -725,9 +799,9 @@
                       WHERE identity_name=? AND key_identifier=? AND cert_name=?",
                      -1, &statement, 0);
 
-  sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(statement, 2, keyId, SQLITE_TRANSIENT);
-  sqlite3_bind_text(statement, 3, certificateName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 2, keyId, SQLITE_TRANSIENT);
+  sqlite3_bind_string(statement, 3, certificateName.toUri(), SQLITE_TRANSIENT);
 
   sqlite3_step(statement);
 
@@ -795,10 +869,7 @@
                        "SELECT key_identifier FROM Key WHERE default_key=0 and identity_name=?",
                        -1, &stmt, 0);
 
-  sqlite3_bind_text(stmt, 1,
-                    identity.toUri().c_str(),
-                    identity.toUri().size(),
-                    SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 1, identity.toUri(), SQLITE_TRANSIENT);
 
   while (sqlite3_step(stmt) == SQLITE_ROW)
     {
@@ -852,10 +923,10 @@
                        -1, &stmt, 0);
 
   Name identity = keyName.getPrefix(-1);
-  sqlite3_bind_text(stmt, 1, identity.toUri().c_str(), identity.toUri().size(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 1, identity.toUri(), SQLITE_TRANSIENT);
 
   std::string baseKeyName = keyName.get(-1).toUri();
-  sqlite3_bind_text(stmt, 2, baseKeyName.c_str(), baseKeyName.size(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 2, baseKeyName, SQLITE_TRANSIENT);
 
   while (sqlite3_step(stmt) == SQLITE_ROW)
     nameList.push_back(string(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)),
@@ -872,7 +943,7 @@
 
   sqlite3_stmt* stmt;
   sqlite3_prepare_v2(m_database, "DELETE FROM Certificate WHERE cert_name=?", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, certName.toUri().c_str(), certName.toUri().size(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 1, certName.toUri(), SQLITE_TRANSIENT);
   sqlite3_step(stmt);
   sqlite3_finalize(stmt);
 }
@@ -890,16 +961,16 @@
   sqlite3_prepare_v2(m_database,
                      "DELETE FROM Certificate WHERE identity_name=? and key_identifier=?",
                      -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, identity.c_str(), identity.size(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(stmt, 2, keyId.c_str(), keyId.size(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 1, identity, SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 2, keyId, SQLITE_TRANSIENT);
   sqlite3_step(stmt);
   sqlite3_finalize(stmt);
 
   sqlite3_prepare_v2(m_database,
                      "DELETE FROM Key WHERE identity_name=? and key_identifier=?",
                      -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, identity.c_str(), identity.size(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(stmt, 2, keyId.c_str(), keyId.size(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 1, identity, SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 2, keyId, SQLITE_TRANSIENT);
   sqlite3_step(stmt);
   sqlite3_finalize(stmt);
 }
@@ -911,19 +982,25 @@
 
   sqlite3_stmt* stmt;
   sqlite3_prepare_v2(m_database, "DELETE FROM Certificate WHERE identity_name=?", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, identity.c_str(), identity.size(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 1, identity, SQLITE_TRANSIENT);
   sqlite3_step(stmt);
   sqlite3_finalize(stmt);
 
   sqlite3_prepare_v2(m_database, "DELETE FROM Key WHERE identity_name=?", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, identity.c_str(), identity.size(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 1, identity, SQLITE_TRANSIENT);
   sqlite3_step(stmt);
   sqlite3_finalize(stmt);
 
   sqlite3_prepare_v2(m_database, "DELETE FROM Identity WHERE identity_name=?", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, identity.c_str(), identity.size(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 1, identity, SQLITE_TRANSIENT);
   sqlite3_step(stmt);
   sqlite3_finalize(stmt);
 }
 
+std::string
+SecPublicInfoSqlite3::getScheme()
+{
+  return SCHEME;
+}
+
 } // namespace ndn
diff --git a/src/security/sec-public-info-sqlite3.hpp b/src/security/sec-public-info-sqlite3.hpp
index beaff10..7c2fbb6 100644
--- a/src/security/sec-public-info-sqlite3.hpp
+++ b/src/security/sec-public-info-sqlite3.hpp
@@ -45,7 +45,8 @@
     }
   };
 
-  SecPublicInfoSqlite3();
+  explicit
+  SecPublicInfoSqlite3(const std::string& dir = "");
 
   virtual
   ~SecPublicInfoSqlite3();
@@ -53,6 +54,16 @@
   /**********************
    * from SecPublicInfo *
    **********************/
+
+  virtual void
+  setTpmLocator(const std::string& tpmLocator);
+
+  virtual std::string
+  getTpmLocator();
+
+  virtual std::string
+  getPibLocator();
+
   virtual bool
   doesIdentityExist(const Name& identityName);
 
@@ -118,16 +129,35 @@
   virtual void
   deleteIdentityInfo(const Name& identity);
 
-protected:
-  virtual void
+private:
+  bool
+  initializeTable(const std::string& tableName, const std::string& initCommand);
+
+  void
+  deleteTable(const std::string& tableName);
+
+  void
+  setTpmLocatorInternal(const std::string& tpmLocator, bool needReset);
+
+  void
   setDefaultIdentityInternal(const Name& identityName);
 
-  virtual void
+  void
   setDefaultKeyNameForIdentityInternal(const Name& keyName);
 
-  virtual void
+  void
   setDefaultCertificateNameForKeyInternal(const Name& certificateName);
 
+  std::string
+  getScheme();
+
+NDN_CXX_PUBLIC_WITH_TESTS_ELSE_PRIVATE:
+  bool
+  doesTableExist(const std::string& tableName);
+
+public:
+  static const std::string SCHEME;
+
 private:
   sqlite3* m_database;
 };
diff --git a/src/security/sec-public-info.cpp b/src/security/sec-public-info.cpp
new file mode 100644
index 0000000..6b01758
--- /dev/null
+++ b/src/security/sec-public-info.cpp
@@ -0,0 +1,161 @@
+/* -*- 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 "sec-public-info.hpp"
+
+namespace ndn {
+
+SecPublicInfo::SecPublicInfo(const std::string& location)
+  : m_location(location)
+{
+}
+
+SecPublicInfo::~SecPublicInfo()
+{
+}
+
+std::string
+SecPublicInfo::getPibLocator()
+{
+  return this->getScheme() + m_location;
+}
+
+void
+SecPublicInfo::addPublicKey(const Name& keyName, KeyType keyType, const PublicKey& publicKey)
+{
+  addKey(keyName, publicKey);
+}
+
+void
+SecPublicInfo::setDefaultIdentity(const Name& identityName)
+{
+  setDefaultIdentityInternal(identityName);
+  refreshDefaultCertificate();
+}
+
+void
+SecPublicInfo::setDefaultKeyNameForIdentity(const Name& keyName)
+{
+  setDefaultKeyNameForIdentityInternal(keyName);
+  refreshDefaultCertificate();
+}
+
+void
+SecPublicInfo::setDefaultCertificateNameForKey(const Name& certificateName)
+{
+  setDefaultCertificateNameForKeyInternal(certificateName);
+  refreshDefaultCertificate();
+}
+
+Name
+SecPublicInfo::getDefaultCertificateNameForIdentity(const Name& identityName)
+{
+  return getDefaultCertificateNameForKey(getDefaultKeyNameForIdentity(identityName));
+}
+
+Name
+SecPublicInfo::getDefaultCertificateName()
+{
+  if (m_defaultCertificate == nullptr)
+    refreshDefaultCertificate();
+
+  if (m_defaultCertificate == nullptr)
+    throw Error("No default certificate is set");
+
+  return m_defaultCertificate->getName();
+}
+
+Name
+SecPublicInfo::getNewKeyName(const Name& identityName, bool useKsk)
+{
+  std::ostringstream oss;
+
+  if (useKsk)
+    oss << "ksk-";
+  else
+    oss << "dsk-";
+
+  oss << time::toUnixTimestamp(time::system_clock::now()).count();
+
+  Name keyName = Name(identityName).append(oss.str());
+
+  if (doesPublicKeyExist(keyName))
+    throw Error("Key name already exists: " + keyName.toUri());
+
+  return keyName;
+}
+
+void
+SecPublicInfo::addCertificateAsKeyDefault(const IdentityCertificate& certificate)
+{
+  addCertificate(certificate);
+  setDefaultCertificateNameForKeyInternal(certificate.getName());
+  refreshDefaultCertificate();
+}
+
+void
+SecPublicInfo::addCertificateAsIdentityDefault(const IdentityCertificate& certificate)
+{
+  addCertificate(certificate);
+  Name certName = certificate.getName();
+  Name keyName = IdentityCertificate::certificateNameToPublicKeyName(certName);
+  setDefaultKeyNameForIdentityInternal(keyName);
+  setDefaultCertificateNameForKeyInternal(certName);
+  refreshDefaultCertificate();
+}
+
+void
+SecPublicInfo::addCertificateAsSystemDefault(const IdentityCertificate& certificate)
+{
+  addCertificate(certificate);
+  Name certName = certificate.getName();
+  Name keyName = IdentityCertificate::certificateNameToPublicKeyName(certName);
+  setDefaultIdentityInternal(keyName.getPrefix(-1));
+  setDefaultKeyNameForIdentityInternal(keyName);
+  setDefaultCertificateNameForKeyInternal(certName);
+  refreshDefaultCertificate();
+}
+
+shared_ptr<IdentityCertificate>
+SecPublicInfo::defaultCertificate()
+{
+  return getDefaultCertificate();
+}
+
+shared_ptr<IdentityCertificate>
+SecPublicInfo::getDefaultCertificate()
+{
+  return m_defaultCertificate;
+}
+
+void
+SecPublicInfo::refreshDefaultCertificate()
+{
+  try {
+    Name certName = getDefaultCertificateNameForIdentity(getDefaultIdentity());
+    m_defaultCertificate = getCertificate(certName);
+  }
+  catch (SecPublicInfo::Error&) {
+    m_defaultCertificate.reset();
+  }
+}
+
+} // namespace ndn
diff --git a/src/security/sec-public-info.hpp b/src/security/sec-public-info.hpp
index 743914e..4afee08 100644
--- a/src/security/sec-public-info.hpp
+++ b/src/security/sec-public-info.hpp
@@ -17,9 +17,6 @@
  * <http://www.gnu.org/licenses/>.
  *
  * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
- *
- * @author Yingdi Yu <http://irl.cs.ucla.edu/~yingdi/>
- * @author Jeff Thompson <jefft0@remap.ucla.edu>
  */
 
 #ifndef NDN_SECURITY_SEC_PUBLIC_INFO_HPP
@@ -52,13 +49,42 @@
     }
   };
 
+  explicit
+  SecPublicInfo(const std::string& location);
+
   /**
    * @brief The virtual Destructor
    */
   virtual
-  ~SecPublicInfo()
-  {
-  }
+  ~SecPublicInfo();
+
+  /**
+   * @brief Set the corresponding TPM information to @p tpmLocator
+   *
+   * If the provided @p tpmLocator is different from the existing one, the PIB will be reset,
+   * otherwise nothing will be changed.
+   *
+   * For legacy issue, the TPM info may not exist (some old PIB content may not have this info),
+   * this method will simply set the TPM info as provided without changing anything else. Thus an
+   * ideal process of handling old PIB is to check if TPM info exists. If it does not exist,
+   * then set it to the default value according to configuration.
+   */
+  virtual void
+  setTpmLocator(const std::string& tpmLocator) = 0;
+
+  /**
+   * @brief Get TPM Locator
+   *
+   * @throws SecPublicInfo::Error if the TPM info does not exist
+   */
+  virtual std::string
+  getTpmLocator() = 0;
+
+  /**
+   * @brief Get PIB Locator
+   */
+  std::string
+  getPibLocator();
 
   /**
    * @brief Check if the specified identity already exists
@@ -99,17 +125,14 @@
   /**
    * @brief Add a public key to the identity storage.
    *
-   * @deprecated Use addKey instead
-   *
    * @param keyName The name of the public key to be added
    * @param keyType Type of the public key to be added
    * @param publicKey Reference to the PublicKey object
+   * @deprecated Use addKey instead
    */
+  DEPRECATED(
   void
-  addPublicKey(const Name& keyName, KeyType keyType, const PublicKey& publicKey)
-  {
-    addKey(keyName, publicKey);
-  }
+  addPublicKey(const Name& keyName, KeyType keyType, const PublicKey& publicKey));
 
   /**
    * @brief Add a public key to the identity storage.
@@ -306,6 +329,12 @@
   virtual void
   setDefaultCertificateNameForKeyInternal(const Name& certificateName) = 0;
 
+  /**
+   * @brief return the scheme of the PibLocator
+   */
+  virtual std::string
+  getScheme() = 0;
+
 public:
 
   /*****************************************
@@ -423,125 +452,9 @@
 
 protected:
   shared_ptr<IdentityCertificate> m_defaultCertificate;
+  std::string m_location;
 };
 
-inline void
-SecPublicInfo::setDefaultIdentity(const Name& identityName)
-{
-  setDefaultIdentityInternal(identityName);
-  refreshDefaultCertificate();
-}
-
-inline void
-SecPublicInfo::setDefaultKeyNameForIdentity(const Name& keyName)
-{
-  setDefaultKeyNameForIdentityInternal(keyName);
-  refreshDefaultCertificate();
-}
-
-inline void
-SecPublicInfo::setDefaultCertificateNameForKey(const Name& certificateName)
-{
-  setDefaultCertificateNameForKeyInternal(certificateName);
-  refreshDefaultCertificate();
-}
-
-inline Name
-SecPublicInfo::getDefaultCertificateNameForIdentity(const Name& identityName)
-{
-  return getDefaultCertificateNameForKey(getDefaultKeyNameForIdentity(identityName));
-}
-
-inline Name
-SecPublicInfo::getNewKeyName (const Name& identityName, bool useKsk)
-{
-  std::ostringstream oss;
-
-  if (useKsk)
-    oss << "ksk-";
-  else
-    oss << "dsk-";
-
-  oss << time::toUnixTimestamp(time::system_clock::now()).count();
-
-  Name keyName = Name(identityName).append(oss.str());
-
-  if (doesPublicKeyExist(keyName))
-    throw Error("Key name already exists: " + keyName.toUri());
-
-  return keyName;
-}
-
-inline Name
-SecPublicInfo::getDefaultCertificateName()
-{
-  if (!static_cast<bool>(m_defaultCertificate))
-    refreshDefaultCertificate();
-
-  if (!static_cast<bool>(m_defaultCertificate))
-    throw Error("No default certificate is set");
-
-  return m_defaultCertificate->getName();
-}
-
-inline void
-SecPublicInfo::addCertificateAsKeyDefault(const IdentityCertificate& certificate)
-{
-  addCertificate(certificate);
-  setDefaultCertificateNameForKeyInternal(certificate.getName());
-  refreshDefaultCertificate();
-}
-
-inline void
-SecPublicInfo::addCertificateAsIdentityDefault(const IdentityCertificate& certificate)
-{
-  addCertificate(certificate);
-  Name certName = certificate.getName();
-  Name keyName = IdentityCertificate::certificateNameToPublicKeyName(certName);
-  setDefaultKeyNameForIdentityInternal(keyName);
-  setDefaultCertificateNameForKeyInternal(certName);
-  refreshDefaultCertificate();
-}
-
-inline void
-SecPublicInfo::addCertificateAsSystemDefault(const IdentityCertificate& certificate)
-{
-  addCertificate(certificate);
-  Name certName = certificate.getName();
-  Name keyName = IdentityCertificate::certificateNameToPublicKeyName(certName);
-  setDefaultIdentityInternal(keyName.getPrefix(-1));
-  setDefaultKeyNameForIdentityInternal(keyName);
-  setDefaultCertificateNameForKeyInternal(certName);
-  refreshDefaultCertificate();
-}
-
-inline shared_ptr<IdentityCertificate>
-SecPublicInfo::defaultCertificate()
-{
-  return getDefaultCertificate();
-}
-
-inline shared_ptr<IdentityCertificate>
-SecPublicInfo::getDefaultCertificate()
-{
-  return m_defaultCertificate;
-}
-
-inline void
-SecPublicInfo::refreshDefaultCertificate()
-{
-  try
-    {
-      Name certName = getDefaultCertificateNameForIdentity(getDefaultIdentity());
-      m_defaultCertificate = getCertificate(certName);
-    }
-  catch (SecPublicInfo::Error& e)
-    {
-      m_defaultCertificate.reset();
-    }
-
-}
-
 } // namespace ndn
 
-#endif //NDN_SECURITY_SEC_PUBLIC_INFO_HPP
+#endif // NDN_SECURITY_SEC_PUBLIC_INFO_HPP
diff --git a/src/security/sec-tpm-file.cpp b/src/security/sec-tpm-file.cpp
index 7d0748d..26862c5 100644
--- a/src/security/sec-tpm-file.cpp
+++ b/src/security/sec-tpm-file.cpp
@@ -44,6 +44,8 @@
 using std::ostringstream;
 using std::ofstream;
 
+const std::string SecTpmFile::SCHEME("tpm-file:");
+
 class SecTpmFile::Impl
 {
 public:
@@ -53,7 +55,7 @@
     if (dir.empty())
       m_keystorePath = boost::filesystem::path(getenv("HOME")) / ".ndn" / "ndnsec-tpm-file";
     else
-      m_keystorePath = dir;
+      m_keystorePath = boost::filesystem::path(dir) / ".ndn" / "ndnsec-tpm-file";
 
     boost::filesystem::create_directories(m_keystorePath);
   }
@@ -95,12 +97,17 @@
 };
 
 
-SecTpmFile::SecTpmFile(const string& dir)
-  : m_impl(new Impl(dir))
+SecTpmFile::SecTpmFile(const string& location)
+  : SecTpm(location)
+  , m_impl(new Impl(location))
   , m_inTerminal(false)
 {
 }
 
+SecTpmFile::~SecTpmFile()
+{
+}
+
 void
 SecTpmFile::generateKeyPairInTpm(const Name& keyName, const KeyParams& params)
 {
@@ -239,6 +246,12 @@
                                 os.str().size());
 }
 
+std::string
+SecTpmFile::getScheme()
+{
+  return SCHEME;
+}
+
 ConstBufferPtr
 SecTpmFile::exportPrivateKeyPkcs8FromTpm(const Name& keyName)
 {
diff --git a/src/security/sec-tpm-file.hpp b/src/security/sec-tpm-file.hpp
index 3c97e4e..f9d954e 100644
--- a/src/security/sec-tpm-file.hpp
+++ b/src/security/sec-tpm-file.hpp
@@ -49,9 +49,7 @@
   SecTpmFile(const std::string& dir = "");
 
   virtual
-  ~SecTpmFile()
-  {
-  }
+  ~SecTpmFile();
 
   virtual void
   setTpmPassword(const uint8_t* password, size_t passwordLength)
@@ -124,6 +122,8 @@
   ////////////////////////////////
   // From TrustedPlatformModule //
   ////////////////////////////////
+  virtual std::string
+  getScheme();
 
   virtual ConstBufferPtr
   exportPrivateKeyPkcs8FromTpm(const Name& keyName);
@@ -134,12 +134,15 @@
   virtual bool
   importPublicKeyPkcs1IntoTpm(const Name& keyName, const uint8_t* buf, size_t size);
 
+public:
+  static const std::string SCHEME;
+
 private:
   class Impl;
-  shared_ptr<Impl> m_impl;
+  unique_ptr<Impl> m_impl;
   bool m_inTerminal;
 };
 
 } // namespace ndn
 
-#endif  //NDN_SECURITY_SEC_TPM_FILE_HPP
+#endif  // NDN_SECURITY_SEC_TPM_FILE_HPP
diff --git a/src/security/sec-tpm-osx.cpp b/src/security/sec-tpm-osx.cpp
index 9f722fd..593c586 100644
--- a/src/security/sec-tpm-osx.cpp
+++ b/src/security/sec-tpm-osx.cpp
@@ -47,6 +47,8 @@
 
 using std::string;
 
+const std::string SecTpmOsx::SCHEME("tpm-osxkeychain:");
+
 /**
  * @brief Helper class to wrap CoreFoundation object pointers
  *
@@ -236,9 +238,11 @@
   bool m_inTerminal;
 };
 
-SecTpmOsx::SecTpmOsx()
-  : m_impl(new Impl)
+SecTpmOsx::SecTpmOsx(const std::string& location)
+  : SecTpm(location)
+  , m_impl(new Impl)
 {
+  // TODO: add location support
   if (m_impl->m_inTerminal)
     SecKeychainSetUserInteractionAllowed(false);
   else
@@ -250,8 +254,8 @@
     throw Error("No default keychain, create one first!");
 }
 
-SecTpmOsx::~SecTpmOsx(){
-  //TODO: implement
+SecTpmOsx::~SecTpmOsx()
+{
 }
 
 void
@@ -525,6 +529,12 @@
   return key;
 }
 
+std::string
+SecTpmOsx::getScheme()
+{
+  return SCHEME;
+}
+
 ConstBufferPtr
 SecTpmOsx::exportPrivateKeyPkcs8FromTpmInternal(const Name& keyName, bool needRetry)
 {
diff --git a/src/security/sec-tpm-osx.hpp b/src/security/sec-tpm-osx.hpp
index fca8dda..fc6360d 100644
--- a/src/security/sec-tpm-osx.hpp
+++ b/src/security/sec-tpm-osx.hpp
@@ -47,14 +47,13 @@
     }
   };
 
-  SecTpmOsx();
+  explicit
+  SecTpmOsx(const std::string& location = "");
 
   virtual
   ~SecTpmOsx();
 
-
   // Following methods are inherited from SecTpm
-
   virtual void
   setTpmPassword(const uint8_t* password, size_t passwordLength);
 
@@ -115,6 +114,9 @@
 
 protected:
   // Following methods are inherited from SecTpm
+  virtual std::string
+  getScheme();
+
   virtual ConstBufferPtr
   exportPrivateKeyPkcs8FromTpm(const Name& keyName)
   {
@@ -150,6 +152,9 @@
                     const Name& keyName, DigestAlgorithm digestAlgorithm,
                     bool needRetry);
 
+public:
+  static const std::string SCHEME;
+
 private:
   class Impl;
   shared_ptr<Impl> m_impl;
diff --git a/src/security/sec-tpm.cpp b/src/security/sec-tpm.cpp
index 97adf7a..d8c6a4f 100644
--- a/src/security/sec-tpm.cpp
+++ b/src/security/sec-tpm.cpp
@@ -31,6 +31,21 @@
 
 using std::string;
 
+SecTpm::SecTpm(const string& location)
+  : m_location(location)
+{
+}
+
+SecTpm::~SecTpm()
+{
+}
+
+std::string
+SecTpm::getTpmLocator()
+{
+  return this->getScheme() + m_location;
+}
+
 ConstBufferPtr
 SecTpm::exportPrivateKeyPkcs5FromTpm(const Name& keyName, const string& passwordStr)
 {
diff --git a/src/security/sec-tpm.hpp b/src/security/sec-tpm.hpp
index 031aa2b..20a103d 100644
--- a/src/security/sec-tpm.hpp
+++ b/src/security/sec-tpm.hpp
@@ -51,10 +51,14 @@
     }
   };
 
+  explicit
+  SecTpm(const std::string& location);
+
   virtual
-  ~SecTpm()
-  {
-  }
+  ~SecTpm();
+
+  std::string
+  getTpmLocator();
 
   /**
    * @brief set password of TPM
@@ -246,6 +250,9 @@
                                const std::string& password);
 
 protected:
+  virtual std::string
+  getScheme() = 0;
+
   /**
    * @brief Export a private key in PKCS#8 format.
    *
@@ -288,8 +295,11 @@
    */
   virtual bool
   getImpExpPassWord(std::string& password, const std::string& prompt);
+
+protected:
+  std::string m_location;
 };
 
 } // namespace ndn
 
-#endif //NDN_SECURITY_SEC_TPM_HPP
+#endif // NDN_SECURITY_SEC_TPM_HPP