security: change enum to enum class in security-common.hpp
Change-Id: I5565c845cd57f3457c8120b11399a105fa83418d
Refs: #3083
diff --git a/src/security/certificate.cpp b/src/security/certificate.cpp
index 02916a9..1b004ed 100644
--- a/src/security/certificate.cpp
+++ b/src/security/certificate.cpp
@@ -1,6 +1,6 @@
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
- * Copyright (c) 2013-2015 Regents of the University of California.
+ * Copyright (c) 2013-2016 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
@@ -284,10 +284,10 @@
os << "Public key bits: ";
switch (m_key.getKeyType()) {
- case KEY_TYPE_RSA:
+ case KeyType::RSA:
os << "(RSA)";
break;
- case KEY_TYPE_ECDSA:
+ case KeyType::EC:
os << "(ECDSA)";
break;
default:
diff --git a/src/security/detail/openssl-helper.cpp b/src/security/detail/openssl-helper.cpp
index 25fddc7..ce51d1b 100644
--- a/src/security/detail/openssl-helper.cpp
+++ b/src/security/detail/openssl-helper.cpp
@@ -29,7 +29,7 @@
toDigestEvpMd(DigestAlgorithm algo)
{
switch (algo) {
- case DIGEST_ALGORITHM_SHA256:
+ case DigestAlgorithm::SHA256:
return EVP_sha256();
default:
return nullptr;
diff --git a/src/security/key-chain.cpp b/src/security/key-chain.cpp
index e6b1ff0..8369cb1 100644
--- a/src/security/key-chain.cpp
+++ b/src/security/key-chain.cpp
@@ -533,7 +533,7 @@
Name keyName;
SignatureInfo sigInfo;
std::tie(keyName, sigInfo) = prepareSignatureInfo(params);
- return pureSign(buffer, bufferLength, keyName, DIGEST_ALGORITHM_SHA256);
+ return pureSign(buffer, bufferLength, keyName, DigestAlgorithm::SHA256);
}
Signature
@@ -550,7 +550,7 @@
// For temporary usage, we support SHA256 only, but will support more.
sig.setValue(m_tpm->signInTpm(buffer, bufferLength,
certificate->getPublicKeyName(),
- DIGEST_ALGORITHM_SHA256));
+ DigestAlgorithm::SHA256));
return sig;
}
@@ -589,15 +589,16 @@
KeyChain::selfSign(IdentityCertificate& cert)
{
Name keyName = cert.getPublicKeyName();
- if (!m_tpm->doesKeyExistInTpm(keyName, KEY_CLASS_PRIVATE))
+
+ if (!m_tpm->doesKeyExistInTpm(keyName, KeyClass::PRIVATE))
BOOST_THROW_EXCEPTION(SecTpm::Error("Private key does not exist"));
SignatureInfo sigInfo(cert.getSignature().getInfo());
sigInfo.setKeyLocator(KeyLocator(cert.getName().getPrefix(-1)));
sigInfo.setSignatureType(getSignatureType(cert.getPublicKeyInfo().getKeyType(),
- DIGEST_ALGORITHM_SHA256));
+ DigestAlgorithm::SHA256));
- signPacketWrapper(cert, Signature(sigInfo), keyName, DIGEST_ALGORITHM_SHA256);
+ signPacketWrapper(cert, Signature(sigInfo), keyName, DigestAlgorithm::SHA256);
}
shared_ptr<SecuredBag>
@@ -657,7 +658,7 @@
const KeyParams&
KeyChain::getDefaultKeyParamsForIdentity(const Name &identityName) const
{
- KeyType keyType = KEY_TYPE_NULL;
+ KeyType keyType = KeyType::NONE;
try {
keyType = m_pib->getPublicKeyType(m_pib->getDefaultKeyNameForIdentity(identityName));
}
@@ -666,15 +667,15 @@
}
switch (keyType) {
- case KEY_TYPE_RSA: {
+ case KeyType::RSA: {
static RsaKeyParams defaultRsaParams;
return defaultRsaParams;
}
- case KEY_TYPE_ECDSA: {
+ case KeyType::EC: {
static EcdsaKeyParams defaultEcdsaParams;
return defaultEcdsaParams;
}
- case KEY_TYPE_NULL: {
+ case KeyType::NONE: {
return DEFAULT_KEY_PARAMS;
}
default:
@@ -833,9 +834,9 @@
KeyChain::getSignatureType(KeyType keyType, DigestAlgorithm digestAlgorithm)
{
switch (keyType) {
- case KEY_TYPE_RSA:
+ case KeyType::RSA:
return tlv::SignatureSha256WithRsa;
- case KEY_TYPE_ECDSA:
+ case KeyType::EC:
return tlv::SignatureSha256WithEcdsa;
default:
BOOST_THROW_EXCEPTION(Error("Unsupported key types"));
diff --git a/src/security/key-params.hpp b/src/security/key-params.hpp
index a82ace0..9769270 100644
--- a/src/security/key-params.hpp
+++ b/src/security/key-params.hpp
@@ -1,6 +1,6 @@
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
- * Copyright (c) 2013-2015 Regents of the University of California.
+ * Copyright (c) 2013-2016 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
@@ -75,7 +75,7 @@
static KeyType
getType()
{
- return KEY_TYPE_RSA;
+ return KeyType::RSA;
}
/// @brief check if size is qualified, otherwise return the default key size.
@@ -93,7 +93,7 @@
static KeyType
getType()
{
- return KEY_TYPE_ECDSA;
+ return KeyType::EC;
}
/// @brief check if size is qualified, otherwise return the default key size.
@@ -168,7 +168,7 @@
static KeyType
getType()
{
- return KEY_TYPE_AES;
+ return KeyType::AES;
}
/// @brief check if size is qualified, otherwise return the default key size.
diff --git a/src/security/pib-sqlite3.cpp b/src/security/pib-sqlite3.cpp
index 01e80f7..cbded5b 100644
--- a/src/security/pib-sqlite3.cpp
+++ b/src/security/pib-sqlite3.cpp
@@ -377,7 +377,7 @@
"VALUES ((SELECT id FROM identities WHERE identity=?), ?, ?, ?)");
statement.bind(1, identity.wireEncode(), SQLITE_TRANSIENT);
statement.bind(2, keyName.wireEncode(), SQLITE_TRANSIENT);
- statement.bind(3, publicKey.getKeyType());
+ statement.bind(3, static_cast<int>(publicKey.getKeyType()));
statement.bind(4, publicKey.get().buf(), publicKey.get().size(), SQLITE_STATIC);
statement.step();
}
diff --git a/src/security/public-key.cpp b/src/security/public-key.cpp
index 78f2a7f..e366a47 100644
--- a/src/security/public-key.cpp
+++ b/src/security/public-key.cpp
@@ -1,6 +1,6 @@
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
- * Copyright (c) 2013-2015 Regents of the University of California.
+ * Copyright (c) 2013-2016 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
@@ -31,12 +31,12 @@
namespace ndn {
PublicKey::PublicKey()
- : m_type(KEY_TYPE_NULL)
+ : m_type(KeyType::NONE)
{
}
PublicKey::PublicKey(const uint8_t* keyDerBuf, size_t keyDerSize)
- : m_type(KEY_TYPE_NULL)
+ : m_type(KeyType::NONE)
{
CryptoPP::StringSource src(keyDerBuf, keyDerSize, true);
decode(src);
@@ -106,9 +106,9 @@
algorithm.decode(algorithmInfo);
if (algorithm == oid::RSA)
- m_type = KEY_TYPE_RSA;
+ m_type = KeyType::RSA;
else if (algorithm == oid::ECDSA)
- m_type = KEY_TYPE_ECDSA;
+ m_type = KeyType::EC;
else
BOOST_THROW_EXCEPTION(Error("Only RSA/ECDSA public keys are supported for now (" +
algorithm.toString() + " requested)"));
@@ -119,7 +119,7 @@
}
catch (CryptoPP::BERDecodeErr& err)
{
- m_type = KEY_TYPE_NULL;
+ m_type = KeyType::NONE;
BOOST_THROW_EXCEPTION(Error("PublicKey decoding error"));
}
@@ -129,7 +129,7 @@
// Blob
// PublicKey::getDigest(DigestAlgorithm digestAlgorithm) const
// {
-// if (digestAlgorithm == DIGEST_ALGORITHM_SHA256) {
+// if (digestAlgorithm == DigestAlgorithm::SHA256) {
// uint8_t digest[SHA256_DIGEST_LENGTH];
// ndn_digestSha256(keyDer_.buf(), keyDer_.size(), digest);
diff --git a/src/security/sec-public-info-sqlite3.cpp b/src/security/sec-public-info-sqlite3.cpp
index 9974336..1be311f 100644
--- a/src/security/sec-public-info-sqlite3.cpp
+++ b/src/security/sec-public-info-sqlite3.cpp
@@ -385,7 +385,7 @@
sqlite3_bind_string(statement, 1, identityName.toUri(), SQLITE_TRANSIENT);
sqlite3_bind_string(statement, 2, keyId, SQLITE_TRANSIENT);
- sqlite3_bind_int(statement, 3, publicKeyDer.getKeyType());
+ sqlite3_bind_int(statement, 3, static_cast<int>(publicKeyDer.getKeyType()));
sqlite3_bind_blob(statement, 4,
publicKeyDer.get().buf(),
publicKeyDer.get().size(),
@@ -432,7 +432,7 @@
SecPublicInfoSqlite3::getPublicKeyType(const Name& keyName)
{
if (keyName.empty())
- return KEY_TYPE_NULL;
+ return KeyType::NONE;
string keyId = keyName.get(-1).toUri();
Name identityName = keyName.getPrefix(-1);
@@ -454,7 +454,7 @@
}
else {
sqlite3_finalize(statement);
- return KEY_TYPE_NULL;
+ return KeyType::NONE;
}
}
diff --git a/src/security/sec-public-info.hpp b/src/security/sec-public-info.hpp
index 3e698fa..c4b7175 100644
--- a/src/security/sec-public-info.hpp
+++ b/src/security/sec-public-info.hpp
@@ -1,6 +1,6 @@
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
- * Copyright (c) 2013-2015 Regents of the University of California.
+ * Copyright (c) 2013-2016 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
@@ -159,7 +159,7 @@
* This method is more efficient if only KeyType is needed.
*
* @param keyName The name of the requested public key
- * @return the type of the key. If the queried key does not exist, KEY_TYPE_NULL will be returned
+ * @return the type of the key. If the queried key does not exist, KeyType::NONE will be returned
*/
virtual KeyType
getPublicKeyType(const Name& keyName) = 0;
diff --git a/src/security/sec-tpm-file.cpp b/src/security/sec-tpm-file.cpp
index 306a062..adb5938 100644
--- a/src/security/sec-tpm-file.cpp
+++ b/src/security/sec-tpm-file.cpp
@@ -127,99 +127,95 @@
{
string keyURI = keyName.toUri();
- if (doesKeyExistInTpm(keyName, KEY_CLASS_PUBLIC))
+ if (doesKeyExistInTpm(keyName, KeyClass::PUBLIC))
BOOST_THROW_EXCEPTION(Error("public key exists"));
- if (doesKeyExistInTpm(keyName, KEY_CLASS_PRIVATE))
+ if (doesKeyExistInTpm(keyName, KeyClass::PRIVATE))
BOOST_THROW_EXCEPTION(Error("private key exists"));
string keyFileName = m_impl->maintainMapping(keyURI);
- try
- {
- switch (params.getKeyType())
- {
- case KEY_TYPE_RSA:
- {
- using namespace CryptoPP;
+ try {
+ switch (params.getKeyType()) {
+ case KeyType::RSA: {
+ using namespace CryptoPP;
- const RsaKeyParams& rsaParams = static_cast<const RsaKeyParams&>(params);
- AutoSeededRandomPool rng;
- InvertibleRSAFunction privateKey;
- privateKey.Initialize(rng, rsaParams.getKeySize());
+ const RsaKeyParams& rsaParams = static_cast<const RsaKeyParams&>(params);
+ AutoSeededRandomPool rng;
+ InvertibleRSAFunction privateKey;
+ privateKey.Initialize(rng, rsaParams.getKeySize());
- 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;
- }
- case KEY_TYPE_ECDSA:
- {
- using namespace CryptoPP;
+ // set file permission
+ chmod(privateKeyFileName.c_str(), 0000400);
+ chmod(publicKeyFileName.c_str(), 0000444);
+ return;
+ }
- const EcdsaKeyParams& ecdsaParams = static_cast<const EcdsaKeyParams&>(params);
+ case KeyType::EC: {
+ using namespace CryptoPP;
- CryptoPP::OID curveName;
- switch (ecdsaParams.getKeySize())
- {
- case 256:
- curveName = ASN1::secp256r1();
- break;
- case 384:
- curveName = ASN1::secp384r1();
- break;
- default:
- curveName = ASN1::secp256r1();
- }
+ const EcdsaKeyParams& ecdsaParams = static_cast<const EcdsaKeyParams&>(params);
- AutoSeededRandomPool rng;
-
- ECDSA<ECP, SHA256>::PrivateKey privateKey;
- DL_GroupParameters_EC<ECP> cryptoParams(curveName);
- cryptoParams.SetEncodeAsOID(true);
- privateKey.Initialize(rng, cryptoParams);
-
- ECDSA<ECP, SHA256>::PublicKey publicKey;
- privateKey.MakePublicKey(publicKey);
- publicKey.AccessGroupParameters().SetEncodeAsOID(true);
-
- string privateKeyFileName = keyFileName + ".pri";
- Base64Encoder privateKeySink(new FileSink(privateKeyFileName.c_str()));
- privateKey.DEREncode(privateKeySink);
- privateKeySink.MessageEnd();
-
- string publicKeyFileName = keyFileName + ".pub";
- Base64Encoder publicKeySink(new FileSink(publicKeyFileName.c_str()));
- publicKey.Save(publicKeySink);
- publicKeySink.MessageEnd();
-
- /*set file permission*/
- chmod(privateKeyFileName.c_str(), 0000400);
- chmod(publicKeyFileName.c_str(), 0000444);
- return;
- }
+ CryptoPP::OID curveName;
+ switch (ecdsaParams.getKeySize()) {
+ case 256:
+ curveName = ASN1::secp256r1();
+ break;
+ case 384:
+ curveName = ASN1::secp384r1();
+ break;
default:
- BOOST_THROW_EXCEPTION(Error("Unsupported key type"));
+ curveName = ASN1::secp256r1();
+ break;
}
+
+ AutoSeededRandomPool rng;
+
+ ECDSA<ECP, SHA256>::PrivateKey privateKey;
+ DL_GroupParameters_EC<ECP> cryptoParams(curveName);
+ cryptoParams.SetEncodeAsOID(true);
+ privateKey.Initialize(rng, cryptoParams);
+
+ ECDSA<ECP, SHA256>::PublicKey publicKey;
+ privateKey.MakePublicKey(publicKey);
+ publicKey.AccessGroupParameters().SetEncodeAsOID(true);
+
+ string privateKeyFileName = keyFileName + ".pri";
+ Base64Encoder privateKeySink(new FileSink(privateKeyFileName.c_str()));
+ privateKey.DEREncode(privateKeySink);
+ privateKeySink.MessageEnd();
+
+ string publicKeyFileName = keyFileName + ".pub";
+ Base64Encoder publicKeySink(new FileSink(publicKeyFileName.c_str()));
+ publicKey.Save(publicKeySink);
+ publicKeySink.MessageEnd();
+
+ // set file permission
+ chmod(privateKeyFileName.c_str(), 0000400);
+ chmod(publicKeyFileName.c_str(), 0000444);
+ return;
+ }
+
+ default:
+ BOOST_THROW_EXCEPTION(Error("Unsupported key type"));
}
- catch (KeyParams::Error& e)
- {
- BOOST_THROW_EXCEPTION(Error(e.what()));
- }
- catch (CryptoPP::Exception& e)
- {
- BOOST_THROW_EXCEPTION(Error(e.what()));
- }
+ }
+ catch (const KeyParams::Error& e) {
+ BOOST_THROW_EXCEPTION(Error(e.what()));
+ }
+ catch (const CryptoPP::Exception& e) {
+ BOOST_THROW_EXCEPTION(Error(e.what()));
+ }
}
void
@@ -240,21 +236,19 @@
{
string keyURI = keyName.toUri();
- if (!doesKeyExistInTpm(keyName, KEY_CLASS_PUBLIC))
+ if (!doesKeyExistInTpm(keyName, KeyClass::PUBLIC))
BOOST_THROW_EXCEPTION(Error("Public Key does not exist"));
ostringstream os;
- try
- {
- using namespace CryptoPP;
- FileSource(m_impl->transformName(keyURI, ".pub").string().c_str(),
- true,
- new Base64Decoder(new FileSink(os)));
- }
- catch (CryptoPP::Exception& e)
- {
- BOOST_THROW_EXCEPTION(Error(e.what()));
- }
+ try {
+ using namespace CryptoPP;
+ FileSource(m_impl->transformName(keyURI, ".pub").string().c_str(),
+ true,
+ new Base64Decoder(new FileSink(os)));
+ }
+ catch (const CryptoPP::Exception& e) {
+ BOOST_THROW_EXCEPTION(Error(e.what()));
+ }
return make_shared<PublicKey>(reinterpret_cast<const uint8_t*>(os.str().c_str()),
os.str().size());
@@ -279,41 +273,37 @@
bool
SecTpmFile::importPrivateKeyPkcs8IntoTpm(const Name& keyName, const uint8_t* buf, size_t size)
{
- try
- {
- using namespace CryptoPP;
+ 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 (CryptoPP::Exception& e)
- {
- return false;
- }
+ 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
- {
- using namespace CryptoPP;
+ 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 (CryptoPP::Exception& e)
- {
- return false;
- }
+ 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
@@ -322,93 +312,88 @@
{
string keyURI = keyName.toUri();
- if (!doesKeyExistInTpm(keyName, KEY_CLASS_PRIVATE))
+ if (!doesKeyExistInTpm(keyName, KeyClass::PRIVATE))
BOOST_THROW_EXCEPTION(Error("private key doesn't exist"));
- try
- {
- using namespace CryptoPP;
- AutoSeededRandomPool rng;
+ try {
+ using namespace CryptoPP;
+ AutoSeededRandomPool rng;
- //Read public key
- shared_ptr<PublicKey> pubkeyPtr;
- pubkeyPtr = getPublicKeyFromTpm(keyName);
+ // Read public key
+ shared_ptr<PublicKey> pubkeyPtr;
+ pubkeyPtr = getPublicKeyFromTpm(keyName);
- switch (pubkeyPtr->getKeyType())
- {
- case KEY_TYPE_RSA:
- {
- //Read private key
- ByteQueue bytes;
- FileSource file(m_impl->transformName(keyURI, ".pri").string().c_str(),
- true, new Base64Decoder);
- file.TransferTo(bytes);
- bytes.MessageEnd();
- RSA::PrivateKey privateKey;
- privateKey.Load(bytes);
+ switch (pubkeyPtr->getKeyType()) {
+ case KeyType::RSA: {
+ // Read private key
+ ByteQueue bytes;
+ FileSource file(m_impl->transformName(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 DigestAlgorithm::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:
- BOOST_THROW_EXCEPTION(Error("Unsupported digest algorithm"));
- }
- }
- case KEY_TYPE_ECDSA:
- {
- //Read private key
- ByteQueue bytes;
- FileSource file(m_impl->transformName(keyURI, ".pri").string().c_str(),
- true, new Base64Decoder);
- file.TransferTo(bytes);
- bytes.MessageEnd();
-
- //Sign message
- switch (digestAlgorithm)
- {
- case DIGEST_ALGORITHM_SHA256:
- {
- ECDSA<ECP, SHA256>::PrivateKey privateKey;
- privateKey.Load(bytes);
- ECDSA<ECP, SHA256>::Signer signer(privateKey);
-
- OBufferStream os;
- StringSource(data, dataLength,
- true,
- new SignerFilter(rng, signer, new FileSink(os)));
-
- uint8_t buf[200];
- size_t bufSize = DSAConvertSignatureFormat(buf, 200, DSA_DER,
- os.buf()->buf(), os.buf()->size(),
- DSA_P1363);
-
- shared_ptr<Buffer> sigBuffer = make_shared<Buffer>(buf, bufSize);
-
- return Block(tlv::SignatureValue, sigBuffer);
- }
- default:
- BOOST_THROW_EXCEPTION(Error("Unsupported digest algorithm"));
- }
+ return Block(tlv::SignatureValue, os.buf());
}
- default:
- BOOST_THROW_EXCEPTION(Error("Unsupported key type"));
+
+ default:
+ BOOST_THROW_EXCEPTION(Error("Unsupported digest algorithm"));
}
+ }
+
+ case KeyType::EC: {
+ // Read private key
+ ByteQueue bytes;
+ FileSource file(m_impl->transformName(keyURI, ".pri").string().c_str(),
+ true, new Base64Decoder);
+ file.TransferTo(bytes);
+ bytes.MessageEnd();
+
+ // Sign message
+ switch (digestAlgorithm) {
+ case DigestAlgorithm::SHA256: {
+ ECDSA<ECP, SHA256>::PrivateKey privateKey;
+ privateKey.Load(bytes);
+ ECDSA<ECP, SHA256>::Signer signer(privateKey);
+
+ OBufferStream os;
+ StringSource(data, dataLength,
+ true,
+ new SignerFilter(rng, signer, new FileSink(os)));
+
+ uint8_t buf[200];
+ size_t bufSize = DSAConvertSignatureFormat(buf, sizeof(buf), DSA_DER,
+ os.buf()->buf(), os.buf()->size(),
+ DSA_P1363);
+
+ shared_ptr<Buffer> sigBuffer = make_shared<Buffer>(buf, bufSize);
+
+ return Block(tlv::SignatureValue, sigBuffer);
+ }
+
+ default:
+ BOOST_THROW_EXCEPTION(Error("Unsupported digest algorithm"));
+ }
+ }
+
+ default:
+ BOOST_THROW_EXCEPTION(Error("Unsupported key type"));
}
- catch (CryptoPP::Exception& e)
- {
- BOOST_THROW_EXCEPTION(Error(e.what()));
- }
+ }
+ catch (const CryptoPP::Exception& e) {
+ BOOST_THROW_EXCEPTION(Error(e.what()));
+ }
}
@@ -420,7 +405,7 @@
// string keyURI = keyName.toUri();
// if (!isSymmetric)
// {
- // if (!doesKeyExistInTpm(keyName, KEY_CLASS_PRIVATE))
+ // if (!doesKeyExistInTpm(keyName, KeyClass::PRIVATE))
// throw Error("private key doesn't exist");
// try{
@@ -441,14 +426,14 @@
// return os.buf();
// }
- // catch (CryptoPP::Exception& e){
+ // catch (const CryptoPP::Exception& e){
// throw Error(e.what());
// }
// }
// else
// {
// throw Error("Symmetric encryption is not implemented!");
- // // if (!doesKeyExistInTpm(keyName, KEY_CLASS_SYMMETRIC))
+ // // if (!doesKeyExistInTpm(keyName, KeyClass::SYMMETRIC))
// // throw Error("symmetric key doesn't exist");
// // try{
@@ -468,7 +453,8 @@
// // StringSource(data, dataLength, true, new StreamTransformationFilter(decryptor,new FileSink(os)));
// // return os.buf();
- // // }catch (CryptoPP::Exception& e){
+ // // }
+ // // catch (const CryptoPP::Exception& e){
// // throw Error(e.what());
// // }
// }
@@ -483,7 +469,7 @@
// if (!isSymmetric)
// {
- // if (!doesKeyExistInTpm(keyName, KEY_CLASS_PUBLIC))
+ // if (!doesKeyExistInTpm(keyName, KeyClass::PUBLIC))
// throw Error("public key doesn't exist");
// try
// {
@@ -504,14 +490,14 @@
// StringSource(data, dataLength, true, new PK_EncryptorFilter(rng, encryptor, new FileSink(os)));
// return os.buf();
// }
- // catch (CryptoPP::Exception& e){
+ // catch (const CryptoPP::Exception& e){
// throw Error(e.what());
// }
// }
// else
// {
// throw Error("Symmetric encryption is not implemented!");
- // // if (!doesKeyExistInTpm(keyName, KEY_CLASS_SYMMETRIC))
+ // // if (!doesKeyExistInTpm(keyName, KeyClass::SYMMETRIC))
// // throw Error("symmetric key doesn't exist");
// // try{
@@ -530,7 +516,7 @@
// // OBufferStream os;
// // StringSource(data, dataLength, true, new StreamTransformationFilter(encryptor, new FileSink(os)));
// // return os.buf();
- // // }catch (CryptoPP::Exception& e){
+ // // } catch (const CryptoPP::Exception& e){
// // throw Error(e.what());
// // }
// }
@@ -542,7 +528,7 @@
BOOST_THROW_EXCEPTION(Error("SecTpmFile::generateSymmetricKeyInTpm is not supported"));
// string keyURI = keyName.toUri();
- // if (doesKeyExistInTpm(keyName, KEY_CLASS_SYMMETRIC))
+ // if (doesKeyExistInTpm(keyName, KeyClass::SYMMETRIC))
// throw Error("symmetric key exists");
// string keyFileName = m_impl->maintainMapping(keyURI);
@@ -550,7 +536,7 @@
// try{
// switch (keyType){
- // case KEY_TYPE_AES:
+ // case KeyType::AES:
// {
// using namespace CryptoPP;
// AutoSeededRandomPool rng;
@@ -566,7 +552,7 @@
// default:
// throw Error("Unsupported symmetric key type!");
// }
- // }catch (CryptoPP::Exception& e){
+ // } catch (const CryptoPP::Exception& e){
// throw Error(e.what());
// }
}
@@ -575,43 +561,29 @@
SecTpmFile::doesKeyExistInTpm(const Name& keyName, KeyClass keyClass)
{
string keyURI = keyName.toUri();
- if (keyClass == KEY_CLASS_PUBLIC)
- {
- if (boost::filesystem::exists(m_impl->transformName(keyURI, ".pub")))
- return true;
- else
- return false;
- }
- if (keyClass == KEY_CLASS_PRIVATE)
- {
- if (boost::filesystem::exists(m_impl->transformName(keyURI, ".pri")))
- return true;
- else
- return false;
- }
- if (keyClass == KEY_CLASS_SYMMETRIC)
- {
- if (boost::filesystem::exists(m_impl->transformName(keyURI, ".key")))
- return true;
- else
- return false;
- }
+ if (keyClass == KeyClass::PUBLIC) {
+ return boost::filesystem::exists(m_impl->transformName(keyURI, ".pub"));
+ }
+ if (keyClass == KeyClass::PRIVATE) {
+ return boost::filesystem::exists(m_impl->transformName(keyURI, ".pri"));
+ }
+ if (keyClass == KeyClass::SYMMETRIC) {
+ return boost::filesystem::exists(m_impl->transformName(keyURI, ".key"));
+ }
return false;
}
bool
SecTpmFile::generateRandomBlock(uint8_t* res, size_t size)
{
- try
- {
- CryptoPP::AutoSeededRandomPool rng;
- rng.GenerateBlock(res, size);
- return true;
- }
- catch (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-osx.cpp b/src/security/sec-tpm-osx.cpp
index 04445c3..92c6add 100644
--- a/src/security/sec-tpm-osx.cpp
+++ b/src/security/sec-tpm-osx.cpp
@@ -1,6 +1,6 @@
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
- * Copyright (c) 2013-2015 Regents of the University of California.
+ * Copyright (c) 2013-2016 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
@@ -65,7 +65,7 @@
// Construction/destruction //
CFReleaser()
- : m_typeRef(0)
+ : m_typeRef(nullptr)
{
}
@@ -75,7 +75,7 @@
}
CFReleaser(const CFReleaser& inReleaser)
- : m_typeRef(0)
+ : m_typeRef(nullptr)
{
retain(inReleaser.m_typeRef);
}
@@ -133,21 +133,34 @@
void
retain(const T& typeRef)
{
- if (typeRef != 0) {
+ if (typeRef != nullptr) {
CFRetain(typeRef);
}
release();
m_typeRef = typeRef;
}
- void release()
+ void
+ release()
{
- if (m_typeRef != 0) {
+ if (m_typeRef != nullptr) {
CFRelease(m_typeRef);
- m_typeRef = 0;
+ m_typeRef = nullptr;
}
};
+ bool
+ operator==(std::nullptr_t)
+ {
+ return get() == nullptr;
+ }
+
+ bool
+ operator!=(std::nullptr_t)
+ {
+ return get() != nullptr;
+ }
+
private:
T m_typeRef;
};
@@ -303,59 +316,54 @@
return true;
// If the default key chain is locked, unlock the key chain.
- if (usePassword)
- {
- // Use the supplied password.
- res = SecKeychainUnlock(m_impl->m_keyChainRef,
- passwordLength,
- password,
- true);
- }
- else if (m_impl->m_passwordSet)
- {
- // If no password supplied, then use the configured password if exists.
- SecKeychainUnlock(m_impl->m_keyChainRef,
- m_impl->m_password.size(),
- m_impl->m_password.c_str(),
- true);
- }
+ if (usePassword) {
+ // Use the supplied password.
+ res = SecKeychainUnlock(m_impl->m_keyChainRef,
+ passwordLength,
+ password,
+ true);
+ }
+ else if (m_impl->m_passwordSet) {
+ // If no password supplied, then use the configured password if exists.
+ SecKeychainUnlock(m_impl->m_keyChainRef,
+ m_impl->m_password.size(),
+ m_impl->m_password.c_str(),
+ true);
+ }
#ifdef NDN_CXX_HAVE_GETPASS
- else if (m_impl->m_inTerminal)
- {
- // If no configured password, get password from terminal if inTerminal set.
- bool isLocked = true;
- const char* fmt = "Password to unlock the default keychain: ";
- int count = 0;
+ else if (m_impl->m_inTerminal) {
+ // If no configured password, get password from terminal if inTerminal set.
+ bool isLocked = true;
+ const char* fmt = "Password to unlock the default keychain: ";
+ int count = 0;
- while (isLocked)
- {
- if (count > 2)
- break;
+ while (isLocked) {
+ if (count > 2)
+ break;
- char* getPassword = 0;
- getPassword = getpass(fmt);
- count++;
+ char* getPassword = nullptr;
+ getPassword = getpass(fmt);
+ count++;
- if (!getPassword)
- continue;
+ if (!getPassword)
+ continue;
- res = SecKeychainUnlock(m_impl->m_keyChainRef,
- strlen(getPassword),
- getPassword,
- true);
+ res = SecKeychainUnlock(m_impl->m_keyChainRef,
+ strlen(getPassword),
+ getPassword,
+ true);
- memset(getPassword, 0, strlen(getPassword));
+ memset(getPassword, 0, strlen(getPassword));
- if (res == errSecSuccess)
- break;
- }
+ if (res == errSecSuccess)
+ break;
}
+ }
#endif // NDN_CXX_HAVE_GETPASS
- else
- {
- // If inTerminal is not set, get the password from GUI.
- SecKeychainUnlock(m_impl->m_keyChainRef, 0, 0, false);
- }
+ else {
+ // If inTerminal is not set, get the password from GUI.
+ SecKeychainUnlock(m_impl->m_keyChainRef, 0, nullptr, false);
+ }
return !isLocked();
}
@@ -366,12 +374,11 @@
bool needRetry)
{
- if (doesKeyExistInTpm(keyName, KEY_CLASS_PUBLIC))
- {
- BOOST_THROW_EXCEPTION(Error("keyName already exists"));
- }
+ if (doesKeyExistInTpm(keyName, KeyClass::PUBLIC)) {
+ BOOST_THROW_EXCEPTION(Error("keyName already exists"));
+ }
- string keyNameUri = m_impl->toInternalKeyName(keyName, KEY_CLASS_PUBLIC);
+ string keyNameUri = m_impl->toInternalKeyName(keyName, KeyClass::PUBLIC);
CFReleaser<CFStringRef> keyLabel =
CFStringCreateWithCString(0,
@@ -385,24 +392,23 @@
0);
KeyType keyType = params.getKeyType();
- uint32_t keySize;
- switch (keyType)
- {
- case KEY_TYPE_RSA:
- {
- const RsaKeyParams& rsaParams = static_cast<const RsaKeyParams&>(params);
- keySize = rsaParams.getKeySize();
- break;
- }
- case KEY_TYPE_ECDSA:
- {
- const EcdsaKeyParams& ecdsaParams = static_cast<const EcdsaKeyParams&>(params);
- keySize = ecdsaParams.getKeySize();
- break;
- }
+ uint32_t keySize = 0;
+ switch (keyType) {
+ case KeyType::RSA: {
+ const RsaKeyParams& rsaParams = static_cast<const RsaKeyParams&>(params);
+ keySize = rsaParams.getKeySize();
+ break;
+ }
+
+ case KeyType::EC: {
+ const EcdsaKeyParams& ecdsaParams = static_cast<const EcdsaKeyParams&>(params);
+ keySize = ecdsaParams.getKeySize();
+ break;
+ }
+
default:
BOOST_THROW_EXCEPTION(Error("Fail to create a key pair: Unsupported key type"));
- }
+ }
CFReleaser<CFNumberRef> cfKeySize = CFNumberCreate(0, kCFNumberIntType, &keySize);
@@ -415,22 +421,19 @@
OSStatus res = SecKeyGeneratePair((CFDictionaryRef)attrDict.get(),
&publicKey.get(), &privateKey.get());
- if (res == errSecSuccess)
- {
- return;
- }
+ if (res == errSecSuccess) {
+ return;
+ }
- if (res == errSecAuthFailed && !needRetry)
- {
- if (unlockTpm(0, 0, false))
- generateKeyPairInTpmInternal(keyName, params, true);
- else
- BOOST_THROW_EXCEPTION(Error("Fail to unlock the keychain"));
- }
- else
- {
- BOOST_THROW_EXCEPTION(Error("Fail to create a key pair"));
- }
+ if (res == errSecAuthFailed && !needRetry) {
+ if (unlockTpm(nullptr, 0, false))
+ generateKeyPairInTpmInternal(keyName, params, true);
+ else
+ BOOST_THROW_EXCEPTION(Error("Fail to unlock the keychain"));
+ }
+ else {
+ BOOST_THROW_EXCEPTION(Error("Fail to create a key pair"));
+ }
}
void
@@ -454,21 +457,20 @@
if (res == errSecSuccess)
return;
- if (res == errSecAuthFailed && !needRetry)
- {
- if (unlockTpm(0, 0, false))
- deleteKeyPairInTpmInternal(keyName, true);
- }
+ if (res == errSecAuthFailed && !needRetry) {
+ if (unlockTpm(nullptr, 0, false))
+ deleteKeyPairInTpmInternal(keyName, true);
+ }
}
void
SecTpmOsx::generateSymmetricKeyInTpm(const Name& keyName, const KeyParams& params)
{
BOOST_THROW_EXCEPTION(Error("SecTpmOsx::generateSymmetricKeyInTpm is not supported"));
- // if (doesKeyExistInTpm(keyName, KEY_CLASS_SYMMETRIC))
+ // if (doesKeyExistInTpm(keyName, KeyClass::SYMMETRIC))
// throw Error("keyName has existed!");
- // string keyNameUri = m_impl->toInternalKeyName(keyName, KEY_CLASS_SYMMETRIC);
+ // string keyNameUri = m_impl->toInternalKeyName(keyName, KeyClass::SYMMETRIC);
// CFReleaser<CFMutableDictionaryRef> attrDict =
// CFDictionaryCreateMutable(kCFAllocatorDefault,
@@ -499,23 +501,21 @@
shared_ptr<PublicKey>
SecTpmOsx::getPublicKeyFromTpm(const Name& keyName)
{
- CFReleaser<SecKeychainItemRef> publicKey = m_impl->getKey(keyName, KEY_CLASS_PUBLIC);
- if (publicKey.get() == 0)
- {
- BOOST_THROW_EXCEPTION(Error("Requested public key [" + keyName.toUri() + "] does not exist "
- "in OSX Keychain"));
- }
+ CFReleaser<SecKeychainItemRef> publicKey = m_impl->getKey(keyName, KeyClass::PUBLIC);
+ if (publicKey == nullptr) {
+ BOOST_THROW_EXCEPTION(Error("Requested public key [" + keyName.toUri() + "] does not exist "
+ "in OSX Keychain"));
+ }
CFReleaser<CFDataRef> exportedKey;
OSStatus res = SecItemExport(publicKey.get(),
kSecFormatOpenSSL,
0,
- 0,
+ nullptr,
&exportedKey.get());
- if (res != errSecSuccess)
- {
- BOOST_THROW_EXCEPTION(Error("Cannot export requested public key from OSX Keychain"));
- }
+ if (res != errSecSuccess) {
+ BOOST_THROW_EXCEPTION(Error("Cannot export requested public key from OSX Keychain"));
+ }
shared_ptr<PublicKey> key = make_shared<PublicKey>(CFDataGetBytePtr(exportedKey.get()),
CFDataGetLength(exportedKey.get()));
@@ -533,13 +533,12 @@
{
using namespace CryptoPP;
- CFReleaser<SecKeychainItemRef> privateKey = m_impl->getKey(keyName, KEY_CLASS_PRIVATE);
- if (privateKey.get() == 0)
- {
- /// @todo Can this happen because of keychain is locked?
- BOOST_THROW_EXCEPTION(Error("Private key [" + keyName.toUri() + "] does not exist "
- "in OSX Keychain"));
- }
+ CFReleaser<SecKeychainItemRef> privateKey = m_impl->getKey(keyName, KeyClass::PRIVATE);
+ if (privateKey == nullptr) {
+ /// @todo Can this happen because of keychain is locked?
+ BOOST_THROW_EXCEPTION(Error("Private key [" + keyName.toUri() + "] does not exist "
+ "in OSX Keychain"));
+ }
shared_ptr<PublicKey> publicKey = getPublicKeyFromTpm(keyName);
@@ -547,35 +546,32 @@
OSStatus res = SecItemExport(privateKey.get(),
kSecFormatOpenSSL,
0,
- 0,
+ nullptr,
&exportedKey.get());
- if (res != errSecSuccess)
- {
- if (res == errSecAuthFailed && !needRetry)
- {
- if (unlockTpm(0, 0, false))
- return exportPrivateKeyPkcs8FromTpmInternal(keyName, true);
- else
- return shared_ptr<Buffer>();
- }
+ if (res != errSecSuccess) {
+ if (res == errSecAuthFailed && !needRetry) {
+ if (unlockTpm(nullptr, 0, false))
+ return exportPrivateKeyPkcs8FromTpmInternal(keyName, true);
else
- return shared_ptr<Buffer>();
+ return nullptr;
}
+ else
+ return nullptr;
+ }
uint32_t version = 0;
OID algorithm;
bool hasParameters = false;
OID algorithmParameter;
switch (publicKey->getKeyType()) {
- case KEY_TYPE_RSA:
- {
+ case KeyType::RSA: {
algorithm = oid::RSA; // "RSA encryption"
hasParameters = false;
break;
}
- case KEY_TYPE_ECDSA:
- {
+
+ case KeyType::EC: {
// "ECDSA encryption"
StringSource src(publicKey->get().buf(), publicKey->get().size(), true);
BERSequenceDecoder subjectPublicKeyInfo(src);
@@ -589,9 +585,10 @@
hasParameters = true;
break;
}
- default:
- BOOST_THROW_EXCEPTION(Error("Unsupported key type" +
- boost::lexical_cast<std::string>(publicKey->getKeyType())));
+
+ default:
+ BOOST_THROW_EXCEPTION(Error("Unsupported key type" +
+ boost::lexical_cast<std::string>(publicKey->getKeyType())));
}
OBufferStream pkcs8Os;
@@ -654,15 +651,12 @@
if (keyTypeOID == oid::RSA)
BERDecodeNull(sequenceDecoder);
- else if (keyTypeOID == oid::ECDSA)
- {
- OID parameterOID;
- parameterOID.decode(sequenceDecoder);
- }
+ else if (keyTypeOID == oid::ECDSA) {
+ OID parameterOID;
+ parameterOID.decode(sequenceDecoder);
+ }
else
return false; // Unsupported key type;
-
-
}
BERDecodeOctetString(privateKeyInfo, rawKeyBits);
}
@@ -705,23 +699,21 @@
#pragma clang diagnostic pop
#endif // __clang__
- if (res != errSecSuccess)
- {
- if (res == errSecAuthFailed && !needRetry)
- {
- if (unlockTpm(0, 0, false))
- return importPrivateKeyPkcs8IntoTpmInternal(keyName, buf, size, true);
- else
- return false;
- }
+ if (res != errSecSuccess) {
+ if (res == errSecAuthFailed && !needRetry) {
+ if (unlockTpm(nullptr, 0, false))
+ return importPrivateKeyPkcs8IntoTpmInternal(keyName, buf, size, true);
else
return false;
}
+ else
+ return false;
+ }
// C-style cast is used as per Apple convention
SecKeychainItemRef privateKey = (SecKeychainItemRef)CFArrayGetValueAtIndex(outItems.get(), 0);
SecKeychainAttribute attrs[1]; // maximum number of attributes
- SecKeychainAttributeList attrList = { 0, attrs };
+ SecKeychainAttributeList attrList = {0, attrs};
string keyUri = keyName.toUri();
{
attrs[attrList.count].tag = kSecKeyPrintName;
@@ -733,12 +725,11 @@
res = SecKeychainItemModifyAttributesAndData(privateKey,
&attrList,
0,
- 0);
+ nullptr);
- if (res != errSecSuccess)
- {
- return false;
- }
+ if (res != errSecSuccess) {
+ return false;
+ }
return true;
}
@@ -803,18 +794,17 @@
dataLength,
kCFAllocatorNull);
- CFReleaser<SecKeychainItemRef> privateKey = m_impl->getKey(keyName, KEY_CLASS_PRIVATE);
- if (privateKey.get() == 0)
- {
- BOOST_THROW_EXCEPTION(Error("Private key [" + keyName.toUri() + "] does not exist "
- "in OSX Keychain"));
- }
+ CFReleaser<SecKeychainItemRef> privateKey = m_impl->getKey(keyName, KeyClass::PRIVATE);
+ if (privateKey == nullptr) {
+ BOOST_THROW_EXCEPTION(Error("Private key [" + keyName.toUri() + "] does not exist "
+ "in OSX Keychain"));
+ }
CFReleaser<CFErrorRef> error;
// C-style cast is used as per Apple convention
CFReleaser<SecTransformRef> signer = SecSignTransformCreate((SecKeyRef)privateKey.get(),
&error.get());
- if (error.get() != 0)
+ if (error != nullptr)
BOOST_THROW_EXCEPTION(Error("Fail to create signer"));
// Set input
@@ -822,7 +812,7 @@
kSecTransformInputAttributeName,
dataRef.get(),
&error.get());
- if (error.get() != 0)
+ if (error != nullptr)
BOOST_THROW_EXCEPTION(Error("Fail to configure input of signer"));
// Enable use of padding
@@ -830,7 +820,7 @@
kSecPaddingKey,
kSecPaddingPKCS1Key,
&error.get());
- if (error.get() != 0)
+ if (error != nullptr)
BOOST_THROW_EXCEPTION(Error("Fail to configure digest algorithm of signer"));
// Set padding type
@@ -838,7 +828,7 @@
kSecDigestTypeAttribute,
m_impl->getDigestAlgorithm(digestAlgorithm),
&error.get());
- if (error.get() != 0)
+ if (error != nullptr)
BOOST_THROW_EXCEPTION(Error("Fail to configure digest algorithm of signer"));
// Set padding attribute
@@ -848,29 +838,26 @@
kSecDigestLengthAttribute,
cfDigestSize.get(),
&error.get());
- if (error.get() != 0)
+ if (error != nullptr)
BOOST_THROW_EXCEPTION(Error("Fail to configure digest size of signer"));
// Actually sign
// C-style cast is used as per Apple convention
CFReleaser<CFDataRef> signature = (CFDataRef)SecTransformExecute(signer.get(), &error.get());
- if (error.get() != 0)
- {
- if (!needRetry)
- {
- if (unlockTpm(0, 0, false))
- return signInTpmInternal(data, dataLength, keyName, digestAlgorithm, true);
- else
- BOOST_THROW_EXCEPTION(Error("Fail to unlock the keychain"));
- }
+ if (error != nullptr) {
+ if (!needRetry) {
+ if (unlockTpm(nullptr, 0, false))
+ return signInTpmInternal(data, dataLength, keyName, digestAlgorithm, true);
else
- {
- CFShow(error.get());
- BOOST_THROW_EXCEPTION(Error("Fail to sign data"));
- }
+ BOOST_THROW_EXCEPTION(Error("Fail to unlock the keychain"));
}
+ else {
+ CFShow(error.get());
+ BOOST_THROW_EXCEPTION(Error("Fail to sign data"));
+ }
+ }
- if (signature.get() == 0)
+ if (signature == nullptr)
BOOST_THROW_EXCEPTION(Error("Signature is NULL!\n"));
return Block(tlv::SignatureValue,
@@ -885,9 +872,9 @@
// KeyClass keyClass;
// if (sym)
- // keyClass = KEY_CLASS_SYMMETRIC;
+ // keyClass = KeyClass::SYMMETRIC;
// else
- // keyClass = KEY_CLASS_PRIVATE;
+ // keyClass = KeyClass::PRIVATE;
// CFDataRef dataRef = CFDataCreate(0,
// reinterpret_cast<const unsigned char*>(data),
@@ -895,7 +882,7 @@
// );
// CFReleaser<SecKeyRef> decryptKey = (SecKeyRef)m_impl->getKey(keyName, keyClass);
- // if (decryptKey.get() == 0)
+ // if (decryptKey == nullptr)
// {
// /// @todo Can this happen because of keychain is locked?
// throw Error("Decruption key [" + ??? + "] does not exist in OSX Keychain");
@@ -925,49 +912,47 @@
void
SecTpmOsx::addAppToAcl(const Name& keyName, KeyClass keyClass, const string& appPath, AclType acl)
{
- if (keyClass == KEY_CLASS_PRIVATE && acl == ACL_TYPE_PRIVATE)
- {
- CFReleaser<SecKeychainItemRef> privateKey = m_impl->getKey(keyName, keyClass);
- if (privateKey.get() == 0)
- {
- BOOST_THROW_EXCEPTION(Error("Private key [" + keyName.toUri() + "] does not exist "
- "in OSX Keychain"));
- }
-
- CFReleaser<SecAccessRef> accRef;
- SecKeychainItemCopyAccess(privateKey.get(), &accRef.get());
-
- CFReleaser<CFArrayRef> signACL = SecAccessCopyMatchingACLList(accRef.get(),
- kSecACLAuthorizationSign);
-
- // C-style cast is used as per Apple convention
- SecACLRef aclRef = (SecACLRef)CFArrayGetValueAtIndex(signACL.get(), 0);
-
- CFReleaser<CFArrayRef> appList;
- CFReleaser<CFStringRef> description;
- SecKeychainPromptSelector promptSelector;
- SecACLCopyContents(aclRef,
- &appList.get(),
- &description.get(),
- &promptSelector);
-
- CFReleaser<CFMutableArrayRef> newAppList = CFArrayCreateMutableCopy(0,
- 0,
- appList.get());
-
- CFReleaser<SecTrustedApplicationRef> trustedApp;
- SecTrustedApplicationCreateFromPath(appPath.c_str(),
- &trustedApp.get());
-
- CFArrayAppendValue(newAppList.get(), trustedApp.get());
-
- SecACLSetContents(aclRef,
- newAppList.get(),
- description.get(),
- promptSelector);
-
- SecKeychainItemSetAccess(privateKey.get(), accRef.get());
+ if (keyClass == KeyClass::PRIVATE && acl == AclType::PRIVATE) {
+ CFReleaser<SecKeychainItemRef> privateKey = m_impl->getKey(keyName, keyClass);
+ if (privateKey == nullptr) {
+ BOOST_THROW_EXCEPTION(Error("Private key [" + keyName.toUri() + "] does not exist "
+ "in OSX Keychain"));
}
+
+ CFReleaser<SecAccessRef> accRef;
+ SecKeychainItemCopyAccess(privateKey.get(), &accRef.get());
+
+ CFReleaser<CFArrayRef> signACL = SecAccessCopyMatchingACLList(accRef.get(),
+ kSecACLAuthorizationSign);
+
+ // C-style cast is used as per Apple convention
+ SecACLRef aclRef = (SecACLRef)CFArrayGetValueAtIndex(signACL.get(), 0);
+
+ CFReleaser<CFArrayRef> appList;
+ CFReleaser<CFStringRef> description;
+ SecKeychainPromptSelector promptSelector;
+ SecACLCopyContents(aclRef,
+ &appList.get(),
+ &description.get(),
+ &promptSelector);
+
+ CFReleaser<CFMutableArrayRef> newAppList = CFArrayCreateMutableCopy(0,
+ 0,
+ appList.get());
+
+ CFReleaser<SecTrustedApplicationRef> trustedApp;
+ SecTrustedApplicationCreateFromPath(appPath.c_str(),
+ &trustedApp.get());
+
+ CFArrayAppendValue(newAppList.get(), trustedApp.get());
+
+ SecACLSetContents(aclRef,
+ newAppList.get(),
+ description.get(),
+ promptSelector);
+
+ SecKeychainItemSetAccess(privateKey.get(), accRef.get());
+ }
}
ConstBufferPtr
@@ -977,9 +962,9 @@
// KeyClass keyClass;
// if (sym)
- // keyClass = KEY_CLASS_SYMMETRIC;
+ // keyClass = KeyClass::SYMMETRIC;
// else
- // keyClass = KEY_CLASS_PUBLIC;
+ // keyClass = KeyClass::PUBLIC;
// CFDataRef dataRef = CFDataCreate(0,
// reinterpret_cast<const unsigned char*>(data),
@@ -987,7 +972,7 @@
// );
// CFReleaser<SecKeyRef> encryptKey = (SecKeyRef)m_impl->getKey(keyName, keyClass);
- // if (encryptKey.get() == 0)
+ // if (encryptKey == nullptr)
// {
// throw Error("Encryption key [" + ???? + "] does not exist in OSX Keychain");
// }
@@ -1086,7 +1071,7 @@
{
string keyUri = keyName.toUri();
- if (KEY_CLASS_SYMMETRIC == keyClass)
+ if (KeyClass::SYMMETRIC == keyClass)
return keyUri + "/symmetric";
else
return keyUri;
@@ -1096,9 +1081,9 @@
SecTpmOsx::Impl::getAsymKeyType(KeyType keyType)
{
switch (keyType) {
- case KEY_TYPE_RSA:
+ case KeyType::RSA:
return kSecAttrKeyTypeRSA;
- case KEY_TYPE_ECDSA:
+ case KeyType::EC:
return kSecAttrKeyTypeECDSA;
default:
return 0;
@@ -1109,7 +1094,7 @@
SecTpmOsx::Impl::getSymKeyType(KeyType keyType)
{
switch (keyType) {
- case KEY_TYPE_AES:
+ case KeyType::AES:
return kSecAttrKeyTypeAES;
default:
return 0;
@@ -1120,11 +1105,11 @@
SecTpmOsx::Impl::getKeyClass(KeyClass keyClass)
{
switch (keyClass) {
- case KEY_CLASS_PRIVATE:
+ case KeyClass::PRIVATE:
return kSecAttrKeyClassPrivate;
- case KEY_CLASS_PUBLIC:
+ case KeyClass::PUBLIC:
return kSecAttrKeyClassPublic;
- case KEY_CLASS_SYMMETRIC:
+ case KeyClass::SYMMETRIC:
return kSecAttrKeyClassSymmetric;
default:
return 0;
@@ -1135,7 +1120,7 @@
SecTpmOsx::Impl::getDigestAlgorithm(DigestAlgorithm digestAlgo)
{
switch (digestAlgo) {
- case DIGEST_ALGORITHM_SHA256:
+ case DigestAlgorithm::SHA256:
return kSecDigestSHA2;
default:
return 0;
@@ -1146,7 +1131,7 @@
SecTpmOsx::Impl::getDigestSize(DigestAlgorithm digestAlgo)
{
switch (digestAlgo) {
- case DIGEST_ALGORITHM_SHA256:
+ case DigestAlgorithm::SHA256:
return 256;
default:
return -1;
diff --git a/src/security/sec-tpm.cpp b/src/security/sec-tpm.cpp
index c84b2de..14e71fa 100644
--- a/src/security/sec-tpm.cpp
+++ b/src/security/sec-tpm.cpp
@@ -1,6 +1,6 @@
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
- * Copyright (c) 2013-2015 Regents of the University of California.
+ * Copyright (c) 2013-2016 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
@@ -62,112 +62,106 @@
uint32_t iterationCount = 2048;
PKCS5_PBKDF2_HMAC<SHA1> keyGenerator;
- size_t derivedLen = 24; //For DES-EDE3-CBC-PAD
+ size_t derivedLen = 24; // For DES-EDE3-CBC-PAD
byte derived[24] = {0};
byte purpose = 0;
- try
- {
- keyGenerator.DeriveKey(derived, derivedLen, purpose,
- reinterpret_cast<const byte*>(passwordStr.c_str()), passwordStr.size(),
- salt, 8, iterationCount);
- }
- catch (CryptoPP::Exception& e)
- {
- BOOST_THROW_EXCEPTION(Error("Cannot derived the encryption key"));
- }
+ try {
+ keyGenerator.DeriveKey(derived, derivedLen, purpose,
+ reinterpret_cast<const byte*>(passwordStr.c_str()), passwordStr.size(),
+ salt, 8, iterationCount);
+ }
+ catch (const CryptoPP::Exception& e) {
+ BOOST_THROW_EXCEPTION(Error("Cannot derived the encryption key"));
+ }
- //encrypt
+ // encrypt
CBC_Mode< DES_EDE3 >::Encryption e;
e.SetKeyWithIV(derived, derivedLen, iv);
ConstBufferPtr pkcs8PrivateKey = exportPrivateKeyPkcs8FromTpm(keyName);
- if (!static_cast<bool>(pkcs8PrivateKey))
+ if (pkcs8PrivateKey == nullptr)
BOOST_THROW_EXCEPTION(Error("Cannot export the private key, #1"));
OBufferStream encryptedOs;
- try
- {
- StringSource stringSource(pkcs8PrivateKey->buf(), pkcs8PrivateKey->size(), true,
- new StreamTransformationFilter(e, new FileSink(encryptedOs)));
- }
- catch (CryptoPP::Exception& e)
- {
- BOOST_THROW_EXCEPTION(Error("Cannot export the private key, #2"));
- }
+ try {
+ StringSource stringSource(pkcs8PrivateKey->buf(), pkcs8PrivateKey->size(), true,
+ new StreamTransformationFilter(e, new FileSink(encryptedOs)));
+ }
+ catch (const CryptoPP::Exception& e) {
+ BOOST_THROW_EXCEPTION(Error("Cannot export the private key, #2"));
+ }
- //encode
+ // encode
OID pbes2Id("1.2.840.113549.1.5.13");
OID pbkdf2Id("1.2.840.113549.1.5.12");
OID pbes2encsId("1.2.840.113549.3.7");
OBufferStream pkcs8Os;
- try
- {
- FileSink sink(pkcs8Os);
+ try {
+ FileSink sink(pkcs8Os);
- // EncryptedPrivateKeyInfo ::= SEQUENCE {
- // encryptionAlgorithm EncryptionAlgorithmIdentifier,
- // encryptedData OCTET STRING }
- DERSequenceEncoder encryptedPrivateKeyInfo(sink);
+ // EncryptedPrivateKeyInfo ::= SEQUENCE {
+ // encryptionAlgorithm EncryptionAlgorithmIdentifier,
+ // encryptedData OCTET STRING }
+ DERSequenceEncoder encryptedPrivateKeyInfo(sink);
+ {
+ // EncryptionAlgorithmIdentifier ::= SEQUENCE {
+ // algorithm OBJECT IDENTIFIER {{PBES2-id}},
+ // parameters SEQUENCE {{PBES2-params}} }
+ DERSequenceEncoder encryptionAlgorithm(encryptedPrivateKeyInfo);
{
- // EncryptionAlgorithmIdentifier ::= SEQUENCE {
- // algorithm OBJECT IDENTIFIER {{PBES2-id}},
- // parameters SEQUENCE {{PBES2-params}} }
- DERSequenceEncoder encryptionAlgorithm(encryptedPrivateKeyInfo);
+ pbes2Id.encode(encryptionAlgorithm);
+ // PBES2-params ::= SEQUENCE {
+ // keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
+ // encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} }
+ DERSequenceEncoder pbes2Params(encryptionAlgorithm);
{
- pbes2Id.encode(encryptionAlgorithm);
- // PBES2-params ::= SEQUENCE {
- // keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
- // encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} }
- DERSequenceEncoder pbes2Params(encryptionAlgorithm);
+ // AlgorithmIdentifier ::= SEQUENCE {
+ // algorithm OBJECT IDENTIFIER {{PBKDF2-id}},
+ // parameters SEQUENCE {{PBKDF2-params}} }
+ DERSequenceEncoder pbes2KDFs(pbes2Params);
{
+ pbkdf2Id.encode(pbes2KDFs);
// AlgorithmIdentifier ::= SEQUENCE {
- // algorithm OBJECT IDENTIFIER {{PBKDF2-id}},
- // parameters SEQUENCE {{PBKDF2-params}} }
- DERSequenceEncoder pbes2KDFs(pbes2Params);
+ // salt OCTET STRING,
+ // iterationCount INTEGER (1..MAX),
+ // keyLength INTEGER (1..MAX) OPTIONAL,
+ // prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1 }
+ DERSequenceEncoder pbkdf2Params(pbes2KDFs);
{
- pbkdf2Id.encode(pbes2KDFs);
- // AlgorithmIdentifier ::= SEQUENCE {
- // salt OCTET STRING,
- // iterationCount INTEGER (1..MAX),
- // keyLength INTEGER (1..MAX) OPTIONAL,
- // prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1 }
- DERSequenceEncoder pbkdf2Params(pbes2KDFs);
- {
- DEREncodeOctetString(pbkdf2Params, salt, 8);
- DEREncodeUnsigned<uint32_t>(pbkdf2Params, iterationCount, INTEGER);
- }
- pbkdf2Params.MessageEnd();
+ DEREncodeOctetString(pbkdf2Params, salt, 8);
+ DEREncodeUnsigned<uint32_t>(pbkdf2Params, iterationCount, INTEGER);
}
- pbes2KDFs.MessageEnd();
-
- // AlgorithmIdentifier ::= SEQUENCE {
- // algorithm OBJECT IDENTIFIER {{DES-EDE3-CBC-PAD}},
- // parameters OCTET STRING} {{iv}} }
- DERSequenceEncoder pbes2Encs(pbes2Params);
- {
- pbes2encsId.encode(pbes2Encs);
- DEREncodeOctetString(pbes2Encs, iv, 8);
- }
- pbes2Encs.MessageEnd();
+ pbkdf2Params.MessageEnd();
}
- pbes2Params.MessageEnd();
+ pbes2KDFs.MessageEnd();
+
+ // AlgorithmIdentifier ::= SEQUENCE {
+ // algorithm OBJECT IDENTIFIER {{DES-EDE3-CBC-PAD}},
+ // parameters OCTET STRING} {{iv}} }
+ DERSequenceEncoder pbes2Encs(pbes2Params);
+ {
+ pbes2encsId.encode(pbes2Encs);
+ DEREncodeOctetString(pbes2Encs, iv, 8);
+ }
+ pbes2Encs.MessageEnd();
}
- encryptionAlgorithm.MessageEnd();
-
- DEREncodeOctetString(encryptedPrivateKeyInfo,
- encryptedOs.buf()->buf(), encryptedOs.buf()->size());
+ pbes2Params.MessageEnd();
}
- encryptedPrivateKeyInfo.MessageEnd();
+ encryptionAlgorithm.MessageEnd();
- return pkcs8Os.buf();
+ DEREncodeOctetString(encryptedPrivateKeyInfo,
+ encryptedOs.buf()->buf(), encryptedOs.buf()->size());
}
- catch (CryptoPP::Exception& e)
- {
- BOOST_THROW_EXCEPTION(Error("Cannot export the private key, #3"));
- }
+ encryptedPrivateKeyInfo.MessageEnd();
+
+ return pkcs8Os.buf();
+ }
+ catch (const CryptoPP::Exception& e) {
+ BOOST_THROW_EXCEPTION(Error("Cannot export the private key, #3"));
+ }
}
bool
@@ -185,112 +179,106 @@
SecByteBlock ivBlock;
SecByteBlock encryptedDataBlock;
- try
- {
- // decode some decoding processes are not necessary for now,
- // because we assume only one encryption scheme.
- StringSource source(buf, size, true);
+ try {
+ // decode some decoding processes are not necessary for now,
+ // because we assume only one encryption scheme.
+ StringSource source(buf, size, true);
- // EncryptedPrivateKeyInfo ::= SEQUENCE {
- // encryptionAlgorithm EncryptionAlgorithmIdentifier,
- // encryptedData OCTET STRING }
- BERSequenceDecoder encryptedPrivateKeyInfo(source);
+ // EncryptedPrivateKeyInfo ::= SEQUENCE {
+ // encryptionAlgorithm EncryptionAlgorithmIdentifier,
+ // encryptedData OCTET STRING }
+ BERSequenceDecoder encryptedPrivateKeyInfo(source);
+ {
+ // EncryptionAlgorithmIdentifier ::= SEQUENCE {
+ // algorithm OBJECT IDENTIFIER {{PBES2-id}},
+ // parameters SEQUENCE {{PBES2-params}} }
+ BERSequenceDecoder encryptionAlgorithm(encryptedPrivateKeyInfo);
{
- // EncryptionAlgorithmIdentifier ::= SEQUENCE {
- // algorithm OBJECT IDENTIFIER {{PBES2-id}},
- // parameters SEQUENCE {{PBES2-params}} }
- BERSequenceDecoder encryptionAlgorithm(encryptedPrivateKeyInfo);
+ pbes2Id.decode(encryptionAlgorithm);
+ // PBES2-params ::= SEQUENCE {
+ // keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
+ // encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} }
+ BERSequenceDecoder pbes2Params(encryptionAlgorithm);
{
- pbes2Id.decode(encryptionAlgorithm);
- // PBES2-params ::= SEQUENCE {
- // keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
- // encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} }
- BERSequenceDecoder pbes2Params(encryptionAlgorithm);
+ // AlgorithmIdentifier ::= SEQUENCE {
+ // algorithm OBJECT IDENTIFIER {{PBKDF2-id}},
+ // parameters SEQUENCE {{PBKDF2-params}} }
+ BERSequenceDecoder pbes2KDFs(pbes2Params);
{
+ pbkdf2Id.decode(pbes2KDFs);
// AlgorithmIdentifier ::= SEQUENCE {
- // algorithm OBJECT IDENTIFIER {{PBKDF2-id}},
- // parameters SEQUENCE {{PBKDF2-params}} }
- BERSequenceDecoder pbes2KDFs(pbes2Params);
+ // salt OCTET STRING,
+ // iterationCount INTEGER (1..MAX),
+ // keyLength INTEGER (1..MAX) OPTIONAL,
+ // prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1 }
+ BERSequenceDecoder pbkdf2Params(pbes2KDFs);
{
- pbkdf2Id.decode(pbes2KDFs);
- // AlgorithmIdentifier ::= SEQUENCE {
- // salt OCTET STRING,
- // iterationCount INTEGER (1..MAX),
- // keyLength INTEGER (1..MAX) OPTIONAL,
- // prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1 }
- BERSequenceDecoder pbkdf2Params(pbes2KDFs);
- {
- BERDecodeOctetString(pbkdf2Params, saltBlock);
- BERDecodeUnsigned<uint32_t>(pbkdf2Params, iterationCount, INTEGER);
- }
- pbkdf2Params.MessageEnd();
+ BERDecodeOctetString(pbkdf2Params, saltBlock);
+ BERDecodeUnsigned<uint32_t>(pbkdf2Params, iterationCount, INTEGER);
}
- pbes2KDFs.MessageEnd();
-
- // AlgorithmIdentifier ::= SEQUENCE {
- // algorithm OBJECT IDENTIFIER {{DES-EDE3-CBC-PAD}},
- // parameters OCTET STRING} {{iv}} }
- BERSequenceDecoder pbes2Encs(pbes2Params);
- {
- pbes2encsId.decode(pbes2Encs);
- BERDecodeOctetString(pbes2Encs, ivBlock);
- }
- pbes2Encs.MessageEnd();
+ pbkdf2Params.MessageEnd();
}
- pbes2Params.MessageEnd();
- }
- encryptionAlgorithm.MessageEnd();
+ pbes2KDFs.MessageEnd();
- BERDecodeOctetString(encryptedPrivateKeyInfo, encryptedDataBlock);
+ // AlgorithmIdentifier ::= SEQUENCE {
+ // algorithm OBJECT IDENTIFIER {{DES-EDE3-CBC-PAD}},
+ // parameters OCTET STRING} {{iv}} }
+ BERSequenceDecoder pbes2Encs(pbes2Params);
+ {
+ pbes2encsId.decode(pbes2Encs);
+ BERDecodeOctetString(pbes2Encs, ivBlock);
+ }
+ pbes2Encs.MessageEnd();
+ }
+ pbes2Params.MessageEnd();
}
- encryptedPrivateKeyInfo.MessageEnd();
+ encryptionAlgorithm.MessageEnd();
+
+ BERDecodeOctetString(encryptedPrivateKeyInfo, encryptedDataBlock);
}
- catch (CryptoPP::Exception& e)
- {
- return false;
- }
+ encryptedPrivateKeyInfo.MessageEnd();
+ }
+ catch (const CryptoPP::Exception& e) {
+ return false;
+ }
PKCS5_PBKDF2_HMAC<SHA1> keyGenerator;
size_t derivedLen = 24; //For DES-EDE3-CBC-PAD
byte derived[24] = {0};
byte purpose = 0;
- try
- {
- keyGenerator.DeriveKey(derived, derivedLen,
- purpose,
- reinterpret_cast<const byte*>(passwordStr.c_str()), passwordStr.size(),
- saltBlock.BytePtr(), saltBlock.size(),
- iterationCount);
- }
- catch (CryptoPP::Exception& e)
- {
- return false;
- }
+ try {
+ keyGenerator.DeriveKey(derived, derivedLen,
+ purpose,
+ reinterpret_cast<const byte*>(passwordStr.c_str()), passwordStr.size(),
+ saltBlock.BytePtr(), saltBlock.size(),
+ iterationCount);
+ }
+ catch (const CryptoPP::Exception& e) {
+ return false;
+ }
//decrypt
CBC_Mode< DES_EDE3 >::Decryption d;
d.SetKeyWithIV(derived, derivedLen, ivBlock.BytePtr());
OBufferStream privateKeyOs;
- try
- {
- StringSource encryptedSource(encryptedDataBlock.BytePtr(), encryptedDataBlock.size(), true,
- new StreamTransformationFilter(d, new FileSink(privateKeyOs)));
- }
- catch (CryptoPP::Exception& e)
- {
- return false;
- }
+ try {
+ StringSource encryptedSource(encryptedDataBlock.BytePtr(), encryptedDataBlock.size(), true,
+ new StreamTransformationFilter(d, new FileSink(privateKeyOs)));
+ }
+ catch (const CryptoPP::Exception& e) {
+ return false;
+ }
if (!importPrivateKeyPkcs8IntoTpm(keyName,
privateKeyOs.buf()->buf(), privateKeyOs.buf()->size()))
return false;
- //determine key type
+ // determine key type
StringSource privateKeySource(privateKeyOs.buf()->buf(), privateKeyOs.buf()->size(), true);
- KeyType publicKeyType = KEY_TYPE_NULL;
+ KeyType publicKeyType = KeyType::NONE;
SecByteBlock rawKeyBits;
// PrivateKeyInfo ::= SEQUENCE {
// INTEGER,
@@ -305,22 +293,21 @@
OID keyTypeOID;
keyTypeOID.decode(sequenceDecoder);
if (keyTypeOID == oid::RSA)
- publicKeyType = KEY_TYPE_RSA;
+ publicKeyType = KeyType::RSA;
else if (keyTypeOID == oid::ECDSA)
- publicKeyType = KEY_TYPE_ECDSA;
+ publicKeyType = KeyType::EC;
else
return false; // Unsupported key type;
}
}
- //derive public key
+ // derive public key
OBufferStream publicKeyOs;
try {
switch (publicKeyType) {
- case KEY_TYPE_RSA:
- {
+ case KeyType::RSA: {
RSA::PrivateKey privateKey;
privateKey.Load(StringStore(privateKeyOs.buf()->buf(), privateKeyOs.buf()->size()).Ref());
RSAFunction publicKey(privateKey);
@@ -330,8 +317,8 @@
publicKeySink.MessageEnd();
break;
}
- case KEY_TYPE_ECDSA:
- {
+
+ case KeyType::EC: {
ECDSA<ECP, SHA256>::PrivateKey privateKey;
privateKey.Load(StringStore(privateKeyOs.buf()->buf(), privateKeyOs.buf()->size()).Ref());
@@ -344,12 +331,13 @@
publicKeySink.MessageEnd();
break;
}
- default:
- return false;
+
+ default:
+ return false;
}
}
- catch (CryptoPP::Exception& e) {
- return false;
+ catch (const CryptoPP::Exception& e) {
+ return false;
}
if (!importPublicKeyPkcs1IntoTpm(keyName, publicKeyOs.buf()->buf(), publicKeyOs.buf()->size()))
@@ -364,26 +352,24 @@
bool isInitialized = false;
#ifdef NDN_CXX_HAVE_GETPASS
- char* pw0 = 0;
+ char* pw0 = nullptr;
pw0 = getpass(prompt.c_str());
- if (0 == pw0)
+ if (pw0 == nullptr)
return false;
std::string password1 = pw0;
memset(pw0, 0, strlen(pw0));
pw0 = getpass("Confirm:");
- if (0 == pw0)
- {
- std::fill(password1.begin(), password1.end(), 0);
- return false;
- }
+ if (pw0 == nullptr) {
+ std::fill(password1.begin(), password1.end(), 0);
+ return false;
+ }
- if (0 == password1.compare(pw0))
- {
- isInitialized = true;
- password.swap(password1);
- }
+ if (password1.compare(pw0) == 0) {
+ isInitialized = true;
+ password.swap(password1);
+ }
std::fill(password1.begin(), password1.end(), 0);
memset(pw0, 0, strlen(pw0));
diff --git a/src/security/sec-tpm.hpp b/src/security/sec-tpm.hpp
index 6c27077..1ade1d6 100644
--- a/src/security/sec-tpm.hpp
+++ b/src/security/sec-tpm.hpp
@@ -1,6 +1,6 @@
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
- * Copyright (c) 2013-2015 Regents of the University of California.
+ * Copyright (c) 2013-2016 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
@@ -194,7 +194,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.
+ * @param keyClass The class of the key, e.g. KeyClass::PUBLIC, KeyClass::PRIVATE.
* @return True if the key exists, otherwise false.
*/
virtual bool
diff --git a/src/security/security-common.cpp b/src/security/security-common.cpp
new file mode 100644
index 0000000..0f8714d
--- /dev/null
+++ b/src/security/security-common.cpp
@@ -0,0 +1,127 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2016 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#include "security-common.hpp"
+#include <ostream>
+
+namespace ndn {
+
+std::ostream&
+operator<<(std::ostream& os, KeyType keyType)
+{
+ switch (keyType) {
+ case KeyType::NONE:
+ os << "NONE";
+ break;
+ case KeyType::RSA:
+ os << "RSA";
+ break;
+ case KeyType::EC:
+ os << "EC";
+ break;
+ case KeyType::AES:
+ os << "AES";
+ break;
+ default:
+ os << static_cast<int>(keyType);
+ break;
+ };
+ return os;
+}
+
+std::ostream&
+operator<<(std::ostream& os, KeyClass keyClass)
+{
+ switch (keyClass) {
+ case KeyClass::NONE:
+ os << "NONE";
+ break;
+ case KeyClass::PUBLIC:
+ os << "PUBLIC";
+ break;
+ case KeyClass::PRIVATE:
+ os << "PRIVATE";
+ break;
+ case KeyClass::SYMMETRIC:
+ os << "SYMMETRIC";
+ break;
+ default:
+ os << static_cast<int>(keyClass);
+ break;
+ };
+ return os;
+}
+
+std::ostream&
+operator<<(std::ostream& os, DigestAlgorithm algorithm)
+{
+ switch (algorithm) {
+ case DigestAlgorithm::NONE:
+ os << "NONE";
+ break;
+ case DigestAlgorithm::SHA256:
+ os << "SHA256";
+ break;
+ default:
+ os << static_cast<int>(algorithm);
+ break;
+ };
+ return os;
+}
+
+std::ostream&
+operator<<(std::ostream& os, BlockCipherAlgorithm algorithm)
+{
+ switch (algorithm) {
+ case BlockCipherAlgorithm::NONE:
+ os << "NONE";
+ break;
+ case BlockCipherAlgorithm::AES_CBC:
+ os << "AES_CBC";
+ break;
+ default:
+ os << static_cast<int>(algorithm);
+ break;
+ };
+ return os;
+}
+
+std::ostream&
+operator<<(std::ostream& os, AclType aclType)
+{
+ switch (aclType) {
+ case AclType::NONE:
+ os << "NONE";
+ break;
+ case AclType::PUBLIC:
+ os << "PUBLIC";
+ break;
+ case AclType::PRIVATE:
+ os << "PRIVATE";
+ break;
+ default:
+ os << static_cast<int>(aclType);
+ break;
+ };
+ return os;
+}
+
+} // namespace ndn
diff --git a/src/security/security-common.hpp b/src/security/security-common.hpp
index 8edb22c..15a82bf 100644
--- a/src/security/security-common.hpp
+++ b/src/security/security-common.hpp
@@ -37,40 +37,51 @@
} // namespace signed_interest
-enum KeyType {
- KEY_TYPE_NONE = 0,
- /// @deprecated use KEY_TYPE_NONE
- KEY_TYPE_NULL = KEY_TYPE_NONE,
-
- KEY_TYPE_RSA = 1,
- KEY_TYPE_ECDSA = 2,
- KEY_TYPE_AES = 128
+enum class KeyType {
+ NONE = 0,
+ RSA = 1,
+ EC = 2,
+ AES = 128
};
-enum KeyClass {
- KEY_CLASS_NONE,
- KEY_CLASS_PUBLIC,
- KEY_CLASS_PRIVATE,
- KEY_CLASS_SYMMETRIC
+std::ostream&
+operator<<(std::ostream& os, KeyType keyType);
+
+enum class KeyClass {
+ NONE,
+ PUBLIC,
+ PRIVATE,
+ SYMMETRIC
};
-enum DigestAlgorithm {
- DIGEST_ALGORITHM_NONE = 0,
- DIGEST_ALGORITHM_SHA256 = 1
+std::ostream&
+operator<<(std::ostream& os, KeyClass keyClass);
+
+enum class DigestAlgorithm {
+ NONE = 0,
+ SHA256 = 1
};
-enum EncryptMode {
- ENCRYPT_MODE_DEFAULT,
- ENCRYPT_MODE_CFB_AES
- // ENCRYPT_MODE_CBC_AES
+std::ostream&
+operator<<(std::ostream& os, DigestAlgorithm algorithm);
+
+enum class BlockCipherAlgorithm {
+ NONE,
+ AES_CBC
};
-enum AclType {
- ACL_TYPE_NONE,
- ACL_TYPE_PUBLIC,
- ACL_TYPE_PRIVATE
+std::ostream&
+operator<<(std::ostream& os, BlockCipherAlgorithm algorithm);
+
+enum class AclType {
+ NONE,
+ PUBLIC,
+ PRIVATE
};
+std::ostream&
+operator<<(std::ostream& os, AclType aclType);
+
} // namespace ndn
#endif // NDN_SECURITY_COMMON_HPP
diff --git a/src/security/signing-info.cpp b/src/security/signing-info.cpp
index 0872167..57cf046 100644
--- a/src/security/signing-info.cpp
+++ b/src/security/signing-info.cpp
@@ -1,6 +1,6 @@
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
- * Copyright (c) 2013-2015 Regents of the University of California.
+ * Copyright (c) 2013-2016 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
@@ -33,7 +33,7 @@
const SignatureInfo& signatureInfo)
: m_type(signerType)
, m_name(signerName)
- , m_digestAlgorithm(DIGEST_ALGORITHM_SHA256)
+ , m_digestAlgorithm(DigestAlgorithm::SHA256)
, m_info(signatureInfo)
{
}
diff --git a/src/security/transform/digest-filter.cpp b/src/security/transform/digest-filter.cpp
index 9fed4d2..c984b8c 100644
--- a/src/security/transform/digest-filter.cpp
+++ b/src/security/transform/digest-filter.cpp
@@ -23,6 +23,8 @@
#include "../../encoding/buffer.hpp"
#include "../detail/openssl-helper.hpp"
+#include <boost/lexical_cast.hpp>
+
namespace ndn {
namespace security {
namespace transform {
@@ -56,13 +58,13 @@
{
const EVP_MD* md = detail::toDigestEvpMd(algo);
if (md == nullptr) {
- // @todo Add digest algorithm to the error message
- BOOST_THROW_EXCEPTION(Error(getIndex(), "Unsupported digest algorithm"));
+ BOOST_THROW_EXCEPTION(Error(getIndex(), "Unsupported digest algorithm " +
+ boost::lexical_cast<std::string>(algo)));
}
if (!BIO_set_md(m_impl->m_md, md)) {
- // @todo Add digest algorithm to the error message
- BOOST_THROW_EXCEPTION(Error(getIndex(), "Cannot set digest"));
+ BOOST_THROW_EXCEPTION(Error(getIndex(), "Cannot set digest"+
+ boost::lexical_cast<std::string>(algo)));
}
}
diff --git a/src/security/transform/digest-filter.hpp b/src/security/transform/digest-filter.hpp
index fdd9c5b..935899f 100644
--- a/src/security/transform/digest-filter.hpp
+++ b/src/security/transform/digest-filter.hpp
@@ -62,7 +62,7 @@
};
unique_ptr<Transform>
-digestFilter(DigestAlgorithm algo = DIGEST_ALGORITHM_SHA256);
+digestFilter(DigestAlgorithm algo = DigestAlgorithm::SHA256);
} // namespace transform
} // namespace security
diff --git a/src/security/validator.cpp b/src/security/validator.cpp
index 62e4938..488d0d7 100644
--- a/src/security/validator.cpp
+++ b/src/security/validator.cpp
@@ -53,13 +53,12 @@
std::vector<shared_ptr<ValidationRequest> > nextSteps;
checkPolicy(interest, nSteps, onValidated, onValidationFailed, nextSteps);
- if (nextSteps.empty())
- {
- // If there is no nextStep,
- // that means InterestPolicy has already been able to verify the Interest.
- // No more further processes.
- return;
- }
+ if (nextSteps.empty()) {
+ // If there is no nextStep,
+ // that means InterestPolicy has already been able to verify the Interest.
+ // No more further processes.
+ return;
+ }
OnFailure onFailure = bind(onValidationFailed, interest.shared_from_this(), _1);
afterCheckPolicy(nextSteps, onFailure);
@@ -74,13 +73,12 @@
std::vector<shared_ptr<ValidationRequest> > nextSteps;
checkPolicy(data, nSteps, onValidated, onValidationFailed, nextSteps);
- if (nextSteps.empty())
- {
- // If there is no nextStep,
- // that means Data Policy has already been able to verify the Interest.
- // No more further processes.
- return;
- }
+ if (nextSteps.empty()) {
+ // If there is no nextStep,
+ // that means Data Policy has already been able to verify the Interest.
+ // No more further processes.
+ return;
+ }
OnFailure onFailure = bind(onValidationFailed, data.shared_from_this(), _1);
afterCheckPolicy(nextSteps, onFailure);
@@ -122,24 +120,22 @@
if (interestName.size() < 2)
return false;
- try
- {
- const Block& nameBlock = interestName.wireEncode();
+ try {
+ const Block& nameBlock = interestName.wireEncode();
- Signature sig(interestName[-2].blockFromValue(),
- interestName[-1].blockFromValue());
+ Signature sig(interestName[signed_interest::POS_SIG_INFO].blockFromValue(),
+ interestName[signed_interest::POS_SIG_VALUE].blockFromValue());
- if (!sig.hasKeyLocator())
- return false;
-
- return verifySignature(nameBlock.value(),
- nameBlock.value_size() - interestName[-1].size(),
- sig, key);
- }
- catch (Block::Error& e)
- {
+ if (!sig.hasKeyLocator())
return false;
- }
+
+ return verifySignature(nameBlock.value(),
+ nameBlock.value_size() - interestName[signed_interest::POS_SIG_VALUE].size(),
+ sig, key);
+ }
+ catch (const Block::Error& e) {
+ return false;
+ }
}
bool
@@ -148,121 +144,113 @@
const Signature& sig,
const PublicKey& key)
{
- try
- {
- using namespace CryptoPP;
+ try {
+ using namespace CryptoPP;
- switch (sig.getType())
- {
- case tlv::SignatureSha256WithRsa:
- {
- if (key.getKeyType() != KEY_TYPE_RSA)
- return false;
-
- RSA::PublicKey publicKey;
- ByteQueue queue;
-
- queue.Put(reinterpret_cast<const byte*>(key.get().buf()), key.get().size());
- publicKey.Load(queue);
-
- RSASS<PKCS1v15, SHA256>::Verifier verifier(publicKey);
- return verifier.VerifyMessage(buf, size,
- sig.getValue().value(), sig.getValue().value_size());
- }
- case tlv::SignatureSha256WithEcdsa:
- {
- if (key.getKeyType() != KEY_TYPE_ECDSA)
- return false;
-
- ECDSA<ECP, SHA256>::PublicKey publicKey;
- ByteQueue queue;
-
- queue.Put(reinterpret_cast<const byte*>(key.get().buf()), key.get().size());
- publicKey.Load(queue);
-
- ECDSA<ECP, SHA256>::Verifier verifier(publicKey);
-
- uint32_t length = 0;
- StringSource src(key.get().buf(), key.get().size(), true);
- BERSequenceDecoder subjectPublicKeyInfo(src);
- {
- BERSequenceDecoder algorithmInfo(subjectPublicKeyInfo);
- {
- OID algorithm;
- algorithm.decode(algorithmInfo);
-
- OID curveId;
- curveId.decode(algorithmInfo);
-
- if (curveId == SECP256R1)
- length = 256;
- else if (curveId == SECP384R1)
- length = 384;
- else
- return false;
- }
- }
-
- switch (length)
- {
- case 256:
- {
- uint8_t buffer[64];
- size_t usedSize = DSAConvertSignatureFormat(buffer, 64, DSA_P1363,
- sig.getValue().value(),
- sig.getValue().value_size(),
- DSA_DER);
- return verifier.VerifyMessage(buf, size, buffer, usedSize);
- }
- case 384:
- {
- uint8_t buffer[96];
- size_t usedSize = DSAConvertSignatureFormat(buffer, 96, DSA_P1363,
- sig.getValue().value(),
- sig.getValue().value_size(),
- DSA_DER);
- return verifier.VerifyMessage(buf, size, buffer, usedSize);
- }
- default:
- return false;
- }
- }
- default:
- // Unsupported sig type
+ switch (sig.getType()) {
+ case tlv::SignatureSha256WithRsa: {
+ if (key.getKeyType() != KeyType::RSA)
return false;
+
+ RSA::PublicKey publicKey;
+ ByteQueue queue;
+
+ queue.Put(reinterpret_cast<const byte*>(key.get().buf()), key.get().size());
+ publicKey.Load(queue);
+
+ RSASS<PKCS1v15, SHA256>::Verifier verifier(publicKey);
+ return verifier.VerifyMessage(buf, size,
+ sig.getValue().value(), sig.getValue().value_size());
+ }
+
+ case tlv::SignatureSha256WithEcdsa: {
+ if (key.getKeyType() != KeyType::EC)
+ return false;
+
+ ECDSA<ECP, SHA256>::PublicKey publicKey;
+ ByteQueue queue;
+
+ queue.Put(reinterpret_cast<const byte*>(key.get().buf()), key.get().size());
+ publicKey.Load(queue);
+
+ ECDSA<ECP, SHA256>::Verifier verifier(publicKey);
+
+ uint32_t length = 0;
+ StringSource src(key.get().buf(), key.get().size(), true);
+ BERSequenceDecoder subjectPublicKeyInfo(src);
+ {
+ BERSequenceDecoder algorithmInfo(subjectPublicKeyInfo);
+ {
+ OID algorithm;
+ algorithm.decode(algorithmInfo);
+
+ OID curveId;
+ curveId.decode(algorithmInfo);
+
+ if (curveId == SECP256R1)
+ length = 256;
+ else if (curveId == SECP384R1)
+ length = 384;
+ else
+ return false;
+ }
}
+
+ switch (length) {
+ case 256: {
+ uint8_t buffer[64];
+ size_t usedSize = DSAConvertSignatureFormat(buffer, sizeof(buffer), DSA_P1363,
+ sig.getValue().value(),
+ sig.getValue().value_size(),
+ DSA_DER);
+ return verifier.VerifyMessage(buf, size, buffer, usedSize);
+ }
+
+ case 384: {
+ uint8_t buffer[96];
+ size_t usedSize = DSAConvertSignatureFormat(buffer, sizeof(buffer), DSA_P1363,
+ sig.getValue().value(),
+ sig.getValue().value_size(),
+ DSA_DER);
+ return verifier.VerifyMessage(buf, size, buffer, usedSize);
+ }
+
+ default:
+ return false;
+ }
+ }
+
+ default:
+ // Unsupported sig type
+ return false;
}
- catch (CryptoPP::Exception& e)
- {
- return false;
- }
+ }
+ catch (const CryptoPP::Exception& e) {
+ return false;
+ }
}
bool
Validator::verifySignature(const uint8_t* buf, const size_t size, const DigestSha256& sig)
{
- try
- {
- ConstBufferPtr buffer = crypto::sha256(buf, size);
- const Block& sigValue = sig.getValue();
+ try {
+ ConstBufferPtr buffer = crypto::sha256(buf, size);
+ const Block& sigValue = sig.getValue();
- if (static_cast<bool>(buffer) &&
- buffer->size() == sigValue.value_size() &&
- buffer->size() == crypto::SHA256_DIGEST_SIZE)
- {
+ if (buffer != nullptr &&
+ buffer->size() == sigValue.value_size() &&
+ buffer->size() == crypto::SHA256_DIGEST_SIZE) {
+ const uint8_t* p1 = buffer->buf();
+ const uint8_t* p2 = sigValue.value();
- const uint8_t* p1 = buffer->buf();
- const uint8_t* p2 = sigValue.value();
-
- return 0 == memcmp(p1, p2, crypto::SHA256_DIGEST_SIZE);
- }
- else
- return false;
+ return 0 == memcmp(p1, p2, crypto::SHA256_DIGEST_SIZE);
}
- catch (CryptoPP::Exception& e)
- {
+ else
return false;
- }
+ }
+ catch (const CryptoPP::Exception& e) {
+ return false;
+ }
}
void
@@ -313,27 +301,24 @@
}
void
-Validator::afterCheckPolicy(const std::vector<shared_ptr<ValidationRequest> >& nextSteps,
+Validator::afterCheckPolicy(const std::vector<shared_ptr<ValidationRequest>>& nextSteps,
const OnFailure& onFailure)
{
- if (m_face == nullptr)
- {
- onFailure("Require more information to validate the packet!");
- return;
- }
+ if (m_face == nullptr) {
+ onFailure("Require more information to validate the packet!");
+ return;
+ }
- for (std::vector<shared_ptr<ValidationRequest> >::const_iterator it = nextSteps.begin();
- it != nextSteps.end(); it++)
- {
- m_face->expressInterest((*it)->m_interest,
- bind(&Validator::onData, this, _1, _2, *it),
- bind(&Validator::onNack, this, _1, _2,
- (*it)->m_nRetries, onFailure, *it),
- bind(&Validator::onTimeout,
- this, _1, (*it)->m_nRetries,
- onFailure,
- *it));
- }
+ for (shared_ptr<ValidationRequest> step : nextSteps) {
+ m_face->expressInterest(step->m_interest,
+ bind(&Validator::onData, this, _1, _2, step),
+ bind(&Validator::onNack, this, _1, _2,
+ step->m_nRetries, onFailure, step),
+ bind(&Validator::onTimeout,
+ this, _1, step->m_nRetries,
+ onFailure,
+ step));
+ }
}
} // namespace ndn