32 #include <boost/filesystem.hpp>
33 #include <boost/lexical_cast.hpp>
39 namespace fs = boost::filesystem;
46 Impl(
const std::string& dir)
49 m_keystorePath = fs::path(dir);
51 #ifdef NDN_CXX_HAVE_TESTS
52 else if (std::getenv(
"TEST_HOME") !=
nullptr) {
53 m_keystorePath = fs::path(std::getenv(
"TEST_HOME")) /
".ndn";
55 #endif // NDN_CXX_HAVE_TESTS
56 else if (std::getenv(
"HOME") !=
nullptr) {
57 m_keystorePath = fs::path(std::getenv(
"HOME")) /
".ndn";
60 m_keystorePath = fs::current_path() /
".ndn";
63 m_keystorePath /=
"ndnsec-key-file";
64 fs::create_directories(m_keystorePath);
70 std::ostringstream os;
78 return m_keystorePath / (os.str() +
".privkey");
82 fs::path m_keystorePath;
86 : m_impl(make_unique<
Impl>(location))
95 static std::string scheme =
"tpm-file";
100 BackEndFile::doHasKey(
const Name& keyName)
const
102 if (!fs::exists(m_impl->toFileName(keyName)))
109 catch (
const std::runtime_error&) {
114 unique_ptr<KeyHandle>
115 BackEndFile::doGetKeyHandle(
const Name& keyName)
const
117 if (!doHasKey(keyName))
120 return make_unique<KeyHandleMem>(loadKey(keyName));
123 unique_ptr<KeyHandle>
124 BackEndFile::doCreateKey(
const Name& identityName,
const KeyParams& params)
126 switch (params.getKeyType()) {
131 NDN_THROW(std::invalid_argument(
"File-based TPM does not support creating a key of type " +
132 boost::lexical_cast<std::string>(params.getKeyType())));
136 unique_ptr<KeyHandle> keyHandle = make_unique<KeyHandleMem>(key);
139 keyHandle->setKeyName(keyName);
142 saveKey(keyName, *key);
145 catch (
const std::runtime_error&) {
151 BackEndFile::doDeleteKey(
const Name& keyName)
153 auto keyPath = m_impl->toFileName(keyName);
154 if (!fs::exists(keyPath))
160 catch (
const fs::filesystem_error&) {
166 BackEndFile::doExportKey(
const Name& keyName,
const char* pw,
size_t pwLen)
168 unique_ptr<PrivateKey> key;
170 key = loadKey(keyName);
172 catch (
const PrivateKey::Error&) {
177 key->savePkcs8(os, pw, pwLen);
182 BackEndFile::doImportKey(
const Name& keyName,
const uint8_t*
buf,
size_t size,
const char* pw,
size_t pwLen)
186 key.loadPkcs8(
buf, size, pw, pwLen);
187 saveKey(keyName, key);
189 catch (
const PrivateKey::Error&) {
195 BackEndFile::doImportKey(
const Name& keyName, shared_ptr<transform::PrivateKey> key)
198 saveKey(keyName, *key);
200 catch (
const PrivateKey::Error&) {
205 unique_ptr<PrivateKey>
206 BackEndFile::loadKey(
const Name& keyName)
const
208 std::ifstream is(m_impl->toFileName(keyName).string());
209 auto key = make_unique<PrivateKey>();
210 key->loadPkcs1Base64(is);
215 BackEndFile::saveKey(
const Name& keyName,
const PrivateKey& key)
217 std::string fileName = m_impl->toFileName(keyName).string();
218 std::ofstream os(fileName);
219 key.savePkcs1Base64(os);
222 ::chmod(fileName.data(), 0000400);