security: Adding SecTpmFile which a pure file based "TPM".

Change-Id: I73b6ed8e0876217642ab6a8733c4da35ef9e69d9
diff --git a/Makefile.am b/Makefile.am
index 60188c1..f762073 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -105,6 +105,7 @@
   src/security/identity-certificate.cpp \
   src/security/public-key.cpp \
   src/security/sec-public-info-sqlite3.cpp \
+  src/security/sec-tpm-file.cpp \
   src/security/sec-public-info-memory.cpp \
   src/security/sec-tpm-memory.cpp \
   src/security/verifier.cpp \
@@ -129,7 +130,7 @@
   EXTRA_DIST = src/security/sec-tpm-osx.cpp
 endif
 
-libndn_cpp_dev_la_LIBADD  = @OPENSSL_LIBS@     @CRYPTOPP_LIBS@     @OSX_SECURITY_LIBS@  @BOOST_SYSTEM_LIB@
+libndn_cpp_dev_la_LIBADD  = @OPENSSL_LIBS@     @CRYPTOPP_LIBS@     @OSX_SECURITY_LIBS@  @BOOST_SYSTEM_LIB@ @BOOST_FILESYSTEM_LIB@
 libndn_cpp_dev_la_LDFLAGS = @OPENSSL_LDFLAGS@  @CRYPTOPP_LDFLAGS@  @SQLITE3_LDFLAGS@    @BOOST_LDFLAGS@
 libndn_cpp_dev_la_CFLAGS  = @OPENSSL_INCLUDES@ @CRYPTOPP_INCLUDES@ @SQLITE3_CFLAGS@     @BOOST_CPPFLAGS@
 
diff --git a/configure.ac b/configure.ac
index 6647cdc..c7c686c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -95,6 +95,7 @@
 )
 
 AX_BOOST_SYSTEM
+AX_BOOST_FILESYSTEM
 AX_BOOST_UNIT_TEST_FRAMEWORK
 AM_CONDITIONAL(HAVE_BOOST_UNIT_TEST_FRAMEWORK, [test "x$ax_cv_boost_unit_test_framework" = "xyes"])
 
