src: Correcting coding style of security related code.
Change-Id: Iff09b16d8a86462aff0abbd202b82cebb74bc365
diff --git a/src/security/certificate-cache-ttl.cpp b/src/security/certificate-cache-ttl.cpp
index 0a9002e..7490471 100644
--- a/src/security/certificate-cache-ttl.cpp
+++ b/src/security/certificate-cache-ttl.cpp
@@ -6,44 +6,43 @@
*/
#include "common.hpp"
-
#include "certificate-cache-ttl.hpp"
-#include "../util/logging.hpp"
-
-INIT_LOGGER("ndn.CertificateCacheTtl");
-
using namespace std;
namespace ndn {
-CertificateCacheTtl::CertificateCacheTtl(shared_ptr<boost::asio::io_service> io, const time::seconds& defaultTtl)
+CertificateCacheTtl::CertificateCacheTtl(shared_ptr<boost::asio::io_service> io,
+ const time::seconds& defaultTtl)
: m_defaultTtl(defaultTtl)
, m_scheduler(*io)
-{}
+{
+}
CertificateCacheTtl::~CertificateCacheTtl()
-{}
-
-void
-CertificateCacheTtl::insertCertificate(ptr_lib::shared_ptr<const IdentityCertificate> certificate)
{
- time::milliseconds expire = (certificate->getFreshnessPeriod() >= time::seconds::zero() ?
- certificate->getFreshnessPeriod() : m_defaultTtl);
-
- Name trackerIndex = certificate->getName().getPrefix(-1);
- EventTracker::iterator it = m_tracker.find(trackerIndex);
- if(it != m_tracker.end())
- m_scheduler.cancelEvent(m_tracker[trackerIndex]);
-
- m_scheduler.scheduleEvent(time::seconds(0), bind(&CertificateCacheTtl::insert, this, certificate));
- m_tracker[trackerIndex] = m_scheduler.scheduleEvent(expire, bind(&CertificateCacheTtl::remove,
- this, certificate->getName()));
-
}
void
-CertificateCacheTtl::insert(ptr_lib::shared_ptr<const IdentityCertificate> certificate)
+CertificateCacheTtl::insertCertificate(shared_ptr<const IdentityCertificate> certificate)
+{
+ time::milliseconds expire = (certificate->getFreshnessPeriod() >= time::seconds::zero() ?
+ certificate->getFreshnessPeriod() : m_defaultTtl);
+
+ Name trackerIndex = certificate->getName().getPrefix(-1);
+ EventTracker::iterator it = m_tracker.find(trackerIndex);
+ if (it != m_tracker.end())
+ m_scheduler.cancelEvent(m_tracker[trackerIndex]);
+
+ m_scheduler.scheduleEvent(time::seconds(0),
+ bind(&CertificateCacheTtl::insert, this, certificate));
+ m_tracker[trackerIndex] = m_scheduler.scheduleEvent(expire,
+ bind(&CertificateCacheTtl::remove,
+ this, certificate->getName()));
+}
+
+void
+CertificateCacheTtl::insert(shared_ptr<const IdentityCertificate> certificate)
{
Name name = certificate->getName().getPrefix(-1);
m_cache[name] = certificate;
@@ -54,18 +53,18 @@
{
Name name = certificateName.getPrefix(-1);
Cache::iterator it = m_cache.find(name);
- if(it != m_cache.end())
+ if (it != m_cache.end())
m_cache.erase(it);
}
-ptr_lib::shared_ptr<const IdentityCertificate>
+shared_ptr<const IdentityCertificate>
CertificateCacheTtl::getCertificate(const Name& certificateName)
{
Cache::iterator it = m_cache.find(certificateName);
- if(it != m_cache.end())
+ if (it != m_cache.end())
return it->second;
else
- return ptr_lib::shared_ptr<IdentityCertificate>();
+ return shared_ptr<IdentityCertificate>();
}
} // namespace ndn
diff --git a/src/security/certificate-cache-ttl.hpp b/src/security/certificate-cache-ttl.hpp
index 4f65d17..e8725c1 100644
--- a/src/security/certificate-cache-ttl.hpp
+++ b/src/security/certificate-cache-ttl.hpp
@@ -11,33 +11,33 @@
#include "../common.hpp"
#include "certificate-cache.hpp"
#include "../util/scheduler.hpp"
-#include "../util/time.hpp"
namespace ndn {
class CertificateCacheTtl : public CertificateCache
{
public:
- CertificateCacheTtl(shared_ptr<boost::asio::io_service> io, const time::seconds& defaultTtl = time::seconds(3600));
+ CertificateCacheTtl(shared_ptr<boost::asio::io_service> io,
+ const time::seconds& defaultTtl = time::seconds(3600));
virtual
~CertificateCacheTtl();
virtual void
- insertCertificate(ptr_lib::shared_ptr<const IdentityCertificate> certificate);
+ insertCertificate(shared_ptr<const IdentityCertificate> certificate);
- virtual ptr_lib::shared_ptr<const IdentityCertificate>
+ virtual shared_ptr<const IdentityCertificate>
getCertificate(const Name& certificateNameWithoutVersion);
private:
void
- insert(ptr_lib::shared_ptr<const IdentityCertificate> certificate);
+ insert(shared_ptr<const IdentityCertificate> certificate);
void
remove(const Name& certificateName);
protected:
- typedef std::map<Name, ptr_lib::shared_ptr<const IdentityCertificate> > Cache;
+ typedef std::map<Name, shared_ptr<const IdentityCertificate> > Cache;
typedef std::map<Name, EventId> EventTracker;
time::seconds m_defaultTtl;
diff --git a/src/security/certificate-cache.hpp b/src/security/certificate-cache.hpp
index 9d99dcc..b49e121 100644
--- a/src/security/certificate-cache.hpp
+++ b/src/security/certificate-cache.hpp
@@ -17,12 +17,14 @@
{
public:
virtual
- ~CertificateCache() {}
-
- virtual void
- insertCertificate(ptr_lib::shared_ptr<const IdentityCertificate> certificate) = 0;
+ ~CertificateCache()
+ {
+ }
- virtual ptr_lib::shared_ptr<const IdentityCertificate>
+ virtual void
+ insertCertificate(shared_ptr<const IdentityCertificate> certificate) = 0;
+
+ virtual shared_ptr<const IdentityCertificate>
getCertificate(const Name& certificateNameWithoutVersion) = 0;
};
diff --git a/src/security/certificate-extension.cpp b/src/security/certificate-extension.cpp
index 3a23a80..87489ce 100644
--- a/src/security/certificate-extension.cpp
+++ b/src/security/certificate-extension.cpp
@@ -26,9 +26,9 @@
DERSequenceEncoder extension(out);
{
- extensionId_.encode(extension);
- DEREncodeUnsigned(extension, isCritical_, BOOLEAN);
- DEREncodeOctetString(extension, extensionValue_.buf(), extensionValue_.size());
+ m_extensionId.encode(extension);
+ DEREncodeUnsigned(extension, m_isCritical, BOOLEAN);
+ DEREncodeOctetString(extension, m_extensionValue.buf(), m_extensionValue.size());
}
extension.MessageEnd();
}
@@ -43,14 +43,14 @@
BERSequenceDecoder extension(in);
{
- extensionId_.decode(extension);
- BERDecodeUnsigned(extension, isCritical_, BOOLEAN);
+ m_extensionId.decode(extension);
+ BERDecodeUnsigned(extension, m_isCritical, BOOLEAN);
// the extra copy operation can be optimized, but not trivial,
// since the length is not known in advance
SecByteBlock tmpBlock;
BERDecodeOctetString(extension, tmpBlock);
- extensionValue_.assign(tmpBlock.begin(), tmpBlock.end());
+ m_extensionValue.assign(tmpBlock.begin(), tmpBlock.end());
}
extension.MessageEnd();
}
diff --git a/src/security/certificate-extension.hpp b/src/security/certificate-extension.hpp
index 1388107..a1aa5b6 100644
--- a/src/security/certificate-extension.hpp
+++ b/src/security/certificate-extension.hpp
@@ -45,12 +45,13 @@
* @param value The extension value.
*/
CertificateExtension(const OID& oid, const bool isCritical, const Buffer& value)
- : extensionId_(oid), isCritical_(isCritical), extensionValue_(value)
+ : m_extensionId(oid), m_isCritical(isCritical), m_extensionValue(value)
{
}
- CertificateExtension(const OID& oid, const bool isCritical, const uint8_t* value, size_t valueSize)
- : extensionId_(oid), isCritical_(isCritical), extensionValue_(value, valueSize)
+ CertificateExtension(const OID& oid, const bool isCritical,
+ const uint8_t* value, size_t valueSize)
+ : m_extensionId(oid), m_isCritical(isCritical), m_extensionValue(value, valueSize)
{
}
@@ -58,7 +59,9 @@
* The virtual destructor.
*/
virtual
- ~CertificateExtension() {}
+ ~CertificateExtension()
+ {
+ }
void
encode(CryptoPP::BufferedTransformation& out) const;
@@ -67,18 +70,27 @@
decode(CryptoPP::BufferedTransformation& in);
inline const OID&
- getOid() const { return extensionId_; }
+ getOid() const
+ {
+ return m_extensionId;
+ }
inline const bool
- getIsCritical() const { return isCritical_; }
+ getIsCritical() const
+ {
+ return m_isCritical;
+ }
inline const Buffer&
- getValue() const { return extensionValue_; }
+ getValue() const
+ {
+ return m_extensionValue;
+ }
protected:
- OID extensionId_;
- bool isCritical_;
- Buffer extensionValue_;
+ OID m_extensionId;
+ bool m_isCritical;
+ Buffer m_extensionValue;
};
} // namespace ndn
diff --git a/src/security/certificate-subject-description.cpp b/src/security/certificate-subject-description.cpp
index 44cd8c5..5c257d4 100644
--- a/src/security/certificate-subject-description.cpp
+++ b/src/security/certificate-subject-description.cpp
@@ -32,8 +32,8 @@
// AttributeValue ::= ANY DEFINED BY AttributeType
DERSequenceEncoder attributeTypeAndValue(out);
{
- oid_.encode(attributeTypeAndValue);
- DEREncodeTextString(attributeTypeAndValue, value_, PRINTABLE_STRING);
+ m_oid.encode(attributeTypeAndValue);
+ DEREncodeTextString(attributeTypeAndValue, m_value, PRINTABLE_STRING);
}
attributeTypeAndValue.MessageEnd();
}
@@ -54,11 +54,11 @@
BERSequenceDecoder attributeTypeAndValue(in);
{
- oid_.decode(attributeTypeAndValue);
+ m_oid.decode(attributeTypeAndValue);
/// @todo May be add more intelligent processing, since the following
/// may fail if somebody encoded attribute that uses non PRINTABLE_STRING as value
- BERDecodeTextString(attributeTypeAndValue, value_, PRINTABLE_STRING);
+ BERDecodeTextString(attributeTypeAndValue, m_value, PRINTABLE_STRING);
}
attributeTypeAndValue.MessageEnd();
}
diff --git a/src/security/certificate-subject-description.hpp b/src/security/certificate-subject-description.hpp
index 859aed3..7665a3f 100644
--- a/src/security/certificate-subject-description.hpp
+++ b/src/security/certificate-subject-description.hpp
@@ -32,7 +32,7 @@
* @param value The value of the subject description entry.
*/
CertificateSubjectDescription(const OID& oid, const std::string& value)
- : oid_(oid), value_(value)
+ : m_oid(oid), m_value(value)
{
}
@@ -45,18 +45,18 @@
std::string
getOidString() const
{
- return oid_.toString();
+ return m_oid.toString();
}
const std::string&
getValue() const
{
- return value_;
+ return m_value;
}
private:
- OID oid_;
- std::string value_;
+ OID m_oid;
+ std::string m_value;
};
} // namespace ndn
diff --git a/src/security/certificate.cpp b/src/security/certificate.cpp
index 3c4ed2d..9e12bfd 100644
--- a/src/security/certificate.cpp
+++ b/src/security/certificate.cpp
@@ -9,31 +9,24 @@
#include "common.hpp"
#include "certificate.hpp"
-
-#include "../util/logging.hpp"
#include "../util/time.hpp"
-
#include "cryptopp.hpp"
-
#include "../encoding/cryptopp/asn_ext.hpp"
-INIT_LOGGER("ndn.Certificate");
-
using namespace std;
namespace ndn {
Certificate::Certificate()
- : notBefore_(time::system_clock::TimePoint::max())
- , notAfter_(time::system_clock::TimePoint::min())
-{}
+ : m_notBefore(time::system_clock::TimePoint::max())
+ , m_notAfter(time::system_clock::TimePoint::min())
+{
+}
Certificate::Certificate(const Data& data)
-// Use the copy constructor. It clones the signature object.
-: Data(data)
+ // Use the copy constructor. It clones the signature object.
+ : Data(data)
{
- // _LOG_DEBUG("Finish local copy: " << getContent().getContent().size());
-
decode();
}
@@ -45,7 +38,7 @@
bool
Certificate::isTooEarly()
{
- if (time::system_clock::now() < notBefore_)
+ if (time::system_clock::now() < m_notBefore)
return true;
else
return false;
@@ -54,7 +47,7 @@
bool
Certificate::isTooLate()
{
- if (time::system_clock::now() > notAfter_)
+ if (time::system_clock::now() > m_notAfter)
return true;
else
return false;
@@ -115,8 +108,8 @@
// notAfter Time }
DERSequenceEncoder validity(idCert);
{
- DEREncodeGeneralTime(validity, notBefore_);
- DEREncodeGeneralTime(validity, notAfter_);
+ DEREncodeGeneralTime(validity, m_notBefore);
+ DEREncodeGeneralTime(validity, m_notAfter);
}
validity.MessageEnd();
@@ -126,8 +119,8 @@
// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
DERSequenceEncoder name(idCert);
{
- for(SubjectDescriptionList::iterator it = subjectDescriptionList_.begin();
- it != subjectDescriptionList_.end(); ++it)
+ for (SubjectDescriptionList::iterator it = m_subjectDescriptionList.begin();
+ it != m_subjectDescriptionList.end(); ++it)
{
it->encode(name);
}
@@ -135,7 +128,7 @@
name.MessageEnd();
// SubjectPublicKeyInfo
- key_.encode(idCert);
+ m_key.encode(idCert);
// Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
//
@@ -143,13 +136,12 @@
// extnID OBJECT IDENTIFIER,
// critical BOOLEAN DEFAULT FALSE,
// extnValue OCTET STRING }
- if (!extensionList_.empty())
+ if (!m_extensionList.empty())
{
DERSequenceEncoder extensions(idCert);
{
-
- for(ExtensionList::iterator it = extensionList_.begin();
- it != extensionList_.end(); ++it)
+ for (ExtensionList::iterator it = m_extensionList.begin();
+ it != m_extensionList.end(); ++it)
{
it->encode(extensions);
}
@@ -170,7 +162,7 @@
using namespace CryptoPP;
OBufferStream os;
- CryptoPP::StringSource source(getContent().value(), getContent().value_size(), true);
+ StringSource source(getContent().value(), getContent().value_size(), true);
// idCert ::= SEQUENCE {
// validity Validity,
@@ -184,8 +176,8 @@
// notAfter Time }
BERSequenceDecoder validity(idCert);
{
- BERDecodeTime(validity, notBefore_);
- BERDecodeTime(validity, notAfter_);
+ BERDecodeTime(validity, m_notBefore);
+ BERDecodeTime(validity, m_notAfter);
}
validity.MessageEnd();
@@ -193,12 +185,12 @@
// RDNSequence }
//
// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
- subjectDescriptionList_.clear();
+ m_subjectDescriptionList.clear();
BERSequenceDecoder name(idCert);
{
- while(!name.EndReached())
+ while (!name.EndReached())
{
- subjectDescriptionList_.push_back(CertificateSubjectDescription(name));
+ m_subjectDescriptionList.push_back(CertificateSubjectDescription(name));
}
}
name.MessageEnd();
@@ -206,7 +198,7 @@
// SubjectPublicKeyInfo ::= SEQUENCE {
// algorithm AlgorithmIdentifier
// keybits BIT STRING }
- key_.decode(idCert);
+ m_key.decode(idCert);
// Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
//
@@ -214,14 +206,14 @@
// extnID OBJECT IDENTIFIER,
// critical BOOLEAN DEFAULT FALSE,
// extnValue OCTET STRING }
- extensionList_.clear();
+ m_extensionList.clear();
if (!idCert.EndReached())
{
BERSequenceDecoder extensions(idCert);
{
- while(!extensions.EndReached())
+ while (!extensions.EndReached())
{
- extensionList_.push_back(CertificateExtension(extensions));
+ m_extensionList.push_back(CertificateExtension(extensions));
}
}
extensions.MessageEnd();
@@ -238,27 +230,20 @@
os << " " << getName() << endl;
os << "Validity:" << endl;
{
- os << " NotBefore: " << time::toIsoString(notBefore_) << endl;
- os << " NotAfter: " << time::toIsoString(notAfter_) << endl;
+ os << " NotBefore: " << time::toIsoString(m_notBefore) << endl;
+ os << " NotAfter: " << time::toIsoString(m_notAfter) << endl;
}
os << "Subject Description:" << endl;
- for(SubjectDescriptionList::const_iterator it = subjectDescriptionList_.begin();
- it != subjectDescriptionList_.end(); ++it)
+ for (SubjectDescriptionList::const_iterator it = m_subjectDescriptionList.begin();
+ it != m_subjectDescriptionList.end(); ++it)
{
os << " " << it->getOidString() << ": " << it->getValue() << endl;
}
os << "Public key bits:" << endl;
CryptoPP::Base64Encoder encoder(new CryptoPP::FileSink(os), true, 64);
- key_.encode(encoder);
-
- // ndnboost::iostreams::stream<ndnboost::iostreams::array_source> is((const char*)key_.getKeyDer().buf(), key_.getKeyDer().size());
-
- // ptr_lib::shared_ptr<der::DerNode> keyRoot = der::DerNode::parse(reinterpret_cast<der::InputIterator&> (is));
-
- // der::PrintVisitor printVisitor;
- // keyRoot->accept(printVisitor, string(""));
+ m_key.encode(encoder);
}
} // namespace ndn
diff --git a/src/security/certificate.hpp b/src/security/certificate.hpp
index 3470134..dc96879 100644
--- a/src/security/certificate.hpp
+++ b/src/security/certificate.hpp
@@ -11,7 +11,6 @@
#include "../common.hpp"
#include "../data.hpp"
-
#include "certificate-subject-description.hpp"
#include "certificate-extension.hpp"
#include "public-key.hpp"
@@ -64,53 +63,98 @@
* @param description The description to be added.
*/
void
- addSubjectDescription(const CertificateSubjectDescription& description) { subjectDescriptionList_.push_back(description); }
+ addSubjectDescription(const CertificateSubjectDescription& description)
+ {
+ m_subjectDescriptionList.push_back(description);
+ }
const SubjectDescriptionList&
- getSubjectDescriptionList() const { return subjectDescriptionList_; }
+ getSubjectDescriptionList() const
+ {
+ return m_subjectDescriptionList;
+ }
SubjectDescriptionList&
- getSubjectDescriptionList() { return subjectDescriptionList_; }
+ getSubjectDescriptionList()
+ {
+ return m_subjectDescriptionList;
+ }
/**
* Add a certificate extension.
* @param extension the extension to be added
*/
void
- addExtension(const CertificateExtension& extension) { extensionList_.push_back(extension); }
+ addExtension(const CertificateExtension& extension)
+ {
+ m_extensionList.push_back(extension);
+ }
const ExtensionList&
- getExtensionList() const { return extensionList_; }
+ getExtensionList() const
+ {
+ return m_extensionList;
+ }
ExtensionList&
- getExtensionList() { return extensionList_; }
+ getExtensionList()
+ {
+ return m_extensionList;
+ }
void
- setNotBefore(const time::system_clock::TimePoint& notBefore) { notBefore_ = notBefore; }
+ setNotBefore(const time::system_clock::TimePoint& notBefore)
+ {
+ m_notBefore = notBefore;
+ }
time::system_clock::TimePoint&
- getNotBefore() { return notBefore_; }
+ getNotBefore()
+ {
+ return m_notBefore;
+ }
const time::system_clock::TimePoint&
- getNotBefore() const { return notBefore_; }
+ getNotBefore() const
+ {
+ return m_notBefore;
+ }
void
- setNotAfter(const time::system_clock::TimePoint& notAfter) { notAfter_ = notAfter; }
+ setNotAfter(const time::system_clock::TimePoint& notAfter)
+ {
+ m_notAfter = notAfter;
+ }
time::system_clock::TimePoint&
- getNotAfter() { return notAfter_; }
+ getNotAfter()
+ {
+ return m_notAfter;
+ }
const time::system_clock::TimePoint&
- getNotAfter() const { return notAfter_; }
+ getNotAfter() const
+ {
+ return m_notAfter;
+ }
void
- setPublicKeyInfo(const PublicKey& key) { key_ = key; }
+ setPublicKeyInfo(const PublicKey& key)
+ {
+ m_key = key;
+ }
PublicKey&
- getPublicKeyInfo() { return key_; }
+ getPublicKeyInfo()
+ {
+ return m_key;
+ }
const PublicKey&
- getPublicKeyInfo() const { return key_; }
+ getPublicKeyInfo() const
+ {
+ return m_key;
+ }
// virtual Name
// getPublicKeyName() const = 0;
@@ -137,11 +181,11 @@
decode();
protected:
- SubjectDescriptionList subjectDescriptionList_;
- time::system_clock::TimePoint notBefore_;
- time::system_clock::TimePoint notAfter_;
- PublicKey key_;
- ExtensionList extensionList_;
+ SubjectDescriptionList m_subjectDescriptionList;
+ time::system_clock::TimePoint m_notBefore;
+ time::system_clock::TimePoint m_notAfter;
+ PublicKey m_key;
+ ExtensionList m_extensionList;
};
inline void
@@ -153,7 +197,7 @@
inline std::ostream&
-operator <<(std::ostream& os, const Certificate& cert)
+operator<<(std::ostream& os, const Certificate& cert)
{
cert.printCertificate(os);
return os;
diff --git a/src/security/encryption-manager.hpp b/src/security/encryption-manager.hpp
index 44eafb7..a6f319b 100644
--- a/src/security/encryption-manager.hpp
+++ b/src/security/encryption-manager.hpp
@@ -5,8 +5,8 @@
* See COPYING for copyright and distribution information.
*/
-#ifndef NDN_ENCRYPTION_MANAGER_HPP
-#define NDN_ENCRYPTION_MANAGER_HPP
+#ifndef NDN_SECURITY_ENCRYPTION_MANAGER_HPP
+#define NDN_SECURITY_ENCRYPTION_MANAGER_HPP
#include "../../name.hpp"
#include "../security-common.hpp"
@@ -15,20 +15,23 @@
class EncryptionManager {
public:
- virtual ~EncryptionManager() {}
-
- virtual void
- createSymmetricKey(const Name& keyName, KeyType keyType, const Name& signkeyName = Name(), bool isSymmetric = true) = 0;
+ virtual ~EncryptionManager()
+ {
+ }
+
+ virtual void
+ createSymmetricKey(const Name& keyName, KeyType keyType,
+ const Name& signkeyName = Name(), bool isSymmetric = true) = 0;
virtual ConstBufferPtr
- encrypt(const Name& keyName, const uint8_t* data, size_t dataLength, bool useSymmetric = false,
+ encrypt(const Name& keyName, const uint8_t* data, size_t dataLength, bool useSymmetric = false,
EncryptMode encryptMode = ENCRYPT_MODE_DEFAULT) = 0;
virtual ConstBufferPtr
- decrypt(const Name& keyName, const uint8_t* data, size_t dataLength, bool useSymmetric = false,
+ decrypt(const Name& keyName, const uint8_t* data, size_t dataLength, bool useSymmetric = false,
EncryptMode encryptMode = ENCRYPT_MODE_DEFAULT) = 0;
};
-}
+} // namespace ndn
-#endif
+#endif // NDN_SECURITY_ENCRYPTION_MANAGER_HPP
diff --git a/src/security/identity-certificate.cpp b/src/security/identity-certificate.cpp
index 75693b0..5cb570a 100644
--- a/src/security/identity-certificate.cpp
+++ b/src/security/identity-certificate.cpp
@@ -46,7 +46,7 @@
if (!isCorrectName(getName()))
throw Error("Wrong Identity Certificate Name!");
- publicKeyName_ = certificateNameToPublicKeyName(getName());
+ m_publicKeyName = certificateNameToPublicKeyName(getName());
}
bool
diff --git a/src/security/identity-certificate.hpp b/src/security/identity-certificate.hpp
index 01427d4..7c3915b 100644
--- a/src/security/identity-certificate.hpp
+++ b/src/security/identity-certificate.hpp
@@ -33,8 +33,6 @@
inline
IdentityCertificate();
- // Note: The copy constructor works because publicKeyName_ has a copy constructor.
-
/**
* Create an IdentityCertificate from the content in the data packet.
* @param data The data packet with the content to decode.
@@ -55,7 +53,7 @@
setName(const Name& name);
inline const Name&
- getPublicKeyName () const;
+ getPublicKeyName() const;
static bool
isIdentityCertificate(const Certificate& certificate);
@@ -76,7 +74,7 @@
setPublicKeyName();
protected:
- Name publicKeyName_;
+ Name m_publicKeyName;
};
inline
@@ -111,9 +109,9 @@
}
inline const Name&
-IdentityCertificate::getPublicKeyName () const
+IdentityCertificate::getPublicKeyName() const
{
- return publicKeyName_;
+ return m_publicKeyName;
}
} // namespace ndn
diff --git a/src/security/key-chain.hpp b/src/security/key-chain.hpp
index 70593a9..1a76d1a 100644
--- a/src/security/key-chain.hpp
+++ b/src/security/key-chain.hpp
@@ -35,7 +35,8 @@
/**
* @brief KeyChain is one of the main classes of the security library.
*
- * The KeyChain class provides a set of interfaces of identity management and private key related operations.
+ * The KeyChain class provides a set of interfaces of identity management and private key related
+ * operations.
*/
template<class Info, class Tpm>
class KeyChainImpl : public Info, public Tpm
@@ -44,7 +45,8 @@
typedef SecTpm::Error TpmError;
public:
/**
- * @brief Create an identity by creating a pair of Key-Signing-Key (KSK) for this identity and a self-signed certificate of the KSK.
+ * @brief Create an identity by creating a pair of Key-Signing-Key (KSK) for this identity and a
+ * self-signed certificate of the KSK.
*
* @param identityName The name of the identity.
* @return The name of the default certificate of the identity.
@@ -94,7 +96,8 @@
}
/**
- * @brief Generate a pair of RSA keys for the specified identity and set it as default key for the identity.
+ * @brief Generate a pair of RSA keys for the specified identity and set it as default key for
+ * the identity.
*
* @param identityName The name of the identity.
* @param isKsk true for generating a Key-Signing-Key (KSK), false for a Data-Signing-Key (KSK).
@@ -141,11 +144,19 @@
if (signingIdentity.isPrefixOf(keyName))
{
- certName.append(signingIdentity).append("KEY").append(keyName.getSubName(signingIdentity.size())).append("ID-CERT").appendVersion();
+ certName.append(signingIdentity)
+ .append("KEY")
+ .append(keyName.getSubName(signingIdentity.size()))
+ .append("ID-CERT")
+ .appendVersion();
}
else
{
- certName.append(keyName.getPrefix(-1)).append("KEY").append(keyName.get(-1)).append("ID-CERT").appendVersion();
+ certName.append(keyName.getPrefix(-1))
+ .append("KEY")
+ .append(keyName.get(-1))
+ .append("ID-CERT")
+ .appendVersion();
}
certificate->setName(certName);
@@ -170,8 +181,10 @@
}
else
{
- std::vector<CertificateSubjectDescription>::const_iterator sdIt = subjectDescription.begin();
- std::vector<CertificateSubjectDescription>::const_iterator sdEnd = subjectDescription.end();
+ std::vector<CertificateSubjectDescription>::const_iterator sdIt =
+ subjectDescription.begin();
+ std::vector<CertificateSubjectDescription>::const_iterator sdEnd =
+ subjectDescription.end();
for(; sdIt != sdEnd; sdIt++)
certificate->addSubjectDescription(*sdIt);
}
@@ -235,7 +248,8 @@
throw InfoError("Requested certificate [" + certificateName.toUri() + "] doesn't exist");
SignatureSha256WithRsa signature;
- signature.setKeyLocator(certificateName.getPrefix(-1)); // implicit conversion should take care
+ // implicit conversion should take care
+ signature.setKeyLocator(certificateName.getPrefix(-1));
// For temporary usage, we support RSA + SHA256 only, but will support more.
signPacketWrapper(packet, signature,
@@ -258,20 +272,22 @@
if (!Info::doesCertificateExist(certificateName))
throw InfoError("Requested certificate [" + certificateName.toUri() + "] doesn't exist");
+ Name keyName = IdentityCertificate::certificateNameToPublicKeyName(certificateName);
+
SignatureSha256WithRsa signature;
- signature.setKeyLocator(certificateName.getPrefix(-1)); // implicit conversion should take care
+ // implicit conversion should take care
+ signature.setKeyLocator(certificateName.getPrefix(-1));
// For temporary usage, we support RSA + SHA256 only, but will support more.
- signature.setValue(Tpm::signInTpm(buffer, bufferLength,
- IdentityCertificate::certificateNameToPublicKeyName(certificateName),
- DIGEST_ALGORITHM_SHA256));
+ signature.setValue(Tpm::signInTpm(buffer, bufferLength, keyName, DIGEST_ALGORITHM_SHA256));
return signature;
}
/**
* @brief Sign packet using the default certificate of a particular identity.
*
- * If there is no default certificate of that identity, this method will create a self-signed certificate.
+ * If there is no default certificate of that identity, this method will create a self-signed
+ * certificate.
*
* @param packet The packet to be signed.
* @param identityName The signing identity name.
@@ -288,10 +304,12 @@
catch (InfoError& e)
{
signingCertificateName = createIdentity(identityName);
- // Ideally, no exception will be thrown out, unless something goes wrong in the TPM, which is a fatal error.
+ // Ideally, no exception will be thrown out, unless something goes wrong in the TPM, which
+ // is a fatal error.
}
- // We either get or create the signing certificate, sign packet! (no exception unless fatal error in TPM)
+ // We either get or create the signing certificate, sign packet! (no exception unless fatal
+ // error in TPM)
sign(packet, signingCertificateName);
}
@@ -314,10 +332,12 @@
catch (InfoError& e)
{
signingCertificateName = createIdentity(identityName);
- // Ideally, no exception will be thrown out, unless something goes wrong in the TPM, which is a fatal error.
+ // Ideally, no exception will be thrown out, unless something goes wrong in the TPM, which
+ // is a fatal error.
}
- // We either get or create the signing certificate, sign data! (no exception unless fatal error in TPM)
+ // We either get or create the signing certificate, sign data! (no exception unless fatal error
+ // in TPM)
return sign(buffer, bufferLength, signingCertificateName);
}
@@ -334,9 +354,9 @@
Block sigValue(Tlv::SignatureValue,
crypto::sha256(data.wireEncode().value(),
- data.wireEncode().value_size() - data.getSignature().getValue().size()));
+ data.wireEncode().value_size() -
+ data.getSignature().getValue().size()));
data.setSignatureValue(sigValue);
-
}
/**
@@ -512,7 +532,8 @@
Info::addCertificateAsIdentityDefault(*cert);
}
- shared_ptr<SecuredBag> secureBag = make_shared<SecuredBag>(boost::cref(*cert), boost::cref(pkcs8));
+ shared_ptr<SecuredBag> secureBag = make_shared<SecuredBag>(boost::cref(*cert),
+ boost::cref(pkcs8));
return secureBag;
}
@@ -526,16 +547,22 @@
void
importIdentity(const SecuredBag& securedBag, const std::string& passwordStr)
{
- Name keyName = IdentityCertificate::certificateNameToPublicKeyName(securedBag.getCertificate().getName());
+ Name certificateName = securedBag.getCertificate().getName();
+ Name keyName = IdentityCertificate::certificateNameToPublicKeyName(certificateName);
Name identity = keyName.getPrefix(-1);
// Add identity
Info::addIdentity(identity);
// Add key
- Tpm::importPrivateKeyPkcs8IntoTpm(keyName, securedBag.getKey()->buf(), securedBag.getKey()->size(), passwordStr);
+ Tpm::importPrivateKeyPkcs8IntoTpm(keyName,
+ securedBag.getKey()->buf(),
+ securedBag.getKey()->size(),
+ passwordStr);
+
shared_ptr<PublicKey> pubKey = Tpm::getPublicKeyFromTpm(keyName.toUri());
- Info::addPublicKey(keyName, KEY_TYPE_RSA, *pubKey); // HACK! We should set key type according to the pkcs8 info.
+ // HACK! We should set key type according to the pkcs8 info.
+ Info::addPublicKey(keyName, KEY_TYPE_RSA, *pubKey);
Info::setDefaultKeyNameForIdentity(keyName);
// Add cert
@@ -571,7 +598,8 @@
* @return The name of the generated key.
*/
Name
- generateKeyPair(const Name& identityName, bool isKsk = false, KeyType keyType = KEY_TYPE_RSA, int keySize = 2048)
+ generateKeyPair(const Name& identityName, bool isKsk = false,
+ KeyType keyType = KEY_TYPE_RSA, int keySize = 2048)
{
Name keyName = Info::getNewKeyName(identityName, isKsk);
@@ -593,13 +621,14 @@
* @throws Tpm::Error
*/
void
- signPacketWrapper(Data& data, const SignatureSha256WithRsa& signature, const Name& keyName, DigestAlgorithm digestAlgorithm)
+ signPacketWrapper(Data& data, const SignatureSha256WithRsa& signature,
+ const Name& keyName, DigestAlgorithm digestAlgorithm)
{
data.setSignature(signature);
- data.setSignatureValue
- (Tpm::signInTpm(data.wireEncode().value(),
- data.wireEncode().value_size() - data.getSignature().getValue().size(),
- keyName, digestAlgorithm));
+ data.setSignatureValue(Tpm::signInTpm(data.wireEncode().value(),
+ data.wireEncode().value_size() -
+ data.getSignature().getValue().size(),
+ keyName, digestAlgorithm));
}
/**
@@ -612,9 +641,11 @@
* @throws Tpm::Error
*/
void
- signPacketWrapper(Interest& interest, const SignatureSha256WithRsa& signature, const Name& keyName, DigestAlgorithm digestAlgorithm)
+ signPacketWrapper(Interest& interest, const SignatureSha256WithRsa& signature,
+ const Name& keyName, DigestAlgorithm digestAlgorithm)
{
- Name signedName = Name(interest.getName()).append(signature.getInfo());
+ Name signedName = interest.getName();
+ signedName.append(signature.getInfo());
Block sigValue = Tpm::signInTpm(signedName.wireEncode().value(),
signedName.wireEncode().value_size(),
@@ -625,7 +656,6 @@
interest.setName(signedName);
}
-
};
} // namespace ndn
diff --git a/src/security/public-key.cpp b/src/security/public-key.cpp
index b9b7cf3..67b57bb 100644
--- a/src/security/public-key.cpp
+++ b/src/security/public-key.cpp
@@ -7,9 +7,7 @@
*/
#include "common.hpp"
-
#include "public-key.hpp"
-
#include "cryptopp.hpp"
using namespace std;
@@ -41,7 +39,7 @@
// algorithm AlgorithmIdentifier
// keybits BIT STRING }
- out.Put(key_.buf(), key_.size());
+ out.Put(m_key.buf(), m_key.size());
}
void
@@ -51,44 +49,47 @@
// algorithm AlgorithmIdentifier
// keybits BIT STRING }
- try {
- std::string out;
- StringSink sink(out);
-
- ////////////////////////
- // part 1: copy as is //
- ////////////////////////
- BERSequenceDecoder decoder(in);
+ try
{
- assert (decoder.IsDefiniteLength());
+ std::string out;
+ StringSink sink(out);
- DERSequenceEncoder encoder(sink);
- decoder.TransferTo(encoder, decoder.RemainingLength());
- encoder.MessageEnd();
- }
- decoder.MessageEnd();
-
- ////////////////////////
- // part 2: check if the key is RSA (since it is the only supported for now)
- ////////////////////////
- StringSource checkedSource(out, true);
- BERSequenceDecoder subjectPublicKeyInfo(checkedSource);
- {
- BERSequenceDecoder algorithmInfo(subjectPublicKeyInfo);
+ ////////////////////////
+ // part 1: copy as is //
+ ////////////////////////
+ BERSequenceDecoder decoder(in);
{
- OID algorithm;
- algorithm.decode(algorithmInfo);
+ assert(decoder.IsDefiniteLength());
- if (algorithm != RSA_OID)
- throw Error("Only RSA public keys are supported for now (" + algorithm.toString() + " requested");
+ DERSequenceEncoder encoder(sink);
+ decoder.TransferTo(encoder, decoder.RemainingLength());
+ encoder.MessageEnd();
}
- }
+ decoder.MessageEnd();
- key_.assign(out.begin(), out.end());
- }
- catch (CryptoPP::BERDecodeErr& err) {
- throw Error("PublicKey decoding error");
- }
+ ////////////////////////
+ // part 2: check if the key is RSA (since it is the only supported for now)
+ ////////////////////////
+ StringSource checkedSource(out, true);
+ BERSequenceDecoder subjectPublicKeyInfo(checkedSource);
+ {
+ BERSequenceDecoder algorithmInfo(subjectPublicKeyInfo);
+ {
+ OID algorithm;
+ algorithm.decode(algorithmInfo);
+
+ if (algorithm != RSA_OID)
+ throw Error("Only RSA public keys are supported for now (" +
+ algorithm.toString() + " requested)");
+ }
+ }
+
+ m_key.assign(out.begin(), out.end());
+ }
+ catch (CryptoPP::BERDecodeErr& err)
+ {
+ throw Error("PublicKey decoding error");
+ }
}
// Blob
@@ -105,7 +106,7 @@
// }
std::ostream&
-operator <<(std::ostream& os, const PublicKey& key)
+operator<<(std::ostream& os, const PublicKey& key)
{
CryptoPP::StringSource(key.get().buf(), key.get().size(), true,
new CryptoPP::Base64Encoder(new CryptoPP::FileSink(os), true, 64));
diff --git a/src/security/public-key.hpp b/src/security/public-key.hpp
index 8d6b7c5..7774755 100644
--- a/src/security/public-key.hpp
+++ b/src/security/public-key.hpp
@@ -10,7 +10,6 @@
#define NDN_SECURITY_PUBLIC_KEY_HPP
#include "../common.hpp"
-
#include "../encoding/oid.hpp"
#include "../encoding/buffer.hpp"
#include "security-common.hpp"
@@ -41,19 +40,19 @@
*
* @throws PublicKey::Error If algorithm is not supported or keyDer cannot be decoded
*/
- PublicKey(const uint8_t *keyDerBuf, size_t keyDerSize);
+ PublicKey(const uint8_t* keyDerBuf, size_t keyDerSize);
inline const Buffer&
get() const
{
- return key_;
+ return m_key;
}
inline void
- set(const uint8_t *keyDerBuf, size_t keyDerSize)
+ set(const uint8_t* keyDerBuf, size_t keyDerSize)
{
Buffer buf(keyDerBuf, keyDerSize);
- key_.swap(buf);
+ m_key.swap(buf);
}
void
@@ -62,31 +61,24 @@
void
decode(CryptoPP::BufferedTransformation& in);
- // /*
- // * Get the digest of the public key.
- // * @param digestAlgorithm The digest algorithm. If omitted, use DIGEST_ALGORITHM_SHA256 by default.
- // */
- // Blob
- // getDigest(DigestAlgorithm digestAlgorithm = DIGEST_ALGORITHM_SHA256) const;
-
inline bool
- operator ==(const PublicKey& key) const
+ operator==(const PublicKey& key) const
{
- return key_ == key.key_;
+ return m_key == key.m_key;
}
inline bool
- operator !=(const PublicKey& key) const
+ operator!=(const PublicKey& key) const
{
- return key_ != key.key_;
+ return m_key != key.m_key;
}
private:
- Buffer key_;
+ Buffer m_key;
};
std::ostream&
-operator <<(std::ostream& os, const PublicKey& key);
+operator<<(std::ostream& os, const PublicKey& key);
} // namespace ndn
diff --git a/src/security/sec-public-info-memory.cpp b/src/security/sec-public-info-memory.cpp
index f2a35ee..c01e59b 100644
--- a/src/security/sec-public-info-memory.cpp
+++ b/src/security/sec-public-info-memory.cpp
@@ -22,57 +22,55 @@
SecPublicInfoMemory::doesIdentityExist(const Name& identityName)
{
string identityUri = identityName.toUri();
- return find(identityStore_.begin(), identityStore_.end(), identityUri) != identityStore_.end();
+ return find(m_identityStore.begin(), m_identityStore.end(), identityUri) != m_identityStore.end();
}
void
SecPublicInfoMemory::addIdentity(const Name& identityName)
{
string identityUri = identityName.toUri();
- if (find(identityStore_.begin(), identityStore_.end(), identityUri) != identityStore_.end())
+ if (find(m_identityStore.begin(), m_identityStore.end(), identityUri) != m_identityStore.end())
return;
- identityStore_.push_back(identityUri);
+ m_identityStore.push_back(identityUri);
}
bool
SecPublicInfoMemory::revokeIdentity()
{
-#if 1
throw Error("SecPublicInfoMemory::revokeIdentity not implemented");
-#endif
}
bool
SecPublicInfoMemory::doesPublicKeyExist(const Name& keyName)
{
- return keyStore_.find(keyName.toUri()) != keyStore_.end();
+ return m_keyStore.find(keyName.toUri()) != m_keyStore.end();
}
void
SecPublicInfoMemory::addPublicKey(const Name& keyName, KeyType keyType, const PublicKey& publicKey)
{
- Name identityName = keyName.getSubName(0, keyName.size() - 1);
+ Name identityName = keyName.getPrefix(-1);
addIdentity(identityName);
- keyStore_[keyName.toUri()] = make_shared<KeyRecord>(keyType, publicKey);
+ m_keyStore[keyName.toUri()] = make_shared<KeyRecord>(keyType, boost::cref(publicKey));
}
shared_ptr<PublicKey>
SecPublicInfoMemory::getPublicKey(const Name& keyName)
{
- KeyStore::iterator record = keyStore_.find(keyName.toUri());
- if (record == keyStore_.end())
+ KeyStore::iterator record = m_keyStore.find(keyName.toUri());
+ if (record == m_keyStore.end())
throw Error("SecPublicInfoMemory::getPublicKey " + keyName.toUri());
- return make_shared<PublicKey> (record->second->getKey());
+ return make_shared<PublicKey>(record->second->getKey());
}
bool
SecPublicInfoMemory::doesCertificateExist(const Name& certificateName)
{
- return certificateStore_.find(certificateName.toUri()) != certificateStore_.end();
+ return m_certificateStore.find(certificateName.toUri()) != m_certificateStore.end();
}
void
@@ -84,14 +82,14 @@
addIdentity(identity);
addPublicKey(keyName, KEY_TYPE_RSA, certificate.getPublicKeyInfo());
- certificateStore_[certificateName.toUri()] = make_shared<IdentityCertificate> (certificate);
+ m_certificateStore[certificateName.toUri()] = make_shared<IdentityCertificate>(certificate);
}
shared_ptr<IdentityCertificate>
SecPublicInfoMemory::getCertificate(const Name& certificateName)
{
- CertificateStore::iterator record = certificateStore_.find(certificateName.toUri());
- if (record == certificateStore_.end())
+ CertificateStore::iterator record = m_certificateStore.find(certificateName.toUri());
+ if (record == m_certificateStore.end())
throw Error("SecPublicInfoMemory::getCertificate " + certificateName.toUri());
return record->second;
@@ -100,45 +98,44 @@
Name
SecPublicInfoMemory::getDefaultIdentity()
{
- return Name(defaultIdentity_);
+ return Name(m_defaultIdentity);
}
void
SecPublicInfoMemory::setDefaultIdentityInternal(const Name& identityName)
{
string identityUri = identityName.toUri();
- if (find(identityStore_.begin(), identityStore_.end(), identityUri) != identityStore_.end())
- defaultIdentity_ = identityUri;
+ if (find(m_identityStore.begin(), m_identityStore.end(), identityUri) != m_identityStore.end())
+ m_defaultIdentity = identityUri;
else
// The identity doesn't exist, so clear the default.
- defaultIdentity_.clear();
+ m_defaultIdentity.clear();
}
Name
SecPublicInfoMemory::getDefaultKeyNameForIdentity(const Name& identityName)
{
- return defaultKeyName_;
+ return m_defaultKeyName;
}
void
SecPublicInfoMemory::setDefaultKeyNameForIdentityInternal(const Name& keyName)
{
- defaultKeyName_ = keyName;
+ m_defaultKeyName = keyName;
}
Name
SecPublicInfoMemory::getDefaultCertificateNameForKey(const Name& keyName)
{
- return defaultCert_;
+ return m_defaultCert;
}
void
SecPublicInfoMemory::setDefaultCertificateNameForKeyInternal(const Name& certificateName)
{
- defaultCert_ = certificateName;
+ m_defaultCert = certificateName;
}
-
void
SecPublicInfoMemory::getAllIdentities(std::vector<Name>& nameList, bool isDefault)
{
@@ -152,7 +149,9 @@
}
void
-SecPublicInfoMemory::getAllKeyNamesOfIdentity(const Name& identity, std::vector<Name>& nameList, bool isDefault)
+SecPublicInfoMemory::getAllKeyNamesOfIdentity(const Name& identity,
+ std::vector<Name>& nameList,
+ bool isDefault)
{
throw Error("SecPublicInfoMemory::getAllKeyNamesOfIdentity not implemented");
}
@@ -164,7 +163,9 @@
}
void
-SecPublicInfoMemory::getAllCertificateNamesOfKey(const Name& keyName, std::vector<Name>& nameList, bool isDefault)
+SecPublicInfoMemory::getAllCertificateNamesOfKey(const Name& keyName,
+ std::vector<Name>& nameList,
+ bool isDefault)
{
throw Error("SecPublicInfoMemory::getAllCertificateNamesOfKey not implemented");
}
diff --git a/src/security/sec-public-info-memory.hpp b/src/security/sec-public-info-memory.hpp
index 58d8529..2ecdc43 100644
--- a/src/security/sec-public-info-memory.hpp
+++ b/src/security/sec-public-info-memory.hpp
@@ -14,7 +14,8 @@
namespace ndn {
/**
- * @brief SecPublicInfoMemory extends SecPublicInfo and implements its methods to store identity, public key and certificate objects in memory.
+ * @brief SecPublicInfoMemory extends SecPublicInfo and implements its methods to store identity,
+ * public key and certificate objects in memory.
*/
class SecPublicInfoMemory : public SecPublicInfo {
public:
@@ -46,7 +47,7 @@
virtual void
addPublicKey(const Name& keyName, KeyType keyType, const PublicKey& publicKeyDer);
- virtual ptr_lib::shared_ptr<PublicKey>
+ virtual shared_ptr<PublicKey>
getPublicKey(const Name& keyName);
virtual bool
@@ -55,10 +56,9 @@
virtual void
addCertificate(const IdentityCertificate& certificate);
- virtual ptr_lib::shared_ptr<IdentityCertificate>
+ virtual shared_ptr<IdentityCertificate>
getCertificate(const Name& certificateName);
-
virtual Name
getDefaultIdentity();
@@ -107,29 +107,40 @@
class KeyRecord {
public:
KeyRecord(KeyType keyType, const PublicKey& key)
- : keyType_(keyType), key_(key)
+ : m_keyType(keyType), m_key(key)
{
}
- const KeyType getKeyType() const { return keyType_; }
+ const KeyType
+ getKeyType() const
+ {
+ return m_keyType;
+ }
- const PublicKey& getKey() { return key_; }
+ const PublicKey&
+ getKey()
+ {
+ return m_key;
+ }
private:
- KeyType keyType_;
- PublicKey key_;
+ KeyType m_keyType;
+ PublicKey m_key;
};
- std::vector<std::string> identityStore_; /**< A list of name URI. */
- std::string defaultIdentity_; /**< The default identity in identityStore_, or "" if not defined. */
- Name defaultKeyName_;
- Name defaultCert_;
+ std::vector<std::string> m_identityStore; // A list of name URI.
+ std::string m_defaultIdentity; // The default identity in m_identityStore, or "" if not defined.
+ Name m_defaultKeyName;
+ Name m_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() */
+ // The map key is the keyName.toUri()
+ typedef std::map<std::string, shared_ptr<KeyRecord> > KeyStore;
- KeyStore keyStore_;
- CertificateStore certificateStore_;
+ // The map key is the certificateName.toUri()
+ typedef std::map<std::string, shared_ptr<IdentityCertificate> > CertificateStore;
+
+ KeyStore m_keyStore;
+ CertificateStore m_certificateStore;
};
} // namespace ndn
diff --git a/src/security/sec-public-info-sqlite3.cpp b/src/security/sec-public-info-sqlite3.cpp
index 8d7ccb2..4df238c 100644
--- a/src/security/sec-public-info-sqlite3.cpp
+++ b/src/security/sec-public-info-sqlite3.cpp
@@ -11,10 +11,6 @@
#include "sec-public-info-sqlite3.hpp"
#include "identity-certificate.hpp"
#include "signature-sha256-with-rsa.hpp"
-
-#include "../util/logging.hpp"
-#include "../util/time.hpp"
-
#include "../data.hpp"
#include <sqlite3.h>
@@ -24,10 +20,6 @@
#include <fstream>
#include <boost/filesystem.hpp>
-
-
-INIT_LOGGER("ndn.SecPublicInfoSqlite3");
-
using namespace std;
namespace ndn {
@@ -81,9 +73,13 @@
";
/**
- * A utility function to call the normal sqlite3_bind_text where the value and length are value.c_str() and value.size().
+ * 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*))
+static int sqlite3_bind_text(sqlite3_stmt* statement,
+ int index,
+ const string& value,
+ void(*destructor)(void*))
{
return sqlite3_bind_text(statement, index, value.c_str(), value.size(), destructor);
}
@@ -107,7 +103,9 @@
//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);
+ 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;
@@ -121,13 +119,14 @@
res = sqlite3_exec(m_database, INIT_ID_TABLE.c_str(), NULL, NULL, &errorMessage);
if (res != SQLITE_OK && errorMessage != 0) {
- _LOG_TRACE("Init \"error\" in Identity: " << errorMessage);
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);
+ 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;
@@ -141,13 +140,14 @@
res = sqlite3_exec(m_database, INIT_KEY_TABLE.c_str(), NULL, NULL, &errorMessage);
if (res != SQLITE_OK && errorMessage != 0) {
- _LOG_TRACE("Init \"error\" in KEY: " << errorMessage);
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);
+ 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;
@@ -161,7 +161,6 @@
res = sqlite3_exec(m_database, INIT_CERT_TABLE.c_str(), NULL, NULL, &errorMessage);
if (res != SQLITE_OK && errorMessage != 0) {
- _LOG_TRACE("Init \"error\" in ID-CERT: " << errorMessage);
sqlite3_free(errorMessage);
}
}
@@ -177,7 +176,9 @@
bool result = false;
sqlite3_stmt* statement;
- sqlite3_prepare_v2(m_database, "SELECT count(*) FROM Identity WHERE identity_name=?", -1, &statement, 0);
+ sqlite3_prepare_v2(m_database,
+ "SELECT count(*) FROM Identity WHERE identity_name=?",
+ -1, &statement, 0);
sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
int res = sqlite3_step(statement);
@@ -201,7 +202,9 @@
sqlite3_stmt* statement;
- sqlite3_prepare_v2(m_database, "INSERT OR REPLACE INTO Identity (identity_name) values (?)", -1, &statement, 0);
+ sqlite3_prepare_v2(m_database,
+ "INSERT OR REPLACE INTO Identity (identity_name) values (?)",
+ -1, &statement, 0);
sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
@@ -227,7 +230,9 @@
Name identityName = keyName.getPrefix(-1);
sqlite3_stmt* statement;
- sqlite3_prepare_v2(m_database, "SELECT count(*) FROM Key WHERE identity_name=? AND key_identifier=?", -1, &statement, 0);
+ sqlite3_prepare_v2(m_database,
+ "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);
@@ -247,7 +252,9 @@
}
void
-SecPublicInfoSqlite3::addPublicKey(const Name& keyName, KeyType keyType, const PublicKey& publicKeyDer)
+SecPublicInfoSqlite3::addPublicKey(const Name& keyName,
+ KeyType keyType,
+ const PublicKey& publicKeyDer)
{
if (keyName.empty())
return;
@@ -261,12 +268,19 @@
addIdentity(identityName);
sqlite3_stmt* statement;
- sqlite3_prepare_v2(m_database, "INSERT OR REPLACE INTO Key (identity_name, key_identifier, key_type, public_key) values (?, ?, ?, ?)", -1, &statement, 0);
+ sqlite3_prepare_v2(m_database,
+ "INSERT OR REPLACE INTO Key \
+ (identity_name, key_identifier, key_type, public_key) \
+ values (?, ?, ?, ?)",
+ -1, &statement, 0);
sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 2, keyId, SQLITE_TRANSIENT);
sqlite3_bind_int(statement, 3, (int)keyType);
- sqlite3_bind_blob(statement, 4, publicKeyDer.get().buf(), publicKeyDer.get().size(), SQLITE_STATIC);
+ sqlite3_bind_blob(statement, 4,
+ publicKeyDer.get().buf(),
+ publicKeyDer.get().size(),
+ SQLITE_STATIC);
sqlite3_step(statement);
@@ -278,7 +292,6 @@
{
if (keyName.empty())
{
- _LOG_DEBUG("SecPublicInfoSqlite3::getPublicKey Empty keyName");
throw Error("SecPublicInfoSqlite3::getPublicKey Empty keyName");
}
@@ -286,7 +299,9 @@
Name identityName = keyName.getPrefix(-1);
sqlite3_stmt* statement;
- sqlite3_prepare_v2(m_database, "SELECT public_key FROM Key WHERE identity_name=? AND key_identifier=?", -1, &statement, 0);
+ sqlite3_prepare_v2(m_database,
+ "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);
@@ -296,7 +311,9 @@
shared_ptr<PublicKey> result;
if (res == SQLITE_ROW)
{
- result = make_shared<PublicKey>(static_cast<const uint8_t*>(sqlite3_column_blob(statement, 0)), sqlite3_column_bytes(statement, 0));
+ result =
+ make_shared<PublicKey>(static_cast<const uint8_t*>(sqlite3_column_blob(statement, 0)),
+ sqlite3_column_bytes(statement, 0));
sqlite3_finalize(statement);
return result;
}
@@ -311,7 +328,9 @@
SecPublicInfoSqlite3::doesCertificateExist(const Name& certificateName)
{
sqlite3_stmt* statement;
- sqlite3_prepare_v2(m_database, "SELECT count(*) FROM Certificate WHERE cert_name=?", -1, &statement, 0);
+ sqlite3_prepare_v2(m_database,
+ "SELECT count(*) FROM Certificate WHERE cert_name=?",
+ -1, &statement, 0);
sqlite3_bind_text(statement, 1, certificateName.toUri(), SQLITE_TRANSIENT);
@@ -347,7 +366,6 @@
// "VALUES (?, ?, ?, ?, datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), ?)",
// -1, &statement, 0);
-// _LOG_DEBUG("certName: " << certificateName);
// sqlite3_bind_text(statement, 1, certificateName, SQLITE_STATIC);
// try
@@ -359,12 +377,10 @@
// }
// catch (KeyLocator::Error& e)
// {
-// _LOG_DEBUG("SecPublicInfoSqlite3::addAnyCertificate unsupported keylocator type");
// return;
// }
// catch (SignatureSha256WithRsa::Error& e)
// {
-// _LOG_DEBUG("SecPublicInfoSqlite3::addAnyCertificate unsupported signature type");
// return;
// }
@@ -388,10 +404,12 @@
SecPublicInfoSqlite3::addCertificate(const IdentityCertificate& certificate)
{
const Name& certificateName = certificate.getName();
+ // KeyName is from IdentityCertificate name, so should be qualified.
Name keyName =
- IdentityCertificate::certificateNameToPublicKeyName(certificate.getName()); // KeyName is from IdentityCertificate name, so should be qualified.
+ IdentityCertificate::certificateNameToPublicKeyName(certificate.getName());
- addPublicKey(keyName, KEY_TYPE_RSA, certificate.getPublicKeyInfo()); //HACK!!! Assume the key type is RSA, we should check more.
+ //HACK!!! Assume the key type is RSA, we should check more.
+ addPublicKey(keyName, KEY_TYPE_RSA, certificate.getPublicKeyInfo());
if (doesCertificateExist(certificateName))
return;
@@ -402,41 +420,42 @@
// Insert the certificate
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
- "INSERT OR REPLACE INTO Certificate (cert_name, cert_issuer, identity_name, key_identifier, not_before, not_after, certificate_data)\
- values (?, ?, ?, ?, datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), ?)",
+ "INSERT OR REPLACE INTO Certificate \
+ (cert_name, cert_issuer, identity_name, key_identifier, \
+ not_before, not_after, certificate_data) \
+ values (?, ?, ?, ?, datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), ?)",
-1, &statement, 0);
- _LOG_DEBUG("certName: " << certificateName.toUri());
sqlite3_bind_text(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
+ // this will throw an exception if the signature is not the standard one
+ // or there is no key locator present
SignatureSha256WithRsa signature(certificate.getSignature());
std::string signerName = signature.getKeyLocator().getName().toUri();
sqlite3_bind_text(statement, 2, signerName, SQLITE_STATIC);
}
- catch (KeyLocator::Error& e)
+ catch (std::runtime_error& e)
{
- _LOG_DEBUG("SecPublicInfoSqlite3::addAnyCertificate unsupported keylocator type");
- return;
- }
- catch (SignatureSha256WithRsa::Error& e)
- {
- _LOG_DEBUG("SecPublicInfoSqlite3::addAnyCertificate unsupported signature type");
return;
}
sqlite3_bind_text(statement, 3, identity.toUri(), SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 4, keyId, SQLITE_STATIC);
- sqlite3_bind_int64(statement, 5, static_cast<sqlite3_int64>(
- time::toUnixTimestamp(certificate.getNotBefore()).count()));
- sqlite3_bind_int64(statement, 6, static_cast<sqlite3_int64>(
- time::toUnixTimestamp(certificate.getNotAfter()).count()));
+ sqlite3_bind_int64(statement, 5,
+ static_cast<sqlite3_int64>(
+ time::toUnixTimestamp(certificate.getNotBefore()).count()));
+ sqlite3_bind_int64(statement, 6,
+ static_cast<sqlite3_int64>(
+ time::toUnixTimestamp(certificate.getNotAfter()).count()));
- sqlite3_bind_blob(statement, 7, certificate.wireEncode().wire(), certificate.wireEncode().size(), SQLITE_TRANSIENT);
+ sqlite3_bind_blob(statement, 7,
+ certificate.wireEncode().wire(),
+ certificate.wireEncode().size(),
+ SQLITE_TRANSIENT);
sqlite3_step(statement);
@@ -459,7 +478,7 @@
if (res == SQLITE_ROW)
{
shared_ptr<IdentityCertificate> certificate = make_shared<IdentityCertificate>();
- certificate->wireDecode(Block((const uint8_t*)sqlite3_column_blob(statement, 0),
+ certificate->wireDecode(Block(static_cast<const uint8_t*>(sqlite3_column_blob(statement, 0)),
sqlite3_column_bytes(statement, 0)));
sqlite3_finalize(statement);
return certificate;
@@ -476,13 +495,16 @@
SecPublicInfoSqlite3::getDefaultIdentity()
{
sqlite3_stmt* statement;
- sqlite3_prepare_v2(m_database, "SELECT identity_name FROM Identity WHERE default_identity=1", -1, &statement, 0);
+ sqlite3_prepare_v2(m_database,
+ "SELECT identity_name FROM Identity WHERE default_identity=1",
+ -1, &statement, 0);
int res = sqlite3_step(statement);
if (res == SQLITE_ROW)
{
- Name identity = Name(string(reinterpret_cast<const char *>(sqlite3_column_text(statement, 0)), sqlite3_column_bytes(statement, 0)));
+ Name identity(string(reinterpret_cast<const char *>(sqlite3_column_text(statement, 0)),
+ sqlite3_column_bytes(statement, 0)));
sqlite3_finalize(statement);
return identity;
}
@@ -501,15 +523,20 @@
sqlite3_stmt* statement;
//Reset previous default identity
- sqlite3_prepare_v2(m_database, "UPDATE Identity SET default_identity=0 WHERE default_identity=1", -1, &statement, 0);
+ sqlite3_prepare_v2(m_database,
+ "UPDATE Identity SET default_identity=0 WHERE default_identity=1",
+ -1, &statement, 0);
while (sqlite3_step(statement) == SQLITE_ROW)
- {}
+ {
+ }
sqlite3_finalize(statement);
//Set current default identity
- sqlite3_prepare_v2(m_database, "UPDATE Identity SET default_identity=1 WHERE identity_name=?", -1, &statement, 0);
+ sqlite3_prepare_v2(m_database,
+ "UPDATE Identity SET default_identity=1 WHERE identity_name=?",
+ -1, &statement, 0);
sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
@@ -522,7 +549,9 @@
SecPublicInfoSqlite3::getDefaultKeyNameForIdentity(const Name& identityName)
{
sqlite3_stmt* statement;
- sqlite3_prepare_v2(m_database, "SELECT key_identifier FROM Key WHERE identity_name=? AND default_key=1", -1, &statement, 0);
+ sqlite3_prepare_v2(m_database,
+ "SELECT key_identifier FROM Key WHERE identity_name=? AND default_key=1",
+ -1, &statement, 0);
sqlite3_bind_text(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
@@ -530,8 +559,9 @@
if (res == SQLITE_ROW)
{
- Name keyName = Name(identityName).append(string(reinterpret_cast<const char *>(sqlite3_column_text(statement, 0)),
- sqlite3_column_bytes(statement, 0)));
+ Name keyName = identityName;
+ keyName.append(string(reinterpret_cast<const char *>(sqlite3_column_text(statement, 0)),
+ sqlite3_column_bytes(statement, 0)));
sqlite3_finalize(statement);
return keyName;
}
@@ -546,7 +576,7 @@
SecPublicInfoSqlite3::setDefaultKeyNameForIdentityInternal(const Name& keyName)
{
if (!doesPublicKeyExist(keyName))
- throw Error("SecPublicInfoSqlite3::setDefaultKeyNameForIdentityInternal Key does not exist:" + keyName.toUri());
+ throw Error("Key does not exist:" + keyName.toUri());
string keyId = keyName.get(-1).toEscapedString();
Name identityName = keyName.getPrefix(-1);
@@ -554,17 +584,22 @@
sqlite3_stmt* statement;
//Reset previous default Key
- sqlite3_prepare_v2(m_database, "UPDATE Key SET default_key=0 WHERE default_key=1 and identity_name=?", -1, &statement, 0);
+ sqlite3_prepare_v2(m_database,
+ "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);
while (sqlite3_step(statement) == SQLITE_ROW)
- {}
+ {
+ }
sqlite3_finalize(statement);
//Set current default Key
- sqlite3_prepare_v2(m_database, "UPDATE Key SET default_key=1 WHERE identity_name=? AND key_identifier=?", -1, &statement, 0);
+ sqlite3_prepare_v2(m_database,
+ "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);
@@ -584,7 +619,10 @@
Name identityName = keyName.getPrefix(-1);
sqlite3_stmt* statement;
- sqlite3_prepare_v2(m_database, "SELECT cert_name FROM Certificate WHERE identity_name=? AND key_identifier=? AND default_cert=1", -1, &statement, 0);
+ sqlite3_prepare_v2(m_database,
+ "SELECT cert_name FROM Certificate \
+ 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);
@@ -593,14 +631,15 @@
if (res == SQLITE_ROW)
{
- Name certName = Name(string(reinterpret_cast<const char *>(sqlite3_column_text(statement, 0)), sqlite3_column_bytes(statement, 0)));
+ Name certName(string(reinterpret_cast<const char *>(sqlite3_column_text(statement, 0)),
+ sqlite3_column_bytes(statement, 0)));
sqlite3_finalize(statement);
return certName;
}
else
{
sqlite3_finalize(statement);
- throw Error("SecPublicInfoSqlite3::getDefaultCertificateNameForKey certificate not found");
+ throw Error("certificate not found");
}
}
@@ -608,7 +647,7 @@
SecPublicInfoSqlite3::setDefaultCertificateNameForKeyInternal(const Name& certificateName)
{
if (!doesCertificateExist(certificateName))
- throw Error("SecPublicInfoSqlite3::setDefaultCertificateNameForKeyInternal certificate does not exist:" + certificateName.toUri());
+ throw Error("certificate does not exist:" + certificateName.toUri());
Name keyName = IdentityCertificate::certificateNameToPublicKeyName(certificateName);
string keyId = keyName.get(-1).toEscapedString();
@@ -617,18 +656,25 @@
sqlite3_stmt* statement;
//Reset previous default Key
- sqlite3_prepare_v2(m_database, "UPDATE Certificate SET default_cert=0 WHERE default_cert=1 AND identity_name=? AND key_identifier=?", -1, &statement, 0);
+ sqlite3_prepare_v2(m_database,
+ "UPDATE Certificate SET default_cert=0 \
+ 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);
while (sqlite3_step(statement) == SQLITE_ROW)
- {}
+ {
+ }
sqlite3_finalize(statement);
//Set current default Key
- sqlite3_prepare_v2(m_database, "UPDATE Certificate SET default_cert=1 WHERE identity_name=? AND key_identifier=? AND cert_name=?", -1, &statement, 0);
+ sqlite3_prepare_v2(m_database,
+ "UPDATE Certificate SET default_cert=1 \
+ 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);
@@ -644,90 +690,129 @@
{
sqlite3_stmt* stmt;
if (isDefault)
- sqlite3_prepare_v2 (m_database, "SELECT identity_name FROM Identity WHERE default_identity=1", -1, &stmt, 0);
+ sqlite3_prepare_v2(m_database,
+ "SELECT identity_name FROM Identity WHERE default_identity=1",
+ -1, &stmt, 0);
else
- sqlite3_prepare_v2 (m_database, "SELECT identity_name FROM Identity WHERE default_identity=0", -1, &stmt, 0);
+ sqlite3_prepare_v2(m_database,
+ "SELECT identity_name FROM Identity WHERE default_identity=0",
+ -1, &stmt, 0);
- while(sqlite3_step (stmt) == SQLITE_ROW)
- nameList.push_back(Name(string(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)), sqlite3_column_bytes (stmt, 0))));
+ while (sqlite3_step(stmt) == SQLITE_ROW)
+ nameList.push_back(Name(string(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)),
+ sqlite3_column_bytes(stmt, 0))));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
}
void
SecPublicInfoSqlite3::getAllKeyNames(vector<Name>& nameList, bool isDefault)
{
sqlite3_stmt* stmt;
- if (isDefault)
- sqlite3_prepare_v2 (m_database, "SELECT identity_name, key_identifier FROM Key WHERE default_key=1", -1, &stmt, 0);
- else
- sqlite3_prepare_v2 (m_database, "SELECT identity_name, key_identifier FROM Key WHERE default_key=0", -1, &stmt, 0);
- while(sqlite3_step (stmt) == SQLITE_ROW)
+ if (isDefault)
+ sqlite3_prepare_v2(m_database,
+ "SELECT identity_name, key_identifier FROM Key WHERE default_key=1",
+ -1, &stmt, 0);
+ else
+ sqlite3_prepare_v2(m_database,
+ "SELECT identity_name, key_identifier FROM Key WHERE default_key=0",
+ -1, &stmt, 0);
+
+ while (sqlite3_step(stmt) == SQLITE_ROW)
{
- Name keyName(string(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)), sqlite3_column_bytes (stmt, 0)));
- keyName.append(string(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 1)), sqlite3_column_bytes (stmt, 1)));
+ Name keyName(string(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)),
+ sqlite3_column_bytes(stmt, 0)));
+ keyName.append(string(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 1)),
+ sqlite3_column_bytes(stmt, 1)));
nameList.push_back(keyName);
}
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
}
void
-SecPublicInfoSqlite3::getAllKeyNamesOfIdentity(const Name& identity, vector<Name>& nameList, bool isDefault)
+SecPublicInfoSqlite3::getAllKeyNamesOfIdentity(const Name& identity,
+ vector<Name>& nameList,
+ bool isDefault)
{
sqlite3_stmt* stmt;
+
if (isDefault)
- sqlite3_prepare_v2 (m_database, "SELECT key_identifier FROM Key WHERE default_key=1 and identity_name=?", -1, &stmt, 0);
+ sqlite3_prepare_v2(m_database,
+ "SELECT key_identifier FROM Key WHERE default_key=1 and identity_name=?",
+ -1, &stmt, 0);
else
- sqlite3_prepare_v2 (m_database, "SELECT key_identifier FROM Key WHERE default_key=0 and identity_name=?", -1, &stmt, 0);
+ sqlite3_prepare_v2(m_database,
+ "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_text(stmt, 1,
+ identity.toUri().c_str(),
+ identity.toUri().size(),
+ SQLITE_TRANSIENT);
- while(sqlite3_step (stmt) == SQLITE_ROW)
+ while (sqlite3_step(stmt) == SQLITE_ROW)
{
Name keyName(identity);
- keyName.append(string(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)), sqlite3_column_bytes (stmt, 0)));
+ keyName.append(string(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)),
+ sqlite3_column_bytes(stmt, 0)));
nameList.push_back(keyName);
}
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
}
void
SecPublicInfoSqlite3::getAllCertificateNames(vector<Name>& nameList, bool isDefault)
{
sqlite3_stmt* stmt;
+
if (isDefault)
- sqlite3_prepare_v2 (m_database, "SELECT cert_name FROM Certificate WHERE default_cert=1", -1, &stmt, 0);
+ sqlite3_prepare_v2(m_database,
+ "SELECT cert_name FROM Certificate WHERE default_cert=1",
+ -1, &stmt, 0);
else
- sqlite3_prepare_v2 (m_database, "SELECT cert_name FROM Certificate WHERE default_cert=0", -1, &stmt, 0);
+ sqlite3_prepare_v2(m_database,
+ "SELECT cert_name FROM Certificate WHERE default_cert=0",
+ -1, &stmt, 0);
- while(sqlite3_step (stmt) == SQLITE_ROW)
- nameList.push_back(string(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)), sqlite3_column_bytes (stmt, 0)));
+ while (sqlite3_step(stmt) == SQLITE_ROW)
+ nameList.push_back(string(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)),
+ sqlite3_column_bytes(stmt, 0)));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
}
void
-SecPublicInfoSqlite3::getAllCertificateNamesOfKey(const Name& keyName, vector<Name>& nameList, bool isDefault)
+SecPublicInfoSqlite3::getAllCertificateNamesOfKey(const Name& keyName,
+ vector<Name>& nameList,
+ bool isDefault)
{
if (keyName.empty())
return;
sqlite3_stmt* stmt;
if (isDefault)
- sqlite3_prepare_v2 (m_database, "SELECT cert_name FROM Certificate WHERE default_cert=1 and identity_name=? and key_identifier=?", -1, &stmt, 0);
+ sqlite3_prepare_v2(m_database,
+ "SELECT cert_name FROM Certificate \
+ WHERE default_cert=1 and identity_name=? and key_identifier=?",
+ -1, &stmt, 0);
else
- sqlite3_prepare_v2 (m_database, "SELECT cert_name FROM Certificate WHERE default_cert=0 and identity_name=? and key_identifier=?", -1, &stmt, 0);
+ sqlite3_prepare_v2(m_database,
+ "SELECT cert_name FROM Certificate \
+ WHERE default_cert=0 and identity_name=? and key_identifier=?",
+ -1, &stmt, 0);
Name identity = keyName.getPrefix(-1);
- sqlite3_bind_text(stmt, 1, identity.toUri().c_str(), identity.toUri().size (), SQLITE_TRANSIENT);
+ sqlite3_bind_text(stmt, 1, identity.toUri().c_str(), identity.toUri().size (), SQLITE_TRANSIENT);
+
std::string baseKeyName = keyName.get(-1).toEscapedString();
sqlite3_bind_text(stmt, 2, baseKeyName.c_str(), baseKeyName.size(), SQLITE_TRANSIENT);
- while(sqlite3_step (stmt) == SQLITE_ROW)
- nameList.push_back(string(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)), sqlite3_column_bytes (stmt, 0)));
+ while (sqlite3_step(stmt) == SQLITE_ROW)
+ nameList.push_back(string(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)),
+ sqlite3_column_bytes(stmt, 0)));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
}
void
@@ -738,9 +823,9 @@
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_text(stmt, 1, certName.toUri().c_str(), certName.toUri().size (), SQLITE_TRANSIENT);
sqlite3_step(stmt);
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
}
void
@@ -753,17 +838,21 @@
string keyId = keyName.get(-1).toEscapedString();
sqlite3_stmt* stmt;
- sqlite3_prepare_v2(m_database, "DELETE FROM Certificate WHERE identity_name=? and key_identifier=?", -1, &stmt, 0);
+ 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_step(stmt);
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
- sqlite3_prepare_v2(m_database, "DELETE FROM Key WHERE identity_name=? and key_identifier=?", -1, &stmt, 0);
+ 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_step(stmt);
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
}
void
@@ -775,17 +864,17 @@
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_step(stmt);
- sqlite3_finalize (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_step(stmt);
- sqlite3_finalize (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_step(stmt);
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
}
} // namespace ndn
diff --git a/src/security/sec-public-info-sqlite3.hpp b/src/security/sec-public-info-sqlite3.hpp
index b89859a..6241817 100644
--- a/src/security/sec-public-info-sqlite3.hpp
+++ b/src/security/sec-public-info-sqlite3.hpp
@@ -51,7 +51,7 @@
virtual void
addPublicKey(const Name& keyName, KeyType keyType, const PublicKey& publicKeyDer);
- virtual ptr_lib::shared_ptr<PublicKey>
+ virtual shared_ptr<PublicKey>
getPublicKey(const Name& keyName);
virtual bool
@@ -60,7 +60,7 @@
virtual void
addCertificate(const IdentityCertificate& certificate);
- virtual ptr_lib::shared_ptr<IdentityCertificate>
+ virtual shared_ptr<IdentityCertificate>
getCertificate(const Name& certificateName);
diff --git a/src/security/sec-public-info.hpp b/src/security/sec-public-info.hpp
index 5fe7b3c..99b4f57 100644
--- a/src/security/sec-public-info.hpp
+++ b/src/security/sec-public-info.hpp
@@ -20,7 +20,8 @@
/**
* @brief SecPublicInfo is a base class for the storage of public information.
*
- * It specify interfaces related to public information, such as identity, public keys and certificates.
+ * It specify interfaces related to public information, such as identity, public keys and
+ * certificates.
*/
class SecPublicInfo {
public:
@@ -338,7 +339,8 @@
addCertificateAsKeyDefault(const IdentityCertificate& certificate);
/**
- * @brief Add a certificate into the public key identity storage and set the certificate as the default one of its corresponding identity.
+ * @brief Add a certificate into the public key identity storage and set the certificate as the
+ * default one of its corresponding identity.
*
* @param certificate The certificate to be added.
* @throws SecPublicInfo::Error if the certificate cannot be added (though it is really rare)
@@ -347,7 +349,8 @@
addCertificateAsIdentityDefault(const IdentityCertificate& certificate);
/**
- * @brief Add a certificate into the public key identity storage and set the certificate as the default one of the default identity.
+ * @brief Add a certificate into the public key identity storage and set the certificate as the
+ * default one of the default identity.
*
* @param certificate The certificate to be added.
* @throws SecPublicInfo::Error if the certificate cannot be added (though it is really rare)
@@ -445,7 +448,8 @@
{
addCertificate(certificate);
Name certName = certificate.getName();
- setDefaultKeyNameForIdentityInternal(IdentityCertificate::certificateNameToPublicKeyName(certName));
+ Name keyName = IdentityCertificate::certificateNameToPublicKeyName(certName);
+ setDefaultKeyNameForIdentityInternal(keyName);
setDefaultCertificateNameForKeyInternal(certName);
refreshDefaultCertificate();
}
diff --git a/src/security/sec-rule-relative.cpp b/src/security/sec-rule-relative.cpp
index 6133aac..3b0b40f 100644
--- a/src/security/sec-rule-relative.cpp
+++ b/src/security/sec-rule-relative.cpp
@@ -20,8 +20,10 @@
namespace ndn {
-SecRuleRelative::SecRuleRelative (const string& dataRegex, const string& signerRegex, const string& op,
- const string& dataExpand, const string& signerExpand, bool isPositive)
+SecRuleRelative::SecRuleRelative (const string& dataRegex, const string& signerRegex,
+ const string& op,
+ const string& dataExpand, const string& signerExpand,
+ bool isPositive)
: SecRule(isPositive),
m_dataRegex(dataRegex),
m_signerRegex(signerRegex),
@@ -43,17 +45,16 @@
SecRuleRelative::satisfy (const Data& data)
{
Name dataName = data.getName();
- try {
- SignatureSha256WithRsa sig(data.getSignature());
- Name signerName = sig.getKeyLocator().getName ();
- return satisfy (dataName, signerName);
- }
- catch (SignatureSha256WithRsa::Error& e){
- return false;
- }
- catch (KeyLocator::Error& e){
- return false;
- }
+ try
+ {
+ SignatureSha256WithRsa sig(data.getSignature());
+ Name signerName = sig.getKeyLocator().getName ();
+ return satisfy (dataName, signerName);
+ }
+ catch (std::runtime_error& e)
+ {
+ return false;
+ }
}
bool
@@ -74,22 +75,23 @@
bool
SecRuleRelative::matchDataName (const Data& data)
-{ return m_dataNameRegex.match(data.getName()); }
+{
+ return m_dataNameRegex.match(data.getName());
+}
bool
SecRuleRelative::matchSignerName (const Data& data)
{
- try {
- SignatureSha256WithRsa sig(data.getSignature());
- Name signerName = sig.getKeyLocator().getName ();
- return m_signerNameRegex.match(signerName);
- }
- catch (SignatureSha256WithRsa::Error& e){
- return false;
- }
- catch (KeyLocator::Error& e){
- return false;
- }
+ try
+ {
+ SignatureSha256WithRsa sig(data.getSignature());
+ Name signerName = sig.getKeyLocator().getName ();
+ return m_signerNameRegex.match(signerName);
+ }
+ catch (std::runtime_error& e)
+ {
+ return false;
+ }
}
bool
diff --git a/src/security/sec-rule-relative.hpp b/src/security/sec-rule-relative.hpp
index 7ea4c51..522e52e 100644
--- a/src/security/sec-rule-relative.hpp
+++ b/src/security/sec-rule-relative.hpp
@@ -27,8 +27,10 @@
}
};
- SecRuleRelative(const std::string& dataRegex, const std::string& signerRegex, const std::string& op,
- const std::string& dataExpand, const std::string& signerExpand, bool isPositive);
+ SecRuleRelative(const std::string& dataRegex, const std::string& signerRegex,
+ const std::string& op,
+ const std::string& dataExpand, const std::string& signerExpand,
+ bool isPositive);
virtual
~SecRuleRelative();
diff --git a/src/security/sec-rule-specific.cpp b/src/security/sec-rule-specific.cpp
index a9fee4e..f9b2662 100644
--- a/src/security/sec-rule-specific.cpp
+++ b/src/security/sec-rule-specific.cpp
@@ -19,32 +19,35 @@
: SecRule(true)
, m_dataRegex(dataRegex)
, m_signerRegex(signerRegex)
-{}
+{
+}
SecRuleSpecific::SecRuleSpecific(const SecRuleSpecific& rule)
: SecRule(true)
, m_dataRegex(rule.m_dataRegex)
, m_signerRegex(rule.m_signerRegex)
-{}
+{
+}
bool
SecRuleSpecific::matchDataName(const Data& data)
-{ return m_dataRegex->match(data.getName()); }
+{
+ return m_dataRegex->match(data.getName());
+}
bool
SecRuleSpecific::matchSignerName(const Data& data)
{
- try {
- SignatureSha256WithRsa sig(data.getSignature());
- Name signerName = sig.getKeyLocator().getName ();
- return m_signerRegex->match(signerName);
- }
- catch (SignatureSha256WithRsa::Error& e) {
- return false;
- }
- catch (KeyLocator::Error& e) {
- return false;
- }
+ try
+ {
+ SignatureSha256WithRsa sig(data.getSignature());
+ Name signerName = sig.getKeyLocator().getName();
+ return m_signerRegex->match(signerName);
+ }
+ catch (std::runtime_error& e)
+ {
+ return false;
+ }
}
bool
diff --git a/src/security/sec-rule-specific.hpp b/src/security/sec-rule-specific.hpp
index 1e961a0..3103f3b 100644
--- a/src/security/sec-rule-specific.hpp
+++ b/src/security/sec-rule-specific.hpp
@@ -14,33 +14,33 @@
namespace ndn {
-class SecRuleSpecific : public ndn::SecRule
+class SecRuleSpecific : public SecRule
{
-
+
public:
- SecRuleSpecific(ndn::shared_ptr<ndn::Regex> dataRegex,
- ndn::shared_ptr<ndn::Regex> signerRegex);
+ SecRuleSpecific(shared_ptr<Regex> dataRegex,
+ shared_ptr<Regex> signerRegex);
SecRuleSpecific(const SecRuleSpecific& rule);
virtual
~SecRuleSpecific() {};
- bool
- matchDataName(const ndn::Data& data);
-
- bool
- matchSignerName(const ndn::Data& data);
+ bool
+ matchDataName(const Data& data);
bool
- satisfy(const ndn::Data& data);
+ matchSignerName(const Data& data);
bool
- satisfy(const ndn::Name& dataName, const ndn::Name& signerName);
-
+ satisfy(const Data& data);
+
+ bool
+ satisfy(const Name& dataName, const Name& signerName);
+
private:
- ndn::shared_ptr<ndn::Regex> m_dataRegex;
- ndn::shared_ptr<ndn::Regex> m_signerRegex;
+ shared_ptr<Regex> m_dataRegex;
+ shared_ptr<Regex> m_signerRegex;
};
} // namespace ndn
diff --git a/src/security/sec-rule.hpp b/src/security/sec-rule.hpp
index ecb9686..4db324f 100644
--- a/src/security/sec-rule.hpp
+++ b/src/security/sec-rule.hpp
@@ -27,12 +27,14 @@
};
SecRule(bool isPositive)
- : m_isPositive(isPositive)
- {}
+ : m_isPositive(isPositive)
+ {
+ }
virtual
~SecRule()
- {}
+ {
+ }
virtual bool
matchDataName(const Data& data) = 0;
diff --git a/src/security/sec-tpm-file.cpp b/src/security/sec-tpm-file.cpp
index 3a05282..5238ca4 100644
--- a/src/security/sec-tpm-file.cpp
+++ b/src/security/sec-tpm-file.cpp
@@ -43,7 +43,10 @@
using namespace CryptoPP;
string digest;
SHA256 hash;
- StringSource src(keyName, true, new HashFilter(hash, new Base64Encoder (new CryptoPP::StringSink(digest))));
+ StringSource src(keyName,
+ true,
+ new HashFilter(hash,
+ new Base64Encoder(new CryptoPP::StringSink(digest))));
boost::algorithm::trim(digest);
std::replace(digest.begin(), digest.end(), '/', '%');
@@ -88,38 +91,42 @@
string keyFileName = m_impl->maintainMapping(keyURI);
- try{
- switch (keyType){
- case KEY_TYPE_RSA:
- {
- using namespace CryptoPP;
- AutoSeededRandomPool rng;
+ try
+ {
+ switch (keyType)
+ {
+ case KEY_TYPE_RSA:
+ {
+ using namespace CryptoPP;
+ AutoSeededRandomPool rng;
- InvertibleRSAFunction privateKey;
- privateKey.Initialize(rng, keySize);
+ InvertibleRSAFunction privateKey;
+ privateKey.Initialize(rng, keySize);
- string privateKeyFileName = keyFileName + ".pri";
- Base64Encoder privateKeySink(new FileSink(privateKeyFileName.c_str()));
- privateKey.DEREncode(privateKeySink);
- privateKeySink.MessageEnd();
+ 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();
+ 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!");
+ /*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());
- }
+ catch (const CryptoPP::Exception& e)
+ {
+ throw Error(e.what());
+ }
}
void
@@ -144,14 +151,20 @@
throw Error("Public Key already exist");
ostringstream os;
- try{
- using namespace CryptoPP;
- FileSource(m_impl->nameTransform(keyURI, ".pub").string().c_str(), true, new Base64Decoder(new FileSink(os)));
- }catch (const CryptoPP::Exception& e){
- throw Error(e.what());
- }
+ try
+ {
+ using namespace CryptoPP;
+ FileSource(m_impl->nameTransform(keyURI, ".pub").string().c_str(),
+ true,
+ new Base64Decoder(new FileSink(os)));
+ }
+ catch (const CryptoPP::Exception& e)
+ {
+ throw Error(e.what());
+ }
- return make_shared<PublicKey>(reinterpret_cast<const uint8_t*>(os.str().c_str()), os.str().size());
+ return make_shared<PublicKey>(reinterpret_cast<const uint8_t*>(os.str().c_str()),
+ os.str().size());
}
ConstBufferPtr
@@ -167,73 +180,94 @@
bool
SecTpmFile::importPrivateKeyPkcs1IntoTpm(const Name& keyName, const uint8_t* buf, size_t size)
{
- try{
- string keyFileName = m_impl->maintainMapping(keyName.toUri());
- keyFileName.append(".pri");
- CryptoPP::StringSource(buf, size, true,
- new CryptoPP::Base64Encoder(new CryptoPP::FileSink(keyFileName.c_str())));
- return true;
- }catch (...){
- return false;
- }
+ try
+ {
+ using namespace CryptoPP;
+
+ string keyFileName = m_impl->maintainMapping(keyName.toUri());
+ keyFileName.append(".pri");
+ StringSource(buf, size,
+ true,
+ new Base64Encoder(new FileSink(keyFileName.c_str())));
+ return true;
+ }
+ catch (const CryptoPP::Exception& e)
+ {
+ return false;
+ }
}
bool
SecTpmFile::importPublicKeyPkcs1IntoTpm(const Name& keyName, const uint8_t* buf, size_t size)
{
- try{
- string keyFileName = m_impl->maintainMapping(keyName.toUri());
- keyFileName.append(".pub");
- CryptoPP::StringSource(buf, size, true,
- new CryptoPP::Base64Encoder(new CryptoPP::FileSink(keyFileName.c_str())));
- return true;
- }catch (...){
- return false;
- }
+ try
+ {
+ using namespace CryptoPP;
+
+ string keyFileName = m_impl->maintainMapping(keyName.toUri());
+ keyFileName.append(".pub");
+ StringSource(buf, size,
+ true,
+ new Base64Encoder(new FileSink(keyFileName.c_str())));
+ return true;
+ }
+ catch (const CryptoPP::Exception& e)
+ {
+ return false;
+ }
}
Block
-SecTpmFile::signInTpm(const uint8_t* data, size_t dataLength, const Name& keyName, DigestAlgorithm digestAlgorithm)
+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{
- using namespace CryptoPP;
- AutoSeededRandomPool rng;
+ try
+ {
+ using namespace CryptoPP;
+ AutoSeededRandomPool rng;
- //Read private key
- ByteQueue bytes;
- FileSource file(m_impl->nameTransform(keyURI, ".pri").string().c_str(), true, new Base64Decoder);
- file.TransferTo(bytes);
- bytes.MessageEnd();
- RSA::PrivateKey privateKey;
- privateKey.Load(bytes);
+ //Read private key
+ ByteQueue bytes;
+ FileSource file(m_impl->nameTransform(keyURI, ".pri").string().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);
+ //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)));
+ 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!");
+ return Block(Tlv::SignatureValue, os.buf());
+ }
+ default:
+ throw Error("Unsupported digest algorithm!");
+ }
}
- }catch (const CryptoPP::Exception& e){
- throw Error(e.what());
- }
+ catch (const CryptoPP::Exception& e)
+ {
+ throw Error(e.what());
+ }
}
ConstBufferPtr
-SecTpmFile::decryptInTpm(const uint8_t* data, size_t dataLength, const Name& keyName, bool isSymmetric)
+SecTpmFile::decryptInTpm(const uint8_t* data, size_t dataLength,
+ const Name& keyName, bool isSymmetric)
{
throw Error("SecTpmFile::decryptInTpm is not supported!");
// string keyURI = keyName.toUri();
@@ -294,7 +328,8 @@
}
ConstBufferPtr
-SecTpmFile::encryptInTpm(const uint8_t* data, size_t dataLength, const Name& keyName, bool isSymmetric)
+SecTpmFile::encryptInTpm(const uint8_t* data, size_t dataLength,
+ const Name& keyName, bool isSymmetric)
{
throw Error("SecTpmFile::encryptInTpm is not supported!");
// string keyURI = keyName.toUri();
@@ -421,14 +456,16 @@
bool
SecTpmFile::generateRandomBlock(uint8_t* res, size_t size)
{
- try {
- CryptoPP::AutoSeededRandomPool rng;
- rng.GenerateBlock(res, size);
- return true;
- }
- catch (const CryptoPP::Exception& e) {
- return false;
- }
+ try
+ {
+ CryptoPP::AutoSeededRandomPool rng;
+ rng.GenerateBlock(res, size);
+ return true;
+ }
+ catch (const CryptoPP::Exception& e)
+ {
+ return false;
+ }
}
} // namespace ndn
diff --git a/src/security/sec-tpm-file.hpp b/src/security/sec-tpm-file.hpp
index fc1e410..8cc20df 100644
--- a/src/security/sec-tpm-file.hpp
+++ b/src/security/sec-tpm-file.hpp
@@ -31,15 +31,19 @@
SecTpmFile(const std::string& dir = "");
virtual
- ~SecTpmFile() {};
+ ~SecTpmFile()
+ {
+ }
virtual void
setTpmPassword(const uint8_t* password, size_t passwordLength)
- {}
+ {
+ }
virtual void
resetTpmPassword()
- {}
+ {
+ }
virtual void
setInTerminal(bool inTerminal)
@@ -75,7 +79,8 @@
getPublicKeyFromTpm(const Name& keyName);
virtual Block
- signInTpm(const uint8_t* data, size_t dataLength, const Name& keyName, DigestAlgorithm digestAlgorithm);
+ signInTpm(const uint8_t* data, size_t dataLength,
+ const Name& keyName, DigestAlgorithm digestAlgorithm);
virtual ConstBufferPtr
decryptInTpm(const uint8_t* data, size_t dataLength, const Name& keyName, bool isSymmetric);
@@ -94,7 +99,8 @@
virtual void
addAppToACL(const Name& keyName, KeyClass keyClass, const std::string& appPath, AclType acl)
- {}
+ {
+ }
protected:
/******************************
diff --git a/src/security/sec-tpm-memory.cpp b/src/security/sec-tpm-memory.cpp
index e196f88..3475aa4 100644
--- a/src/security/sec-tpm-memory.cpp
+++ b/src/security/sec-tpm-memory.cpp
@@ -26,25 +26,25 @@
{
// Use a temporary pointer since d2i updates it.
const uint8_t* derPointer = keyDer;
- privateKey_ = d2i_RSAPrivateKey(NULL, &derPointer, keyDerLength);
- if (!privateKey_)
+ m_privateKey = d2i_RSAPrivateKey(NULL, &derPointer, keyDerLength);
+ if (!m_privateKey)
throw Error("RsaPrivateKey constructor: Error decoding private key DER");
}
~RsaPrivateKey()
{
- if (privateKey_)
- RSA_free(privateKey_);
+ if (m_privateKey)
+ RSA_free(m_privateKey);
}
rsa_st*
getPrivateKey()
{
- return privateKey_;
+ return m_privateKey;
}
private:
- rsa_st* privateKey_;
+ rsa_st* m_privateKey;
};
SecTpmMemory::~SecTpmMemory()
@@ -53,19 +53,18 @@
void
SecTpmMemory::setKeyPairForKeyName(const Name& keyName,
- uint8_t* publicKeyDer, size_t publicKeyDerLength,
- uint8_t* privateKeyDer, size_t privateKeyDerLength)
+ const uint8_t* publicKeyDer, size_t publicKeyDerLength,
+ const uint8_t* privateKeyDer, size_t privateKeyDerLength)
{
- publicKeyStore_[keyName.toUri()] = make_shared<PublicKey>(publicKeyDer, publicKeyDerLength);
- privateKeyStore_[keyName.toUri()] = make_shared<RsaPrivateKey>(privateKeyDer, privateKeyDerLength);
+ m_publicKeyStore[keyName.toUri()] = make_shared<PublicKey>(publicKeyDer, publicKeyDerLength);
+ m_privateKeyStore[keyName.toUri()] = make_shared<RsaPrivateKey>(privateKeyDer,
+ privateKeyDerLength);
}
void
SecTpmMemory::generateKeyPairInTpm(const Name& keyName, KeyType keyType, int keySize)
{
-#if 1
throw Error("SecTpmMemory::generateKeyPair not implemented");
-#endif
}
void
@@ -95,8 +94,8 @@
shared_ptr<PublicKey>
SecTpmMemory::getPublicKeyFromTpm(const Name& keyName)
{
- PublicKeyStore::iterator publicKey = publicKeyStore_.find(keyName.toUri());
- if (publicKey == publicKeyStore_.end())
+ PublicKeyStore::iterator publicKey = m_publicKeyStore.find(keyName.toUri());
+ if (publicKey == m_publicKeyStore.end())
throw Error(string("MemoryPrivateKeyStorage: Cannot find public key ") + keyName.toUri());
return publicKey->second;
}
@@ -110,8 +109,8 @@
throw Error("Unsupported digest algorithm.");
// Find the private key and sign.
- PrivateKeyStore::iterator privateKey = privateKeyStore_.find(keyName.toUri());
- if (privateKey == privateKeyStore_.end())
+ PrivateKeyStore::iterator privateKey = m_privateKeyStore.find(keyName.toUri());
+ if (privateKey == m_privateKeyStore.end())
throw Error(string("MemoryPrivateKeyStorage: Cannot find private key ") + keyName.toUri());
uint8_t digest[SHA256_DIGEST_LENGTH];
@@ -136,36 +135,32 @@
}
ConstBufferPtr
-SecTpmMemory::decryptInTpm(const uint8_t* data, size_t dataLength, const Name& keyName, bool isSymmetric)
+SecTpmMemory::decryptInTpm(const uint8_t* data, size_t dataLength,
+ const Name& keyName, bool isSymmetric)
{
-#if 1
throw Error("MemoryPrivateKeyStorage::decrypt not implemented");
-#endif
}
ConstBufferPtr
-SecTpmMemory::encryptInTpm(const uint8_t* data, size_t dataLength, const Name& keyName, bool isSymmetric)
+SecTpmMemory::encryptInTpm(const uint8_t* data, size_t dataLength,
+ const Name& keyName, bool isSymmetric)
{
-#if 1
throw Error("MemoryPrivateKeyStorage::encrypt not implemented");
-#endif
}
void
SecTpmMemory::generateSymmetricKeyInTpm(const Name& keyName, KeyType keyType, int keySize)
{
-#if 1
throw Error("MemoryPrivateKeyStorage::generateKey not implemented");
-#endif
}
bool
SecTpmMemory::doesKeyExistInTpm(const Name& keyName, KeyClass keyClass)
{
if (keyClass == KEY_CLASS_PUBLIC)
- return publicKeyStore_.find(keyName.toUri()) != publicKeyStore_.end();
+ return m_publicKeyStore.find(keyName.toUri()) != m_publicKeyStore.end();
else if (keyClass == KEY_CLASS_PRIVATE)
- return privateKeyStore_.find(keyName.toUri()) != privateKeyStore_.end();
+ return m_privateKeyStore.find(keyName.toUri()) != m_privateKeyStore.end();
else
// KEY_CLASS_SYMMETRIC not implemented yet.
return false;
@@ -174,14 +169,16 @@
bool
SecTpmMemory::generateRandomBlock(uint8_t* res, size_t size)
{
- try {
- CryptoPP::AutoSeededRandomPool rng;
- rng.GenerateBlock(res, size);
- return true;
- }
- catch (const CryptoPP::Exception& e) {
- return false;
- }
+ try
+ {
+ CryptoPP::AutoSeededRandomPool rng;
+ rng.GenerateBlock(res, size);
+ return true;
+ }
+ catch (const CryptoPP::Exception& e)
+ {
+ return false;
+ }
}
} // namespace ndn
diff --git a/src/security/sec-tpm-memory.hpp b/src/security/sec-tpm-memory.hpp
index 605d7c8..61b1c8a 100644
--- a/src/security/sec-tpm-memory.hpp
+++ b/src/security/sec-tpm-memory.hpp
@@ -16,8 +16,9 @@
namespace ndn {
/**
- * MemoryPrivateKeyStorage extends PrivateKeyStorage to implement a simple in-memory private key store. You should
- * initialize by calling setKeyPairForKeyName.
+ * @brief SecTpmMemory implements a simple in-memory TPM.
+ *
+ * You should initialize by calling setKeyPairForKeyName.
*/
class SecTpmMemory : public SecTpm {
public:
@@ -40,11 +41,13 @@
virtual void
setTpmPassword(const uint8_t* password, size_t passwordLength)
- {}
+ {
+ }
virtual void
resetTpmPassword()
- {}
+ {
+ }
virtual void
setInTerminal(bool inTerminal)
@@ -80,7 +83,8 @@
deleteKeyPairInTpm(const Name& keyName);
virtual Block
- signInTpm(const uint8_t* data, size_t dataLength, const Name& keyName, DigestAlgorithm digestAlgorithm);
+ signInTpm(const uint8_t* data, size_t dataLength,
+ const Name& keyName, DigestAlgorithm digestAlgorithm);
virtual ConstBufferPtr
decryptInTpm(const uint8_t* data, size_t dataLength, const Name& keyName, bool isSymmetric);
@@ -99,7 +103,8 @@
virtual void
addAppToACL(const Name& keyName, KeyClass keyClass, const std::string& appPath, AclType acl)
- {}
+ {
+ }
/******************************
* SecTpmMemory specific *
@@ -115,8 +120,8 @@
* @param privateKeyDerLength The length of privateKeyDer.
*/
void setKeyPairForKeyName(const Name& keyName,
- uint8_t* publicKeyDer, size_t publicKeyDerLength,
- uint8_t* privateKeyDer, size_t privateKeyDerLength);
+ const uint8_t* publicKeyDer, size_t publicKeyDerLength,
+ const uint8_t* privateKeyDer, size_t privateKeyDerLength);
protected:
/******************************
@@ -138,8 +143,8 @@
typedef std::map<std::string, shared_ptr<PublicKey> > PublicKeyStore;
typedef std::map<std::string, shared_ptr<RsaPrivateKey> > PrivateKeyStore;
- PublicKeyStore publicKeyStore_; /**< The map key is the keyName.toUri() */
- PrivateKeyStore privateKeyStore_; /**< The map key is the keyName.toUri() */
+ PublicKeyStore m_publicKeyStore; /**< The map key is the keyName.toUri() */
+ PrivateKeyStore m_privateKeyStore; /**< The map key is the keyName.toUri() */
bool m_inTerminal;
};
diff --git a/src/security/sec-tpm-osx.cpp b/src/security/sec-tpm-osx.cpp
index 6a5250c..d06cefe 100644
--- a/src/security/sec-tpm-osx.cpp
+++ b/src/security/sec-tpm-osx.cpp
@@ -10,7 +10,6 @@
#include "sec-tpm-osx.hpp"
#include "security/public-key.hpp"
-#include "util/logging.hpp"
#include "cryptopp.hpp"
#include <pwd.h>
@@ -27,8 +26,6 @@
using namespace std;
-INIT_LOGGER("ndn.SecTpmOsx");
-
namespace ndn {
class SecTpmOsx::Impl {
@@ -118,9 +115,9 @@
: m_impl(new Impl)
{
if (m_impl->m_inTerminal)
- SecKeychainSetUserInteractionAllowed (false);
+ SecKeychainSetUserInteractionAllowed(false);
else
- SecKeychainSetUserInteractionAllowed (true);
+ SecKeychainSetUserInteractionAllowed(true);
OSStatus res = SecKeychainCopyDefault(&m_impl->m_keyChainRef);
@@ -154,9 +151,9 @@
{
m_impl->m_inTerminal = inTerminal;
if (inTerminal)
- SecKeychainSetUserInteractionAllowed (false);
+ SecKeychainSetUserInteractionAllowed(false);
else
- SecKeychainSetUserInteractionAllowed (true);
+ SecKeychainSetUserInteractionAllowed(true);
}
bool
@@ -215,7 +212,7 @@
if (count > 2)
break;
- char* getPassword = NULL;
+ char* getPassword = 0;
getPassword = getpass(fmt);
count++;
@@ -243,29 +240,32 @@
}
void
-SecTpmOsx::generateKeyPairInTpmInternal(const Name& keyName, KeyType keyType, int keySize, bool retry)
+SecTpmOsx::generateKeyPairInTpmInternal(const Name& keyName, KeyType keyType,
+ int keySize, bool needRetry)
{
- if (doesKeyExistInTpm(keyName, KEY_CLASS_PUBLIC)){
- _LOG_DEBUG("keyName has existed");
- throw Error("keyName has existed");
- }
+ if (doesKeyExistInTpm(keyName, KEY_CLASS_PUBLIC))
+ {
+ throw Error("keyName has existed");
+ }
string keyNameUri = m_impl->toInternalKeyName(keyName, KEY_CLASS_PUBLIC);
SecKeyRef publicKey, privateKey;
- CFStringRef keyLabel = CFStringCreateWithCString(NULL,
+ CFStringRef keyLabel = CFStringCreateWithCString(0,
keyNameUri.c_str(),
kCFStringEncodingUTF8);
- CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(NULL,
+ CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(0,
3,
&kCFTypeDictionaryKeyCallBacks,
- NULL);
+ 0);
CFDictionaryAddValue(attrDict, kSecAttrKeyType, m_impl->getAsymKeyType(keyType));
- CFDictionaryAddValue(attrDict, kSecAttrKeySizeInBits, CFNumberCreate(NULL, kCFNumberIntType, &keySize));
+ CFDictionaryAddValue(attrDict, kSecAttrKeySizeInBits, CFNumberCreate(0,
+ kCFNumberIntType,
+ &keySize));
CFDictionaryAddValue(attrDict, kSecAttrLabel, keyLabel);
OSStatus res = SecKeyGeneratePair((CFDictionaryRef)attrDict, &publicKey, &privateKey);
@@ -277,7 +277,7 @@
return;
}
- if (res == errSecAuthFailed && !retry)
+ if (res == errSecAuthFailed && !needRetry)
{
if (unlockTpm(0, 0, false))
generateKeyPairInTpmInternal(keyName, keyType, keySize, true);
@@ -286,20 +286,21 @@
}
else
{
- _LOG_DEBUG("Fail to create a key pair: " << res);
throw Error("Fail to create a key pair");
}
}
void
-SecTpmOsx::deleteKeyPairInTpmInternal(const Name& keyName, bool retry)
+SecTpmOsx::deleteKeyPairInTpmInternal(const Name& keyName, bool needRetry)
{
- CFStringRef keyLabel = CFStringCreateWithCString(NULL,
+ CFStringRef keyLabel = CFStringCreateWithCString(0,
keyName.toUri().c_str(),
kCFStringEncodingUTF8);
CFMutableDictionaryRef searchDict =
- CFDictionaryCreateMutable(NULL, 5, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
+ CFDictionaryCreateMutable(0, 5,
+ &kCFTypeDictionaryKeyCallBacks,
+ &kCFTypeDictionaryValueCallBacks);
CFDictionaryAddValue(searchDict, kSecClass, kSecClassKey);
CFDictionaryAddValue(searchDict, kSecAttrLabel, keyLabel);
@@ -309,7 +310,7 @@
if (res == errSecSuccess)
return;
- if (res == errSecAuthFailed && !retry)
+ if (res == errSecAuthFailed && !needRetry)
{
if (unlockTpm(0, 0, false))
deleteKeyPairInTpmInternal(keyName, true);
@@ -330,16 +331,18 @@
// &kCFTypeDictionaryKeyCallBacks,
// &kCFTypeDictionaryValueCallBacks);
- // CFStringRef keyLabel = CFStringCreateWithCString(NULL,
+ // CFStringRef keyLabel = CFStringCreateWithCString(0,
// keyNameUri.c_str(),
// kCFStringEncodingUTF8);
// CFDictionaryAddValue(attrDict, kSecAttrKeyType, m_impl->getSymKeyType(keyType));
- // CFDictionaryAddValue(attrDict, kSecAttrKeySizeInBits, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &keySize));
+ // CFDictionaryAddValue(attrDict, kSecAttrKeySizeInBits, CFNumberCreate(kCFAllocatorDefault,
+ // kCFNumberSInt32Type,
+ // &keySize));
// CFDictionaryAddValue(attrDict, kSecAttrIsPermanent, kCFBooleanTrue);
// CFDictionaryAddValue(attrDict, kSecAttrLabel, keyLabel);
- // CFErrorRef error = NULL;
+ // CFErrorRef error = 0;
// SecKeyRef symmetricKey = SecKeyGenerateSymmetric(attrDict, &error);
@@ -350,8 +353,6 @@
shared_ptr<PublicKey>
SecTpmOsx::getPublicKeyFromTpm(const Name& keyName)
{
- _LOG_TRACE("OSXPrivateKeyStorage::getPublickey");
-
SecKeychainItemRef publicKey = m_impl->getKey(keyName, KEY_CLASS_PUBLIC);
CFDataRef exportedKey;
@@ -359,20 +360,21 @@
OSStatus res = SecItemExport(publicKey,
kSecFormatOpenSSL,
0,
- NULL,
+ 0,
&exportedKey);
if (res != errSecSuccess)
{
throw Error("Cannot export requested public key from OSX Keychain");
}
- shared_ptr<PublicKey> key = make_shared<PublicKey>(CFDataGetBytePtr(exportedKey), CFDataGetLength(exportedKey));
+ shared_ptr<PublicKey> key = make_shared<PublicKey>(CFDataGetBytePtr(exportedKey),
+ CFDataGetLength(exportedKey));
CFRelease(exportedKey);
return key;
}
ConstBufferPtr
-SecTpmOsx::exportPrivateKeyPkcs1FromTpmInternal(const Name& keyName, bool retry)
+SecTpmOsx::exportPrivateKeyPkcs1FromTpmInternal(const Name& keyName, bool needRetry)
{
using namespace CryptoPP;
@@ -381,12 +383,12 @@
OSStatus res = SecItemExport(privateKey,
kSecFormatOpenSSL,
0,
- NULL,
+ 0,
&exportedKey);
if (res != errSecSuccess)
{
- if (res == errSecAuthFailed && !retry)
+ if (res == errSecAuthFailed && !needRetry)
{
if (unlockTpm(0, 0, false))
return exportPrivateKeyPkcs1FromTpmInternal(keyName, true);
@@ -416,7 +418,9 @@
DEREncodeNull(privateKeyAlgorithm);
}
privateKeyAlgorithm.MessageEnd();
- DEREncodeOctetString(privateKeyInfo, CFDataGetBytePtr(exportedKey), CFDataGetLength(exportedKey));
+ DEREncodeOctetString(privateKeyInfo,
+ CFDataGetBytePtr(exportedKey),
+ CFDataGetLength(exportedKey));
}
privateKeyInfo.MessageEnd();
@@ -432,7 +436,9 @@
#endif // __GNUC__
bool
-SecTpmOsx::importPrivateKeyPkcs1IntoTpmInternal(const Name& keyName, const uint8_t* buf, size_t size, bool retry)
+SecTpmOsx::importPrivateKeyPkcs1IntoTpmInternal(const Name& keyName,
+ const uint8_t* buf, size_t size,
+ bool needRetry)
{
using namespace CryptoPP;
@@ -456,7 +462,7 @@
}
privateKeyInfo.MessageEnd();
- CFDataRef importedKey = CFDataCreateWithBytesNoCopy(NULL,
+ CFDataRef importedKey = CFDataCreateWithBytesNoCopy(0,
rawKeyBits.BytePtr(),
rawKeyBits.size(),
kCFAllocatorNull);
@@ -468,10 +474,10 @@
keyParams.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
keyParams.keyAttributes = CSSM_KEYATTR_EXTRACTABLE | CSSM_KEYATTR_PERMANENT;
SecAccessRef access;
- CFStringRef keyLabel = CFStringCreateWithCString(NULL,
+ CFStringRef keyLabel = CFStringCreateWithCString(0,
keyName.toUri().c_str(),
kCFStringEncodingUTF8);
- SecAccessCreate(keyLabel, NULL, &access);
+ SecAccessCreate(keyLabel, 0, &access);
keyParams.accessRef = access;
CFArrayRef outItems;
@@ -481,7 +487,7 @@
#endif // __clang__
OSStatus res = SecKeychainItemImport (importedKey,
- NULL,
+ 0,
&externalFormat,
&externalType,
0,
@@ -495,7 +501,7 @@
if (res != errSecSuccess)
{
- if (res == errSecAuthFailed && !retry)
+ if (res == errSecAuthFailed && !needRetry)
{
if (unlockTpm(0, 0, false))
return importPrivateKeyPkcs1IntoTpmInternal(keyName, buf, size, true);
@@ -520,7 +526,7 @@
res = SecKeychainItemModifyAttributesAndData(privateKey,
&attrList,
0,
- NULL);
+ 0);
if (res != errSecSuccess)
{
@@ -538,7 +544,7 @@
bool
SecTpmOsx::importPublicKeyPkcs1IntoTpm(const Name& keyName, const uint8_t* buf, size_t size)
{
- CFDataRef importedKey = CFDataCreateWithBytesNoCopy(NULL,
+ CFDataRef importedKey = CFDataCreateWithBytesNoCopy(0,
buf,
size,
kCFAllocatorNull);
@@ -548,11 +554,11 @@
CFArrayRef outItems;
OSStatus res = SecItemImport (importedKey,
- NULL,
+ 0,
&externalFormat,
&externalType,
0,
- NULL,
+ 0,
m_impl->m_keyChainRef,
&outItems);
@@ -573,7 +579,7 @@
res = SecKeychainItemModifyAttributesAndData(publicKey,
&attrList,
0,
- NULL);
+ 0);
if (res != errSecSuccess)
return false;
@@ -583,11 +589,10 @@
}
Block
-SecTpmOsx::signInTpmInternal(const uint8_t* data, size_t dataLength, const Name& keyName, DigestAlgorithm digestAlgorithm, bool retry)
+SecTpmOsx::signInTpmInternal(const uint8_t* data, size_t dataLength,
+ const Name& keyName, DigestAlgorithm digestAlgorithm, bool needRetry)
{
- _LOG_TRACE("OSXPrivateKeyStorage::Sign");
-
- CFDataRef dataRef = CFDataCreateWithBytesNoCopy(NULL,
+ CFDataRef dataRef = CFDataCreateWithBytesNoCopy(0,
data,
dataLength,
kCFAllocatorNull);
@@ -596,42 +601,47 @@
CFErrorRef error;
SecTransformRef signer = SecSignTransformCreate((SecKeyRef)privateKey, &error);
- if (error) throw Error("Fail to create signer");
+ if (error)
+ throw Error("Fail to create signer");
// Set input
Boolean set_res = SecTransformSetAttribute(signer,
kSecTransformInputAttributeName,
dataRef,
&error);
- if (error) throw Error("Fail to configure input of signer");
+ if (error)
+ throw Error("Fail to configure input of signer");
// Enable use of padding
SecTransformSetAttribute(signer,
kSecPaddingKey,
kSecPaddingPKCS1Key,
&error);
- if (error) throw Error("Fail to configure digest algorithm of signer");
+ if (error)
+ throw Error("Fail to configure digest algorithm of signer");
// Set padding type
set_res = SecTransformSetAttribute(signer,
kSecDigestTypeAttribute,
m_impl->getDigestAlgorithm(digestAlgorithm),
&error);
- if (error) throw Error("Fail to configure digest algorithm of signer");
+ if (error)
+ throw Error("Fail to configure digest algorithm of signer");
// Set padding attribute
long digestSize = m_impl->getDigestSize(digestAlgorithm);
set_res = SecTransformSetAttribute(signer,
kSecDigestLengthAttribute,
- CFNumberCreate(NULL, kCFNumberLongType, &digestSize),
+ CFNumberCreate(0, kCFNumberLongType, &digestSize),
&error);
- if (error) throw Error("Fail to configure digest size of signer");
+ if (error)
+ throw Error("Fail to configure digest size of signer");
// Actually sign
CFDataRef signature = (CFDataRef) SecTransformExecute(signer, &error);
if (error)
{
- if (!retry)
+ if (!needRetry)
{
if (unlockTpm(0, 0, false))
return signInTpmInternal(data, dataLength, keyName, digestAlgorithm, true);
@@ -645,7 +655,8 @@
}
}
- if (!signature) throw Error("Signature is NULL!\n");
+ if (!signature)
+ throw Error("Signature is NULL!\n");
return Block(Tlv::SignatureValue,
make_shared<Buffer>(CFDataGetBytePtr(signature), CFDataGetLength(signature)));
@@ -655,7 +666,6 @@
SecTpmOsx::decryptInTpm(const uint8_t* data, size_t dataLength, const Name& keyName, bool sym)
{
throw Error("SecTpmOsx::decryptInTpm is not supported");
- // _LOG_TRACE("OSXPrivateKeyStorage::Decrypt");
// KeyClass keyClass;
// if (sym)
@@ -663,17 +673,13 @@
// else
// keyClass = KEY_CLASS_PRIVATE;
- // CFDataRef dataRef = CFDataCreate(NULL,
+ // CFDataRef dataRef = CFDataCreate(0,
// reinterpret_cast<const unsigned char*>(data),
// dataLength
// );
- // // _LOG_DEBUG("CreateData");
-
// SecKeyRef decryptKey = (SecKeyRef)m_impl->getKey(keyName, keyClass);
- // // _LOG_DEBUG("GetKey");
-
// CFErrorRef error;
// SecTransformRef decrypt = SecDecryptTransformCreate(decryptKey, &error);
// if (error) throw Error("Fail to create decrypt");
@@ -718,7 +724,7 @@
&description,
&promptSelector);
- CFMutableArrayRef newAppList = CFArrayCreateMutableCopy(NULL,
+ CFMutableArrayRef newAppList = CFArrayCreateMutableCopy(0,
0,
appList);
@@ -741,7 +747,6 @@
SecTpmOsx::encryptInTpm(const uint8_t* data, size_t dataLength, const Name& keyName, bool sym)
{
throw Error("SecTpmOsx::encryptInTpm is not supported");
- // _LOG_TRACE("OSXPrivateKeyStorage::Encrypt");
// KeyClass keyClass;
// if (sym)
@@ -749,7 +754,7 @@
// else
// keyClass = KEY_CLASS_PUBLIC;
- // CFDataRef dataRef = CFDataCreate(NULL,
+ // CFDataRef dataRef = CFDataCreate(0,
// reinterpret_cast<const unsigned char*>(data),
// dataLength
// );
@@ -777,18 +782,16 @@
bool
SecTpmOsx::doesKeyExistInTpm(const Name& keyName, KeyClass keyClass)
{
- _LOG_TRACE("OSXPrivateKeyStorage::doesKeyExist");
-
string keyNameUri = m_impl->toInternalKeyName(keyName, keyClass);
- CFStringRef keyLabel = CFStringCreateWithCString(NULL,
+ CFStringRef keyLabel = CFStringCreateWithCString(0,
keyNameUri.c_str(),
kCFStringEncodingUTF8);
- CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(NULL,
+ CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(0,
4,
&kCFTypeDictionaryKeyCallBacks,
- NULL);
+ 0);
CFDictionaryAddValue(attrDict, kSecClass, kSecClassKey);
// CFDictionaryAddValue(attrDict, kSecAttrKeyClass, m_impl->getKeyClass(keyClass));
@@ -820,14 +823,14 @@
{
string keyNameUri = toInternalKeyName(keyName, keyClass);
- CFStringRef keyLabel = CFStringCreateWithCString(NULL,
+ CFStringRef keyLabel = CFStringCreateWithCString(0,
keyNameUri.c_str(),
kCFStringEncodingUTF8);
- CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(NULL,
+ CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(0,
5,
&kCFTypeDictionaryKeyCallBacks,
- NULL);
+ 0);
CFDictionaryAddValue(attrDict, kSecClass, kSecClassKey);
CFDictionaryAddValue(attrDict, kSecAttrLabel, keyLabel);
@@ -838,10 +841,8 @@
OSStatus res = SecItemCopyMatching((CFDictionaryRef) attrDict, (CFTypeRef*)&keyItem);
- if (res != errSecSuccess){
- _LOG_DEBUG("Fail to find the key!");
- return NULL;
- }
+ if (res != errSecSuccess)
+ return 0;
else
return keyItem;
}
@@ -864,8 +865,7 @@
case KEY_TYPE_RSA:
return kSecAttrKeyTypeRSA;
default:
- _LOG_DEBUG("Unrecognized key type!")
- return NULL;
+ return 0;
}
}
@@ -876,8 +876,7 @@
case KEY_TYPE_AES:
return kSecAttrKeyTypeAES;
default:
- _LOG_DEBUG("Unrecognized key type!")
- return NULL;
+ return 0;
}
}
@@ -892,8 +891,7 @@
case KEY_CLASS_SYMMETRIC:
return kSecAttrKeyClassSymmetric;
default:
- _LOG_DEBUG("Unrecognized key class!");
- return NULL;
+ return 0;
}
}
@@ -910,8 +908,7 @@
case DIGEST_ALGORITHM_SHA256:
return kSecDigestSHA2;
default:
- _LOG_DEBUG("Unrecognized digest algorithm!");
- return NULL;
+ return 0;
}
}
@@ -926,7 +923,6 @@
// case DIGEST_MD5:
// return 0;
default:
- _LOG_DEBUG("Unrecognized digest algorithm! Unknown digest size");
return -1;
}
}
diff --git a/src/security/sec-tpm-osx.hpp b/src/security/sec-tpm-osx.hpp
index 3dc6877..d6637ef 100644
--- a/src/security/sec-tpm-osx.hpp
+++ b/src/security/sec-tpm-osx.hpp
@@ -69,7 +69,8 @@
getPublicKeyFromTpm(const Name& keyName);
virtual Block
- signInTpm(const uint8_t* data, size_t dataLength, const Name& keyName, DigestAlgorithm digestAlgorithm)
+ signInTpm(const uint8_t* data, size_t dataLength,
+ const Name& keyName, DigestAlgorithm digestAlgorithm)
{
return signInTpmInternal(data, dataLength, keyName, digestAlgorithm, false);
}
@@ -115,19 +116,23 @@
* OSX-specifics *
******************************/
void
- generateKeyPairInTpmInternal(const Name& keyName, KeyType keyType, int keySize, bool retry);
+ generateKeyPairInTpmInternal(const Name& keyName, KeyType keyType, int keySize, bool needRetry);
void
- deleteKeyPairInTpmInternal(const Name& keyName, bool retry);
+ deleteKeyPairInTpmInternal(const Name& keyName, bool needRetry);
ConstBufferPtr
- exportPrivateKeyPkcs1FromTpmInternal(const Name& keyName, bool retry);
+ exportPrivateKeyPkcs1FromTpmInternal(const Name& keyName, bool needRetry);
bool
- importPrivateKeyPkcs1IntoTpmInternal(const Name& keyName, const uint8_t* buf, size_t size, bool retry);
+ importPrivateKeyPkcs1IntoTpmInternal(const Name& keyName,
+ const uint8_t* buf, size_t size,
+ bool needRetry);
Block
- signInTpmInternal(const uint8_t* data, size_t dataLength, const Name& keyName, DigestAlgorithm digestAlgorithm, bool retry);
+ signInTpmInternal(const uint8_t* data, size_t dataLength,
+ const Name& keyName, DigestAlgorithm digestAlgorithm,
+ bool needRetry);
private:
class Impl;
diff --git a/src/security/sec-tpm.cpp b/src/security/sec-tpm.cpp
index 3638ca1..d2e4af5 100644
--- a/src/security/sec-tpm.cpp
+++ b/src/security/sec-tpm.cpp
@@ -122,7 +122,8 @@
}
encryptionAlgorithm.MessageEnd();
- DEREncodeOctetString(encryptedPrivateKeyInfo, encryptedOs.buf()->buf(), encryptedOs.buf()->size());
+ DEREncodeOctetString(encryptedPrivateKeyInfo,
+ encryptedOs.buf()->buf(), encryptedOs.buf()->size());
}
encryptedPrivateKeyInfo.MessageEnd();
@@ -135,7 +136,9 @@
}
bool
-SecTpm::importPrivateKeyPkcs8IntoTpm(const Name& keyName, const uint8_t* buf, size_t size, const string& passwordStr)
+SecTpm::importPrivateKeyPkcs8IntoTpm(const Name& keyName,
+ const uint8_t* buf, size_t size,
+ const string& passwordStr)
{
using namespace CryptoPP;
@@ -149,7 +152,8 @@
try
{
- //decode some decoding processes are not necessary for now, because we assume only one encryption scheme.
+ // decode some decoding processes are not necessary for now,
+ // because we assume only one encryption scheme.
StringSource source(buf, size, true);
// EncryptedPrivateKeyInfo ::= SEQUENCE {
@@ -245,7 +249,8 @@
return false;
}
- if (!importPrivateKeyPkcs1IntoTpm(keyName, privateKeyOs.buf()->buf(), privateKeyOs.buf()->size()))
+ if (!importPrivateKeyPkcs1IntoTpm(keyName,
+ privateKeyOs.buf()->buf(), privateKeyOs.buf()->size()))
return false;
//derive public key
diff --git a/src/security/sec-tpm.hpp b/src/security/sec-tpm.hpp
index bb7e44b..15f1770 100644
--- a/src/security/sec-tpm.hpp
+++ b/src/security/sec-tpm.hpp
@@ -41,7 +41,8 @@
* @brief set password of TPM
*
* Password is used to unlock TPM when it is locked.
- * You should be cautious when using this method, because remembering password is kind of dangerous.
+ * You should be cautious when using this method, because remembering password is kind of
+ * dangerous.
*
* @param password The password.
* @param passwordLength The length of password.
@@ -133,7 +134,9 @@
* @throws SecTpm::Error if signing fails.
*/
virtual Block
- signInTpm(const uint8_t* data, size_t dataLength, const Name& keyName, DigestAlgorithm digestAlgorithm) = 0;
+ signInTpm(const uint8_t* data, size_t dataLength,
+ const Name& keyName,
+ DigestAlgorithm digestAlgorithm) = 0;
/**
* @brief Decrypt data.
@@ -176,7 +179,7 @@
* @brief 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.
+ * @param keyClass The class of the key, e.g. KEY_CLASS_PUBLIC, KEY_CLASS_PRIVATE.
* @return True if the key exists, otherwise false.
*/
virtual bool
@@ -225,7 +228,9 @@
* @return False if import fails.
*/
bool
- importPrivateKeyPkcs8IntoTpm(const Name& keyName, const uint8_t* buf, size_t size, const std::string& password);
+ importPrivateKeyPkcs8IntoTpm(const Name& keyName,
+ const uint8_t* buf, size_t size,
+ const std::string& password);
protected:
/**
diff --git a/src/security/secured-bag.hpp b/src/security/secured-bag.hpp
index 5848981..827225a 100644
--- a/src/security/secured-bag.hpp
+++ b/src/security/secured-bag.hpp
@@ -28,10 +28,11 @@
SecuredBag()
: m_wire(tlv::security::IdentityPackage)
- {}
+ {
+ }
SecuredBag(const IdentityCertificate& cert,
- ConstBufferPtr key)
+ ConstBufferPtr key)
: m_cert(cert)
, m_key(key)
, m_wire(tlv::security::IdentityPackage)
@@ -44,7 +45,8 @@
virtual
~SecuredBag()
- {}
+ {
+ }
void
wireDecode(const Block& wire)
diff --git a/src/security/validation-request.hpp b/src/security/validation-request.hpp
index 0bc0d59..8846636 100644
--- a/src/security/validation-request.hpp
+++ b/src/security/validation-request.hpp
@@ -12,25 +12,19 @@
#include "../interest.hpp"
namespace ndn {
-/**
- * An OnVerified function object is used to pass a callback to report a successful Interest validation.
- */
-typedef function< void (const shared_ptr<const Interest>&) > OnInterestValidated;
+/// @brief Callback to report a successful Interest validation.
+typedef function<void(const shared_ptr<const Interest>&)> OnInterestValidated;
-/**
- * An OnVerifyFailed function object is used to pass a callback to report a failed Interest validation.
- */
-typedef function< void (const shared_ptr<const Interest>&, const std::string&) > OnInterestValidationFailed;
+/// @brief Callback to report a failed Interest validation.
+typedef function<void(const shared_ptr<const Interest>&,
+ const std::string&)> OnInterestValidationFailed;
-/**
- * An OnVerified function object is used to pass a callback to report a successful Data validation.
- */
-typedef function< void (const shared_ptr<const Data>&) > OnDataValidated;
+/// @brief Callback to report a successful Data validation.
+typedef function<void(const shared_ptr<const Data>&)> OnDataValidated;
-/**
- * An OnVerifyFailed function object is used to pass a callback to report a failed Data validation.
- */
-typedef function< void (const shared_ptr<const Data>&, const std::string&) > OnDataValidationFailed;
+/// @brief Callback to report a failed Data validation.
+typedef function<void(const shared_ptr<const Data>&,
+ const std::string&)> OnDataValidationFailed;
class ValidationRequest {
@@ -38,22 +32,25 @@
ValidationRequest(const Interest& interest,
const OnDataValidated& onValidated,
const OnDataValidationFailed& onDataValidated,
- int retry, int stepCount)
- : m_interest(interest)
- , m_onValidated(onValidated)
- , m_onDataValidated(onDataValidated)
- , m_retry(retry)
- , m_stepCount(stepCount)
- {}
+ int nRetrials, int nSteps)
+ : m_interest(interest)
+ , m_onValidated(onValidated)
+ , m_onDataValidated(onDataValidated)
+ , m_nRetrials(nRetrials)
+ , m_nSteps(nSteps)
+ {
+ }
virtual
- ~ValidationRequest() {}
+ ~ValidationRequest()
+ {
+ }
- Interest m_interest; // An interest packet to fetch the requested data.
- OnDataValidated m_onValidated; // A callback function if the requested certificate is validated.
- OnDataValidationFailed m_onDataValidated; // A callback function if the requested certificate validation fails.
- int m_retry; // The number of retrials when there is an interest timeout.
- int m_stepCount; // The stepCount of next step.
+ Interest m_interest; // Interest for the requested data.
+ OnDataValidated m_onValidated; // Callback function on validated certificate.
+ OnDataValidationFailed m_onDataValidated; // Callback function on validation failure.
+ int m_nRetrials; // The number of retrials when interest timeout.
+ int m_nSteps; // The stepCount of next step.
};
} // namespace ndn
diff --git a/src/security/validator-config.cpp b/src/security/validator-config.cpp
index 3617772..f622ede 100644
--- a/src/security/validator-config.cpp
+++ b/src/security/validator-config.cpp
@@ -274,12 +274,12 @@
void
ValidatorConfig::checkPolicy(const Data& data,
- int stepCount,
+ int nSteps,
const OnDataValidated& onValidated,
const OnDataValidationFailed& onValidationFailed,
std::vector<shared_ptr<ValidationRequest> >& nextSteps)
{
- if (m_stepLimit == stepCount)
+ if (m_stepLimit == nSteps)
return onValidationFailed(data.shared_from_this(),
"Maximum steps of validation reached");
@@ -303,19 +303,19 @@
if (checkResult == 0)
{
const Signature& signature = data.getSignature();
- checkSignature(data, signature, stepCount,
+ checkSignature(data, signature, nSteps,
onValidated, onValidationFailed, nextSteps);
}
}
void
ValidatorConfig::checkPolicy(const Interest& interest,
- int stepCount,
+ int nSteps,
const OnInterestValidated& onValidated,
const OnInterestValidationFailed& onValidationFailed,
std::vector<shared_ptr<ValidationRequest> >& nextSteps)
{
- if (m_stepLimit == stepCount)
+ if (m_stepLimit == nSteps)
return onValidationFailed(interest.shared_from_this(),
"Maximum steps of validation reached");
@@ -343,7 +343,7 @@
Signature signature(interestName[-2].blockFromValue(),
interestName[-1].blockFromValue());
- checkSignature(interest, signature, stepCount,
+ checkSignature(interest, signature, nSteps,
onValidated, onValidationFailed, nextSteps);
}
}
diff --git a/src/security/validator-config.hpp b/src/security/validator-config.hpp
index feea4bf..9551fa5 100644
--- a/src/security/validator-config.hpp
+++ b/src/security/validator-config.hpp
@@ -54,14 +54,14 @@
protected:
virtual void
checkPolicy(const Data& data,
- int stepCount,
+ int nSteps,
const OnDataValidated& onValidated,
const OnDataValidationFailed& onValidationFailed,
std::vector<shared_ptr<ValidationRequest> >& nextSteps);
virtual void
checkPolicy(const Interest& interest,
- int stepCount,
+ int nSteps,
const OnInterestValidated& onValidated,
const OnInterestValidationFailed& onValidationFailed,
std::vector<shared_ptr<ValidationRequest> >& nextSteps);
@@ -71,7 +71,7 @@
void
checkSignature(const Packet& packet,
const Signature& signature,
- int stepCount,
+ int nSteps,
const OnValidated& onValidated,
const OnFailed& onValidationFailed,
std::vector<shared_ptr<ValidationRequest> >& nextSteps);
@@ -117,7 +117,7 @@
void
ValidatorConfig::checkSignature(const Packet& packet,
const Signature& signature,
- int stepCount,
+ int nSteps,
const OnValidated& onValidated,
const OnFailed& onValidationFailed,
std::vector<shared_ptr<ValidationRequest> >& nextSteps)
@@ -170,7 +170,7 @@
make_shared<ValidationRequest>(boost::cref(certInterest),
onCertValidated,
onCertValidationFailed,
- 1, stepCount + 1);
+ 1, nSteps + 1);
nextSteps.push_back(nextStep);
return;
diff --git a/src/security/validator-null.hpp b/src/security/validator-null.hpp
index 4d7b56b..f389d4c 100644
--- a/src/security/validator-null.hpp
+++ b/src/security/validator-null.hpp
@@ -17,24 +17,29 @@
public:
virtual
~ValidatorNull()
- {}
+ {
+ }
protected:
virtual void
- checkPolicy (const Data& data,
- int stepCount,
- const OnDataValidated& onValidated,
- const OnDataValidationFailed& onValidationFailed,
- std::vector<shared_ptr<ValidationRequest> >& nextSteps)
- { onValidated(data.shared_from_this()); }
+ checkPolicy(const Data& data,
+ int nSteps,
+ const OnDataValidated& onValidated,
+ const OnDataValidationFailed& onValidationFailed,
+ std::vector<shared_ptr<ValidationRequest> >& nextSteps)
+ {
+ onValidated(data.shared_from_this());
+ }
virtual void
- checkPolicy (const Interest& interest,
- int stepCount,
- const OnInterestValidated& onValidated,
- const OnInterestValidationFailed& onValidationFailed,
- std::vector<shared_ptr<ValidationRequest> >& nextSteps)
- { onValidated(interest.shared_from_this()); }
+ checkPolicy(const Interest& interest,
+ int nSteps,
+ const OnInterestValidated& onValidated,
+ const OnInterestValidationFailed& onValidationFailed,
+ std::vector<shared_ptr<ValidationRequest> >& nextSteps)
+ {
+ onValidated(interest.shared_from_this());
+ }
};
} // namespace ndn
diff --git a/src/security/validator-regex.cpp b/src/security/validator-regex.cpp
index 0f09741..48b9145 100644
--- a/src/security/validator-regex.cpp
+++ b/src/security/validator-regex.cpp
@@ -76,12 +76,12 @@
void
ValidatorRegex::checkPolicy(const Data& data,
- int stepCount,
+ int nSteps,
const OnDataValidated& onValidated,
const OnDataValidationFailed& onValidationFailed,
vector<shared_ptr<ValidationRequest> >& nextSteps)
{
- if (m_stepLimit == stepCount)
+ if (m_stepLimit == nSteps)
return onValidationFailed(data.shared_from_this(),
"Maximum steps of validation reached: " +
data.getName().toUri());
@@ -137,7 +137,7 @@
onKeyValidated,
onKeyValidationFailed,
3,
- stepCount + 1);
+ nSteps + 1);
nextSteps.push_back(nextStep);
diff --git a/src/security/validator-regex.hpp b/src/security/validator-regex.hpp
index 1124620..fddbb0a 100644
--- a/src/security/validator-regex.hpp
+++ b/src/security/validator-regex.hpp
@@ -59,14 +59,14 @@
protected:
virtual void
checkPolicy(const Data& data,
- int stepCount,
+ int nSteps,
const OnDataValidated& onValidated,
const OnDataValidationFailed& onValidationFailed,
std::vector<shared_ptr<ValidationRequest> >& nextSteps);
virtual void
checkPolicy(const Interest& interest,
- int stepCount,
+ int nSteps,
const OnInterestValidated& onValidated,
const OnInterestValidationFailed& onValidationFailed,
std::vector<shared_ptr<ValidationRequest> >& nextSteps)
diff --git a/src/security/validator.cpp b/src/security/validator.cpp
index cb5be23..029f766 100644
--- a/src/security/validator.cpp
+++ b/src/security/validator.cpp
@@ -9,16 +9,12 @@
#include "common.hpp"
#include "validator.hpp"
-#include "../util/logging.hpp"
#include "../util/crypto.hpp"
#include "cryptopp.hpp"
-
using namespace std;
-INIT_LOGGER("ndn.Validator");
-
namespace ndn {
const shared_ptr<Face> Validator::DEFAULT_FACE;
@@ -32,10 +28,10 @@
Validator::validate(const Interest& interest,
const OnInterestValidated& onValidated,
const OnInterestValidationFailed& onValidationFailed,
- int stepCount)
+ int nSteps)
{
vector<shared_ptr<ValidationRequest> > nextSteps;
- checkPolicy(interest, stepCount, onValidated, onValidationFailed, nextSteps);
+ checkPolicy(interest, nSteps, onValidated, onValidationFailed, nextSteps);
if (!nextSteps.empty())
{
@@ -48,7 +44,7 @@
m_face->expressInterest((*it)->m_interest,
bind(&Validator::onData, this, _1, _2, *it),
bind(&Validator::onTimeout,
- this, _1, (*it)->m_retry,
+ this, _1, (*it)->m_nRetrials,
onFailure,
*it));
}
@@ -64,10 +60,10 @@
Validator::validate(const Data& data,
const OnDataValidated& onValidated,
const OnDataValidationFailed& onValidationFailed,
- int stepCount)
+ int nSteps)
{
vector<shared_ptr<ValidationRequest> > nextSteps;
- checkPolicy(data, stepCount, onValidated, onValidationFailed, nextSteps);
+ checkPolicy(data, nSteps, onValidated, onValidationFailed, nextSteps);
if (!nextSteps.empty())
{
@@ -80,7 +76,7 @@
m_face->expressInterest((*it)->m_interest,
bind(&Validator::onData, this, _1, _2, *it),
bind(&Validator::onTimeout,
- this, _1, (*it)->m_retry,
+ this, _1, (*it)->m_nRetrials,
onFailure,
*it));
}
@@ -97,20 +93,21 @@
const Data& data,
const shared_ptr<ValidationRequest>& nextStep)
{
- validate(data, nextStep->m_onValidated, nextStep->m_onDataValidated, nextStep->m_stepCount);
+ validate(data, nextStep->m_onValidated, nextStep->m_onDataValidated, nextStep->m_nSteps);
}
void
Validator::onTimeout(const Interest& interest,
- int retry,
+ int nRetrials,
const OnFailure& onFailure,
const shared_ptr<ValidationRequest>& nextStep)
{
- if (retry > 0)
- // Issue the same expressInterest except decrement retry.
+ if (nRetrials > 0)
+ // Issue the same expressInterest except decrement nRetrials.
m_face->expressInterest(interest,
bind(&Validator::onData, this, _1, _2, nextStep),
- bind(&Validator::onTimeout, this, _1, retry - 1, onFailure, nextStep));
+ bind(&Validator::onTimeout, this, _1,
+ nRetrials - 1, onFailure, nextStep));
else
onFailure("Cannot fetch cert: " + interest.getName().toUri());
}
@@ -129,14 +126,12 @@
}
default:
{
- _LOG_DEBUG("verifySignature: Unknown signature type: " << data.getSignature().getType());
return false;
}
}
}
catch (const Signature::Error& e)
{
- _LOG_DEBUG("verifySignature: " << e.what());
return false;
}
return false;
@@ -169,19 +164,16 @@
}
default:
{
- _LOG_DEBUG("verifySignature: Unknown signature type: " << sig.getType());
return false;
}
}
}
catch (const Signature::Error& e)
{
- _LOG_DEBUG("verifySignature: " << e.what());
return false;
}
catch (const Block::Error& e)
{
- _LOG_DEBUG("verifySignature: " << e.what());
return false;
}
return false;
@@ -201,14 +193,12 @@
}
default:
{
- _LOG_DEBUG("verifySignature: Unknown signature type: " << sig.getType());
return false;
}
}
}
catch (const Signature::Error& e)
{
- _LOG_DEBUG("verifySignature: " << e.what());
return false;
}
return false;
@@ -237,7 +227,6 @@
}
catch (const CryptoPP::Exception& e)
{
- _LOG_DEBUG("verifySignature: " << e.what());
return false;
}
}
@@ -265,7 +254,6 @@
}
catch (const CryptoPP::Exception& e)
{
- _LOG_DEBUG("verifySignature: " << e.what());
return false;
}
}
diff --git a/src/security/validator.hpp b/src/security/validator.hpp
index 32a5ab6..e65d7a8 100644
--- a/src/security/validator.hpp
+++ b/src/security/validator.hpp
@@ -46,7 +46,7 @@
*
* @param data The Data with the signature to check.
* @param onValidated If the Data is validated, this calls onValidated(data).
- * @param onValidationFailed If the Data validation fails, this calls onValidationFailed(data).
+ * @param onValidationFailed If validation fails, this calls onValidationFailed(data).
*/
void
validate(const Data& data,
@@ -61,7 +61,7 @@
*
* @param interest The Interest with the signature to check.
* @param onValidated If the Interest is validated, this calls onValidated(interest).
- * @param onValidationFailed If the Interest validation fails, this calls onValidationFailed(interest).
+ * @param onValidationFailed If validation fails, this calls onValidationFailed(interest).
*/
void
validate(const Interest& interest,
@@ -185,39 +185,40 @@
* i.e., either onValidated or onValidationFailed callback is invoked.
*
* @param data The Data to check.
- * @param stepCount The number of validation steps that have been done, used to track the validation progress.
+ * @param nSteps The number of validation steps that have been done.
* @param onDataValidated If the Data is validated, this calls onValidated(data).
- * @param onDataValidationFailed If the Data validation fails, this calls onValidationFailed(data).
+ * @param onDataValidationFailed If validation fails, this calls onValidationFailed(data).
* @param nextSteps On return, contains the next validation step.
*/
virtual void
checkPolicy(const Data& data,
- int stepCount,
+ int nSteps,
const OnDataValidated& onValidated,
const OnDataValidationFailed& onValidationFailed,
std::vector<shared_ptr<ValidationRequest> >& nextSteps) = 0;
/**
- * @brief Check the Interest against validation policy and return the next validation step if necessary.
+ * @brief Check the Interest against validation policy and return the next validation step
+ * if necessary.
*
* If there is no next validation step, that validation MUST have been done.
* i.e., either onValidated or onValidationFailed callback is invoked.
*
* @param data The Interest to check.
- * @param stepCount The number of validation steps that have been done, used to track the validation progress.
+ * @param nSteps The number of validation steps that have been done.
* @param OnInterestValidated If the Interest is validated, this calls onValidated(data).
- * @param OnInterestValidationFailed If the Interest validation fails, this calls onValidationFailed(data).
+ * @param OnInterestValidationFailed If validation fails, this calls onValidationFailed(data).
* @return the indication of next validation step, null if there is no further step.
*/
virtual void
checkPolicy(const Interest& interest,
- int stepCount,
+ int nSteps,
const OnInterestValidated& onValidated,
const OnInterestValidationFailed& onValidationFailed,
std::vector<shared_ptr<ValidationRequest> >& nextSteps) = 0;
private:
- typedef function< void (const std::string&) > OnFailure;
+ typedef function<void(const std::string&)> OnFailure;
/// @brief Process the received certificate.
void
@@ -236,13 +237,13 @@
validate(const Data& data,
const OnDataValidated& onValidated,
const OnDataValidationFailed& onValidationFailed,
- int stepCount);
+ int nSteps);
void
validate(const Interest& interest,
const OnInterestValidated& onValidated,
const OnInterestValidationFailed& onValidationFailed,
- int stepCount);
+ int nSteps);
protected:
shared_ptr<Face> m_face;