diff --git a/include/ndn-cpp-dev/security/sec-tpm-file.hpp b/include/ndn-cpp-dev/security/sec-tpm-file.hpp
new file mode 100644
index 0000000..8ef5586
--- /dev/null
+++ b/include/ndn-cpp-dev/security/sec-tpm-file.hpp
@@ -0,0 +1,115 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/**
+ * Copyright (C) 2013 Regents of the University of California.
+ * @author: Xingyu Ma <maxy12@cs.ucla.edu>
+ *          Yingdi Yu <yingdi@cs.ucla.edu>
+ * See COPYING for copyright and distribution information.
+ */
+
+#ifndef NDN_SEC_TPM_FILE_HPP
+#define NDN_SEC_TPM_FILE_HPP
+
+#include "../common.hpp"
+
+#include "sec-tpm.hpp"
+
+namespace ndn 
+{
+
+class SecTpmFile : public SecTpm
+{
+public:
+  struct Error : public SecTpm::Error { Error(const std::string &what) : SecTpm::Error(what) {} };
+
+  SecTpmFile(const std::string & dir = "");
+
+  /**
+   * @brief destructor
+   */
+  virtual
+  ~SecTpmFile() {};
+
+  /**
+   * Generate a pair of asymmetric keys.
+   * @param keyName The name of the key pair.
+   * @param keyType The type of the key pair, e.g. KEY_TYPE_RSA.
+   * @param keySize The size of the key pair.
+   */
+  virtual void
+  generateKeyPairInTpm(const Name & keyName, KeyType keyType, int keySize);
+
+  /**
+   * Get the public key
+   * @param keyName The name of public key.
+   * @return The public key.
+   */
+  virtual ptr_lib::shared_ptr<PublicKey>
+  getPublicKeyFromTpm(const Name & keyName);
+
+  /**
+   * Fetch the private key for keyName and sign the data, returning a signature block.
+   * Throw Error if signing fails.
+   * @param data Pointer to the input byte array.
+   * @param dataLength The length of data.
+   * @param keyName The name of the signing key.
+   * @param digestAlgorithm the digest algorithm.
+   * @return The signature block.
+   */  
+  virtual Block
+  signInTpm(const uint8_t *data, size_t dataLength, const Name& keyName, DigestAlgorithm digestAlgorithm);
+
+  /**
+   * Decrypt data.
+   * @param keyName The name of the decrypting key.
+   * @param data The byte to be decrypted.
+   * @param dataLength the length of data.
+   * @param isSymmetric If true symmetric encryption is used, otherwise asymmetric encryption is used.
+   * @return The decrypted data.
+   */
+  virtual ConstBufferPtr 
+  decryptInTpm(const Name& keyName, const uint8_t* data, size_t dataLength, bool isSymmetric);
+
+  /**
+   * Encrypt data.
+   * @param keyName The name of the encrypting key.
+   * @param data The byte to be encrypted.
+   * @param dataLength the length of data.
+   * @param isSymmetric If true symmetric encryption is used, otherwise asymmetric decryption is used.
+   * @return The encrypted data.
+   */
+  virtual ConstBufferPtr
+  encryptInTpm(const Name& keyName, const uint8_t* data, size_t dataLength, bool isSymmetric);
+
+
+  /**
+   * Generate a symmetric key.
+   * @param keyName The name of the key.
+   * @param keyType The type of the key, e.g. KEY_TYPE_AES.
+   * @param keySize The size of the key.
+   */
+  virtual void 
+  generateSymmetricKeyInTpm(const Name& keyName, KeyType keyType, int keySize);
+
+  /**
+   * Check if a particular key exists.
+   * @param keyName The name of the key.
+   * @param keyClass The class of the key, e.g. KEY_CLASS_PUBLIC, KEY_CLASS_PRIVATE, or KEY_CLASS_SYMMETRIC.
+   * @return True if the key exists, otherwise false.
+   */
+  virtual bool
+  doesKeyExistInTpm(const Name& keyName, KeyClass keyClass);
+
+  std::string
+  nameTransform(const std::string &keyName, const std::string &extension);
+
+private:
+  void 
+  maintainMapping(std::string str1, std::string str2);
+  
+private:
+  class Impl;
+  std::auto_ptr<Impl> impl_;
+};
+}//ndn
+
+#endif
diff --git a/libndn-cpp-dev.pc.in b/libndn-cpp-dev.pc.in
index b862024..6219d0b 100644
--- a/libndn-cpp-dev.pc.in
+++ b/libndn-cpp-dev.pc.in
@@ -6,5 +6,5 @@
 Name: libndn-cpp-dev
 Description: Development version of C++ API for NDN (NDN-TLV packet format)
 Version: @VERSION@
-Libs: -L${libdir} @OPENSSL_LDFLAGS@ @CRYPTOPP_LDFLAGS@ @SQLITE3_LDFLAGS@ @BOOST_LDFLAGS@ -lndn-cpp-dev @OPENSSL_LIBS@ @CRYPTOPP_LIBS@ @OSX_SECURITY_LIBS@ @BOOST_SYSTEM_LIB@
+Libs: -L${libdir} @OPENSSL_LDFLAGS@ @CRYPTOPP_LDFLAGS@ @SQLITE3_LDFLAGS@ @BOOST_LDFLAGS@ -lndn-cpp-dev @OPENSSL_LIBS@ @CRYPTOPP_LIBS@ @OSX_SECURITY_LIBS@ @BOOST_SYSTEM_LIB@ @BOOST_FILESYSTEM_LIB@
 Cflags: -I${includedir} @OPENSSL_INCLUDES@ @CRYPTOPP_INCLUDES@ @SQLITE3_CFLAGS@ @BOOST_CPPFLAGS@
diff --git a/m4/ax_boost_filesystem.m4 b/m4/ax_boost_filesystem.m4
new file mode 100644
index 0000000..f162163
--- /dev/null
+++ b/m4/ax_boost_filesystem.m4
@@ -0,0 +1,118 @@
+# ===========================================================================
+#    http://www.gnu.org/software/autoconf-archive/ax_boost_filesystem.html
+# ===========================================================================
+#
+# SYNOPSIS
+#
+#   AX_BOOST_FILESYSTEM
+#
+# DESCRIPTION
+#
+#   Test for Filesystem library from the Boost C++ libraries. The macro
+#   requires a preceding call to AX_BOOST_BASE. Further documentation is
+#   available at <http://randspringer.de/boost/index.html>.
+#
+#   This macro calls:
+#
+#     AC_SUBST(BOOST_FILESYSTEM_LIB)
+#
+#   And sets:
+#
+#     HAVE_BOOST_FILESYSTEM
+#
+# LICENSE
+#
+#   Copyright (c) 2009 Thomas Porschberg <thomas@randspringer.de>
+#   Copyright (c) 2009 Michael Tindal
+#   Copyright (c) 2009 Roman Rybalko <libtorrent@romanr.info>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 26
+
+AC_DEFUN([AX_BOOST_FILESYSTEM],
+[
+	AC_ARG_WITH([boost-filesystem],
+	AS_HELP_STRING([--with-boost-filesystem@<:@=special-lib@:>@],
+                   [use the Filesystem library from boost - it is possible to specify a certain library for the linker
+                        e.g. --with-boost-filesystem=boost_filesystem-gcc-mt ]),
+        [
+        if test "$withval" = "no"; then
+			want_boost="no"
+        elif test "$withval" = "yes"; then
+            want_boost="yes"
+            ax_boost_user_filesystem_lib=""
+        else
+		    want_boost="yes"
+		ax_boost_user_filesystem_lib="$withval"
+		fi
+        ],
+        [want_boost="yes"]
+	)
+
+	if test "x$want_boost" = "xyes"; then
+        AC_REQUIRE([AC_PROG_CC])
+		CPPFLAGS_SAVED="$CPPFLAGS"
+		CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS"
+		export CPPFLAGS
+
+		LDFLAGS_SAVED="$LDFLAGS"
+		LDFLAGS="$LDFLAGS $BOOST_LDFLAGS"
+		export LDFLAGS
+
+		LIBS_SAVED=$LIBS
+		LIBS="$LIBS $BOOST_SYSTEM_LIB"
+		export LIBS
+
+        AC_CACHE_CHECK(whether the Boost::Filesystem library is available,
+					   ax_cv_boost_filesystem,
+        [AC_LANG_PUSH([C++])
+         AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[@%:@include <boost/filesystem/path.hpp>]],
+                                   [[using namespace boost::filesystem;
+                                   path my_path( "foo/bar/data.txt" );
+                                   return 0;]])],
+					       ax_cv_boost_filesystem=yes, ax_cv_boost_filesystem=no)
+         AC_LANG_POP([C++])
+		])
+		if test "x$ax_cv_boost_filesystem" = "xyes"; then
+			AC_DEFINE(HAVE_BOOST_FILESYSTEM,,[define if the Boost::Filesystem library is available])
+            BOOSTLIBDIR=`echo $BOOST_LDFLAGS | sed -e 's/@<:@^\/@:>@*//'`
+            if test "x$ax_boost_user_filesystem_lib" = "x"; then
+                for libextension in `ls -r $BOOSTLIBDIR/libboost_filesystem* 2>/dev/null | sed 's,.*/lib,,' | sed 's,\..*,,'` ; do
+                     ax_lib=${libextension}
+				    AC_CHECK_LIB($ax_lib, exit,
+                                 [BOOST_FILESYSTEM_LIB="-l$ax_lib"; AC_SUBST(BOOST_FILESYSTEM_LIB) link_filesystem="yes"; break],
+                                 [link_filesystem="no"])
+				done
+                if test "x$link_filesystem" != "xyes"; then
+                for libextension in `ls -r $BOOSTLIBDIR/boost_filesystem* 2>/dev/null | sed 's,.*/,,' | sed -e 's,\..*,,'` ; do
+                     ax_lib=${libextension}
+				    AC_CHECK_LIB($ax_lib, exit,
+                                 [BOOST_FILESYSTEM_LIB="-l$ax_lib"; AC_SUBST(BOOST_FILESYSTEM_LIB) link_filesystem="yes"; break],
+                                 [link_filesystem="no"])
+				done
+		    fi
+            else
+               for ax_lib in $ax_boost_user_filesystem_lib boost_filesystem-$ax_boost_user_filesystem_lib; do
+				      AC_CHECK_LIB($ax_lib, exit,
+                                   [BOOST_FILESYSTEM_LIB="-l$ax_lib"; AC_SUBST(BOOST_FILESYSTEM_LIB) link_filesystem="yes"; break],
+                                   [link_filesystem="no"])
+                  done
+
+            fi
+            if test "x$ax_lib" = "x"; then
+                AC_MSG_ERROR(Could not find a version of the library!)
+            fi
+			if test "x$link_filesystem" != "xyes"; then
+				AC_MSG_ERROR(Could not link against $ax_lib !)
+			fi
+		fi
+
+		CPPFLAGS="$CPPFLAGS_SAVED"
+		LDFLAGS="$LDFLAGS_SAVED"
+		LIBS="$LIBS_SAVED"
+	fi
+])
diff --git a/src/security/sec-tpm-file.cpp b/src/security/sec-tpm-file.cpp
new file mode 100644
index 0000000..c711089
--- /dev/null
+++ b/src/security/sec-tpm-file.cpp
@@ -0,0 +1,380 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/**
+ * Copyright (C) 2013 Regents of the University of California.
+ * @author: Xingyu Ma <maxy12@cs.ucla.edu>
+ *          Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ *          Yingdi Yu <yingdi@cs.ucla.edu>
+ * See COPYING for copyright and distribution information.
+ */
+
+#include <ndn-cpp-dev/security/sec-tpm-file.hpp>
+
+#include <string>
+
+#include <boost/filesystem.hpp>
+#include <boost/algorithm/string.hpp>
+
+#include <cryptopp/rsa.h>
+#include <cryptopp/files.h>
+#include <cryptopp/base64.h>
+#include <cryptopp/hex.h>
+#include <cryptopp/osrng.h>
+#include <cryptopp/sha.h>
+#include <cryptopp/pssr.h>
+#include <cryptopp/modes.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+using namespace CryptoPP;
+using namespace ndn;
+using namespace std;
+
+namespace ndn
+{
+
+class SecTpmFile::Impl {
+public:
+  Impl(const string &dir)
+  {
+    if(dir.empty())
+      m_keystorePath = boost::filesystem::path(getenv("HOME")) / ".ndnx" / "ndnsec-keys";
+    else
+      m_keystorePath = dir;
+    
+    boost::filesystem::create_directories (m_keystorePath);
+  }
+
+public:
+  boost::filesystem::path m_keystorePath;
+};
+
+SecTpmFile::SecTpmFile(const string & dir)
+  : impl_(new Impl(dir))
+{}
+
+void
+SecTpmFile::generateKeyPairInTpm(const Name & keyName, KeyType keyType, int keySize)
+{
+  string keyURI = keyName.toUri();
+
+  if(doesKeyExistInTpm(keyName, KEY_CLASS_PUBLIC))
+    throw Error("public key exists");
+  if(doesKeyExistInTpm(keyName, KEY_CLASS_PRIVATE))
+    throw Error("private key exists");
+
+  string keyFileName = nameTransform(keyURI, "");
+  maintainMapping(keyURI, keyFileName);
+
+  try{
+    switch(keyType){
+    case KEY_TYPE_RSA:
+      {
+	AutoSeededRandomPool rng;
+	InvertibleRSAFunction privateKey;
+	privateKey.Initialize(rng, keySize);
+	
+	string privateKeyFileName = keyFileName + ".pri";
+	Base64Encoder privateKeySink(new FileSink(privateKeyFileName.c_str()));
+	privateKey.DEREncode(privateKeySink);
+	privateKeySink.MessageEnd();
+	
+	RSAFunction publicKey(privateKey);
+	string publicKeyFileName = keyFileName + ".pub";
+	Base64Encoder publicKeySink(new FileSink(publicKeyFileName.c_str()));
+	publicKey.DEREncode(publicKeySink);
+	publicKeySink.MessageEnd();
+	
+	/*set file permission*/
+	chmod(privateKeyFileName.c_str(), 0000400);
+	chmod(publicKeyFileName.c_str(), 0000444);
+	return;
+      }
+    default:
+      throw Error("Unsupported key type!");
+    }
+  }catch(const CryptoPP::Exception& e){
+    throw Error(e.what());
+  }
+}
+
+ptr_lib::shared_ptr<PublicKey>
+SecTpmFile::getPublicKeyFromTpm(const Name & keyName)
+{
+  string keyURI = keyName.toUri();
+
+  if(!doesKeyExistInTpm(keyName, KEY_CLASS_PUBLIC))
+    throw Error("public key doesn't exists");
+
+  string publicKeyFileName = nameTransform(keyURI, ".pub");
+  std::ostringstream os;
+  try{
+    FileSource(publicKeyFileName.c_str(), true, new Base64Decoder(new FileSink(os)));
+  }catch(const CryptoPP::Exception& e){
+    throw Error(e.what());
+  }
+
+  return ptr_lib::make_shared<PublicKey>(reinterpret_cast<const uint8_t*>(os.str().c_str()), os.str().size());
+}
+
+Block
+SecTpmFile::signInTpm(const uint8_t *data, size_t dataLength, const Name& keyName, DigestAlgorithm digestAlgorithm)
+{
+  string keyURI = keyName.toUri();
+
+  if(!doesKeyExistInTpm(keyName, KEY_CLASS_PRIVATE))
+    throw Error("private key doesn't exists");
+ 
+  try{
+    AutoSeededRandomPool rng;
+      
+    //Read private key
+    ByteQueue bytes;
+    string privateKeyFileName = nameTransform(keyURI, ".pri");
+    FileSource file(privateKeyFileName.c_str(), true, new Base64Decoder);
+    file.TransferTo(bytes);
+    bytes.MessageEnd();
+    RSA::PrivateKey privateKey;
+    privateKey.Load(bytes);
+  
+    //Sign message
+    switch(digestAlgorithm){
+    case DIGEST_ALGORITHM_SHA256:
+      {
+	RSASS<PKCS1v15, SHA256>::Signer signer(privateKey);
+	
+	OBufferStream os;
+	StringSource(data, dataLength, true, new SignerFilter(rng, signer, new FileSink(os)));
+	
+	return Block(Tlv::SignatureValue, os.buf());
+      }
+    default:
+      throw Error("Unsupported digest algorithm!");
+    }
+  }catch(const CryptoPP::Exception& e){
+    throw Error(e.what());
+  }
+}
+
+
+ConstBufferPtr
+SecTpmFile::decryptInTpm(const Name& keyName, const uint8_t* data, size_t dataLength, bool isSymmetric)
+{
+  string keyURI = keyName.toUri();
+  if (!isSymmetric)
+    {
+      if(!doesKeyExistInTpm(keyName, KEY_CLASS_PRIVATE))
+	throw Error("private key doesn't exist");
+
+      try{
+	AutoSeededRandomPool rng;
+	
+	//Read private key
+	ByteQueue bytes;
+	string privateKeyFileName = nameTransform(keyURI, ".pri");
+	FileSource file(privateKeyFileName.c_str(), true, new Base64Decoder);
+	file.TransferTo(bytes);
+	bytes.MessageEnd();
+	RSA::PrivateKey privateKey;
+	privateKey.Load(bytes);
+	RSAES_PKCS1v15_Decryptor decryptor(privateKey);
+	
+	OBufferStream os;
+	StringSource(data, dataLength, true, new PK_DecryptorFilter(rng, decryptor, new FileSink(os)));
+	
+	return os.buf();
+      }
+      catch(const CryptoPP::Exception& e){
+	throw Error(e.what());
+      }
+    }
+  else
+    {
+      throw Error("Symmetric encryption is not implemented!");
+      // if(!doesKeyExistInTpm(keyName, KEY_CLASS_SYMMETRIC))
+      // 	throw Error("symmetric key doesn't exist");
+
+      // try{
+      // 	string keyBits;
+      // 	string symKeyFileName = nameTransform(keyURI, ".key");
+      // 	FileSource(symKeyFileName, true, new HexDecoder(new StringSink(keyBits)));
+	
+      // 	using CryptoPP::AES;
+      // 	AutoSeededRandomPool rnd;
+      // 	byte iv[AES::BLOCKSIZE];
+      // 	rnd.GenerateBlock(iv, AES::BLOCKSIZE);
+
+      // 	CFB_Mode<AES>::Decryption decryptor;
+      // 	decryptor.SetKeyWithIV(reinterpret_cast<const uint8_t*>(keyBits.c_str()), keyBits.size(), iv);
+	
+      // 	OBufferStream os;
+      // 	StringSource(data, dataLength, true, new StreamTransformationFilter(decryptor,new FileSink(os)));
+      // 	return os.buf();
+
+      // }catch(const CryptoPP::Exception& e){
+      // 	throw Error(e.what());
+      // }
+    }
+}
+
+ConstBufferPtr
+SecTpmFile::encryptInTpm(const Name& keyName, const uint8_t* data, size_t dataLength, bool isSymmetric)
+{
+  string keyURI = keyName.toUri();
+
+  if (!isSymmetric)
+    {
+      if(!doesKeyExistInTpm(keyName, KEY_CLASS_PUBLIC))
+	throw Error("public key doesn't exist");
+      try
+	{
+	  AutoSeededRandomPool rng;
+
+	  //Read private key
+	  ByteQueue bytes;
+	  string publicKeyFileName = nameTransform(keyURI, ".pub");
+	  FileSource file(publicKeyFileName.c_str(), true, new Base64Decoder);
+	  file.TransferTo(bytes);
+	  bytes.MessageEnd();
+	  RSA::PublicKey publicKey;
+	  publicKey.Load(bytes);
+
+	  OBufferStream os;
+	  RSAES_PKCS1v15_Encryptor encryptor(publicKey);
+
+	  StringSource(data, dataLength, true, new PK_EncryptorFilter(rng, encryptor, new FileSink(os)));
+	  return os.buf();
+	}
+      catch(const CryptoPP::Exception& e){
+	throw Error(e.what());
+      }
+    }
+  else
+    {
+      throw Error("Symmetric encryption is not implemented!");
+      // if(!doesKeyExistInTpm(keyName, KEY_CLASS_SYMMETRIC))
+      // 	throw Error("symmetric key doesn't exist");
+
+      // try{
+      // 	string keyBits;
+      // 	string symKeyFileName = nameTransform(keyURI, ".key");
+      // 	FileSource(symKeyFileName, true, new HexDecoder(new StringSink(keyBits)));
+
+      // 	using CryptoPP::AES;
+      // 	AutoSeededRandomPool rnd;
+      // 	byte iv[AES::BLOCKSIZE];
+      // 	rnd.GenerateBlock(iv, AES::BLOCKSIZE);
+
+      // 	CFB_Mode<AES>::Encryption encryptor;
+      // 	encryptor.SetKeyWithIV(reinterpret_cast<const uint8_t*>(keyBits.c_str()), keyBits.size(), iv);
+
+      // 	OBufferStream os;
+      // 	StringSource(data, dataLength, true, new StreamTransformationFilter(encryptor, new FileSink(os)));
+      // 	return os.buf();
+      // }catch(const CryptoPP::Exception& e){
+      // 	throw Error(e.what());
+      // }
+    }
+}
+
+
+void
+SecTpmFile::generateSymmetricKeyInTpm(const Name & keyName, KeyType keyType, int keySize)
+{
+  string keyURI = keyName.toUri();
+
+  if(doesKeyExistInTpm(keyName, KEY_CLASS_SYMMETRIC))
+    throw Error("symmetric key exists");
+
+  string keyFileName = nameTransform(keyURI, "");
+  maintainMapping(keyURI, keyFileName);
+  string symKeyFileName = keyFileName + ".key";
+
+  try{
+    switch(keyType){
+    case KEY_TYPE_AES:
+      {
+	AutoSeededRandomPool rnd;
+	SecByteBlock key(0x00, keySize);
+	rnd.GenerateBlock(key, keySize );
+	
+	StringSource(key, key.size(), true, new HexEncoder(new FileSink(symKeyFileName.c_str())));
+	
+	chmod(symKeyFileName.c_str(), 0000400);
+	return;
+      }
+    default:
+      throw Error("Unsupported symmetric key type!");
+    }
+  }catch(const CryptoPP::Exception& e){
+    throw Error(e.what());
+  }
+}
+
+bool
+SecTpmFile::doesKeyExistInTpm(const Name & keyName, KeyClass keyClass)
+{
+  string keyURI = keyName.toUri();
+  if (keyClass == KEY_CLASS_PUBLIC)
+    {
+      string publicKeyName = SecTpmFile::nameTransform(keyURI, ".pub");
+      fstream fin(publicKeyName.c_str(),ios::in);
+      if (fin)
+        return true;
+      else
+        return false;
+    }
+  if (keyClass == KEY_CLASS_PRIVATE)
+    {
+      string privateKeyName = SecTpmFile::nameTransform(keyURI, ".pri");
+      fstream fin(privateKeyName.c_str(),ios::in);
+      if (fin)
+        return true;
+      else
+        return false;
+    }
+  if (keyClass == KEY_CLASS_SYMMETRIC)
+    {
+      string symmetricKeyName = SecTpmFile::nameTransform(keyURI, ".key");
+      fstream fin(symmetricKeyName.c_str(),ios::in);
+      if (fin)
+        return true;
+      else
+        return false;
+    }
+  return false;
+}
+
+std::string SecTpmFile::nameTransform(const string &keyName, const string &extension)
+{
+  std::string digest;
+  CryptoPP::SHA256 hash;
+  CryptoPP::StringSource foo(keyName, true,
+                             new CryptoPP::HashFilter(hash,
+                                                      new CryptoPP::Base64Encoder (new CryptoPP::StringSink(digest))
+                                                      )
+                             );
+  boost::algorithm::trim(digest);
+  for (std::string::iterator ch = digest.begin(); ch != digest.end(); ch++)
+    {
+      if (*ch == '/')
+        {
+          *ch = '%';
+        }
+    }
+
+  return (impl_->m_keystorePath / (digest + extension)).string();
+}
+
+void 
+SecTpmFile::maintainMapping(string str1, string str2)
+{
+  std::ofstream outfile;
+  string dirFile = (impl_->m_keystorePath / "mapping.txt").string();
+
+  outfile.open(dirFile.c_str(), std::ios_base::app);
+  outfile << str1 << ' ' << str2 << '\n';
+  outfile.close();
+}
+
+} //ndn