本文整理汇总了C++中KeyChain类的典型用法代码示例。如果您正苦于以下问题:C++ KeyChain类的具体用法?C++ KeyChain怎么用?C++ KeyChain使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了KeyChain类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: localhostRegistration
void
DummyClientFace::enableRegistrationReply()
{
onSendInterest.connect([this] (const Interest& interest) {
static const Name localhostRegistration("/localhost/nfd/rib");
if (!localhostRegistration.isPrefixOf(interest.getName()))
return;
nfd::ControlParameters params(interest.getName().get(-5).blockFromValue());
params.setFaceId(1);
params.setOrigin(0);
if (interest.getName().get(3) == name::Component("register")) {
params.setCost(0);
}
nfd::ControlResponse resp;
resp.setCode(200);
resp.setBody(params.wireEncode());
shared_ptr<Data> data = make_shared<Data>(interest.getName());
data->setContent(resp.wireEncode());
KeyChain keyChain;
keyChain.sign(*data, security::SigningInfo(security::SigningInfo::SIGNER_TYPE_SHA256));
this->getIoService().post([this, data] { this->receive(*data); });
});
}
示例2: BOOST_FIXTURE_TEST_CASE
BOOST_FIXTURE_TEST_CASE(Exemption, CommandInterestFixture)
{
KeyChain keyChain;
Name identity("/TestCommandInterest/AnyKey");
Name certName;
BOOST_REQUIRE_NO_THROW(certName = keyChain.createIdentity(identity));
CommandInterestGenerator generator;
CommandInterestValidator validator;
validator.addInterestBypassRule("^<TestCommandInterest><Exemption>");
//Test a legitimate command
shared_ptr<Interest> commandInterest1 =
make_shared<Interest>("/TestCommandInterest/Exemption/Command1");
generator.generateWithIdentity(*commandInterest1, identity);
validator.validate(*commandInterest1,
bind(&CommandInterestFixture::validated, this, _1),
bind(&CommandInterestFixture::validationFailed, this, _1, _2));
BOOST_CHECK_EQUAL(m_validity, true);
BOOST_CHECK_NO_THROW(keyChain.deleteIdentity(identity));
}
示例3: ndnsec_unlock_tpm
int
ndnsec_unlock_tpm(int argc, char** argv)
{
#ifdef NDN_CXX_HAVE_GETPASS
using namespace ndn;
namespace po = boost::program_options;
std::string keyName;
po::options_description description("General Usage\n ndnsec unlock-tpm [-h] \nGeneral options");
description.add_options()
("help,h", "produce help message")
;
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, description), vm);
po::notify(vm);
}
catch (const std::exception& e)
{
std::cerr << "ERROR: " << e.what() << std::endl;
std::cerr << description << std::endl;
return 1;
}
if (vm.count("help") != 0)
{
std::cerr << description << std::endl;
return 0;
}
bool isUnlocked = false;
KeyChain keyChain;
char* password;
password = getpass("Password to unlock the TPM: ");
isUnlocked = keyChain.unlockTpm(password, strlen(password), true);
memset(password, 0, strlen(password));
if (isUnlocked)
{
std::cerr << "OK: TPM is unlocked" << std::endl;
return 0;
}
else
{
std::cerr << "ERROR: TPM is still locked" << std::endl;
return 1;
}
#else
std::cerr << "ERROR: Command not supported on this platform" << std::endl;
return 1;
#endif // NDN_CXX_HAVE_GETPASS
}
示例4: BOOST_FIXTURE_TEST_CASE
BOOST_FIXTURE_TEST_CASE(ConstructorEmpty2Config, TestHomeAndPibFixture<PibPathEmptyFile>)
{
createClientConf({"tpm=tpm-file:%PATH%"});
BOOST_REQUIRE_NO_THROW(KeyChain());
KeyChain keyChain;
BOOST_CHECK_EQUAL(keyChain.getPib().getPibLocator(), "pib-sqlite3:");
BOOST_CHECK_EQUAL(keyChain.getPib().getTpmLocator(), "tpm-file:" + m_pibDir);
BOOST_CHECK_EQUAL(keyChain.getTpm().getTpmLocator(), "tpm-file:" + m_pibDir);
}
示例5: encoder
void
CommandInterestGenerator::generate
(Interest& interest, KeyChain& keyChain, const Name& certificateName,
WireFormat& wireFormat)
{
MillisecondsSince1970 timestamp = ::round(ndn_getNowMilliseconds());
while (timestamp <= lastTimestamp_)
timestamp += 1.0;
// The timestamp is encoded as a TLV nonNegativeInteger.
TlvEncoder encoder(8);
encoder.writeNonNegativeInteger((uint64_t)timestamp);
interest.getName().append(Blob(encoder.finish()));
// The random value is a TLV nonNegativeInteger too, but we know it is 8 bytes,
// so we don't need to call the nonNegativeInteger encoder.
uint8_t randomBuffer[8];
ndn_Error error;
if ((error = CryptoLite::generateRandomBytes(randomBuffer, sizeof(randomBuffer))))
throw runtime_error(ndn_getErrorString(error));
interest.getName().append(randomBuffer, sizeof(randomBuffer));
keyChain.sign(interest, certificateName, wireFormat);
if (interest.getInterestLifetimeMilliseconds() < 0)
// The caller has not set the interest lifetime, so set it here.
interest.setInterestLifetimeMilliseconds(1000.0);
// We successfully signed the interest, so update the timestamp.
lastTimestamp_ = timestamp;
}
示例6: main
int main(int argc, char** argv)
{
try {
Name prefix("/nfd/edu/ucla/remap/test");
// Route to aleph.ndn.ucla.edu. Have to use the canonical name with
// an IP address and port.
string uri = "udp4://128.97.98.7:6363";
// The default Face connects to the local NFD.
Face face;
// Use the system default key chain and certificate name to sign commands.
KeyChain keyChain;
face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName());
// Create the /localhost/nfd/faces/query command interest, including the
// FaceQueryFilter. Construct the FaceQueryFilter using the structure in
// face-query-filter.pb.h which was produced by protoc.
ndn_message::FaceQueryFilterMessage message;
ndn_message::FaceQueryFilterMessage_FaceQueryFilter* filter =
message.add_face_query_filter();
filter->set_uri(uri);
Blob encodedFilter = ProtobufTlv::encode(message);
Interest interest(Name("/localhost/nfd/faces/query"));
interest.getName().append(encodedFilter);
bool enabled = true;
SegmentFetcher::fetch
(face, interest, SegmentFetcher::DontVerifySegment,
bind(&processFaceStatus, _1, prefix, uri, &face, &enabled),
bind(&onError, _1, _2, &enabled));
// Loop calling processEvents until a callback sets enabled = false.
while (enabled) {
face.processEvents();
// We need to sleep for a few milliseconds so we don't use 100% of the CPU.
usleep(10000);
}
} catch (std::exception& e) {
cout << "exception: " << e.what() << endl;
}
return 0;
}
示例7: main
int main(int argc, char** argv)
{
std::string logfile = createLogDir("./logs");
GLogger glog( argv[0], logfile.c_str() );
std::cout << "Log to path: " << logfile << std::endl;
try {
boost::asio::io_service ioService;
ptr_lib::shared_ptr<ThreadsafeFace> face;
face.reset(new ThreadsafeFace (ioService, "localhost"));
// Use the system default key chain and certificate name to sign commands.
KeyChain keyChain;
face->setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName());
// Also use the default certificate name to sign data packets.
Publisher publisher(ioService, face, keyChain, keyChain.getDefaultCertificateName());
if( !publisher.init() )
{
cout << "Publisher init fail" << endl;
return 0;
}
else
{
std::thread *captureThread =
new std::thread(bind(&Publisher::start,&publisher));
captureThread->detach();
LOG(INFO) << "ioservice start" << endl;
boost::asio::io_service::work work(ioService);
ioService.run();
LOG(INFO) << "ioservice started" << endl;
}
}
catch (std::exception& e) {
cout << "exception: " << e.what() << endl;
}
return 0;
}
示例8: prepareCommandInterestName
void
CommandInterestGenerator::generate
(Interest& interest, KeyChain& keyChain, const Name& certificateName,
WireFormat& wireFormat)
{
prepareCommandInterestName(interest, wireFormat);
keyChain.sign(interest, certificateName, wireFormat);
if (interest.getInterestLifetimeMilliseconds() < 0)
// The caller has not set the interest lifetime, so set it here.
interest.setInterestLifetimeMilliseconds(1000.0);
}
示例9: TEST_F
TEST_F(TestInterestMethods, VerifyDigestSha256)
{
// Create a KeyChain but we don't need to add keys.
ptr_lib::shared_ptr<MemoryIdentityStorage> identityStorage
(new MemoryIdentityStorage());
KeyChain keyChain
(ptr_lib::make_shared<IdentityManager>
(identityStorage, ptr_lib::make_shared<MemoryPrivateKeyStorage>()),
ptr_lib::make_shared<SelfVerifyPolicyManager>(identityStorage.get()));
ptr_lib::shared_ptr<Interest> interest(new Interest(Name("/test/signed-interest")));
keyChain.signWithSha256(*interest);
VerifyCounter counter;
keyChain.verifyInterest
(interest, bind(&VerifyCounter::onVerified, &counter, _1),
// Cast to disambiguate from the deprecated OnVerifyInterestFailed.
(const OnInterestValidationFailed)bind
(&VerifyCounter::onInterestValidationFailed, &counter, _1, _2));
ASSERT_EQ(counter.onValidationFailedCallCount_, 0) << "Signature verification failed";
ASSERT_EQ(counter.onVerifiedCallCount_, 1) << "Verification callback was not used.";
}
示例10: main
int main(int argc, char** argv)
{
try {
Face face("localhost");
shared_ptr<MemoryIdentityStorage> identityStorage(new MemoryIdentityStorage());
shared_ptr<MemoryPrivateKeyStorage> privateKeyStorage(new MemoryPrivateKeyStorage());
KeyChain keyChain
(make_shared<IdentityManager>(identityStorage, privateKeyStorage), make_shared<NoVerifyPolicyManager>());
keyChain.setFace(&face);
// Initialize the storage.
Name keyName("/testname/DSK-123");
Name certificateName = keyName.getSubName(0, keyName.size() - 1).append("KEY").append
(keyName.get(keyName.size() - 1)).append("ID-CERT").append("0");
identityStorage->addKey(keyName, KEY_TYPE_RSA, Blob(DEFAULT_PUBLIC_KEY_DER, sizeof(DEFAULT_PUBLIC_KEY_DER)));
privateKeyStorage->setKeyPairForKeyName
(keyName, DEFAULT_PUBLIC_KEY_DER, sizeof(DEFAULT_PUBLIC_KEY_DER), DEFAULT_PRIVATE_KEY_DER, sizeof(DEFAULT_PRIVATE_KEY_DER));
Echo echo(keyChain, certificateName);
Name prefix("/testecho");
cout << "Register prefix " << prefix.toUri() << endl;
face.registerPrefix(prefix, ref(echo), ref(echo));
// The main event loop.
// Wait forever to receive one interest for the prefix.
while (echo.responseCount_ < 1) {
face.processEvents();
// We need to sleep for a few milliseconds so we don't use 100% of the CPU.
usleep(10000);
}
} catch (std::exception& e) {
cout << "exception: " << e.what() << endl;
}
return 0;
}
示例11: benchmarkDecodeDataSecondsCpp
/**
* Loop to decode a data packet nIterations times using C++.
* @param nIterations The number of iterations.
* @param useCrypto If true, verify the signature. If false, don't verify.
* @param encoding The wire encoding to decode.
* @return The number of seconds for all iterations.
*/
static double
benchmarkDecodeDataSecondsCpp(int nIterations, bool useCrypto, const Blob& encoding)
{
// Initialize the KeyChain storage in case useCrypto is true.
ptr_lib::shared_ptr<MemoryIdentityStorage> identityStorage(new MemoryIdentityStorage());
ptr_lib::shared_ptr<MemoryPrivateKeyStorage> privateKeyStorage(new MemoryPrivateKeyStorage());
KeyChain keyChain
(ptr_lib::make_shared<IdentityManager>(identityStorage, privateKeyStorage),
ptr_lib::make_shared<SelfVerifyPolicyManager>(identityStorage.get()));
Name keyName("/testname/DSK-123");
identityStorage->addKey(keyName, KEY_TYPE_RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER, sizeof(DEFAULT_RSA_PUBLIC_KEY_DER)));
double start = getNowSeconds();
for (int i = 0; i < nIterations; ++i) {
ptr_lib::shared_ptr<Data> data(new Data());
data->wireDecode(encoding);
if (useCrypto)
keyChain.verifyData(data, onVerified, onVerifyFailed);
}
double finish = getNowSeconds();
return finish - start;
}
示例12: ndnsec_delete
int
ndnsec_delete(int argc, char** argv)
{
using namespace ndn;
namespace po = boost::program_options;
// bool deleteId = true;
bool isDeleteKey = false;
bool isDeleteCert = false;
std::string name;
po::options_description description("General Usage\n ndnsec delete [-h] [-k|c] name\nGeneral options");
description.add_options()
("help,h", "produce help message")
("delete-key,k", "(Optional) delete a key if specified.")
("delete-key2,K", "(Optional) delete a key if specified.")
("delete-cert,c", "(Optional) delete a certificate if specified.")
("delete-cert2,C", "(Optional) delete a certificate if specified.")
("name,n", po::value<std::string>(&name), "By default, it refers to an identity."
"If -k is specified, it refers to a key."
"If -c is specified, it refers to a certificate.");
;
po::positional_options_description p;
p.add("name", 1);
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv).options(description).positional(p).run(),
vm);
po::notify(vm);
}
catch (const std::exception& e)
{
std::cerr << "ERROR: " << e.what() << std::endl;
std::cerr << description << std::endl;
return 1;
}
if (vm.count("help") != 0)
{
std::cerr << description << std::endl;;
return 0;
}
if (vm.count("name") == 0)
{
std::cerr << "ERROR: name must be specified" << std::endl;
std::cerr << description << std::endl;
return 1;
}
if (vm.count("delete-cert") != 0 || vm.count("delete-cert2") != 0)
{
isDeleteCert = true;
// deleteId = false;
}
else if (vm.count("delete-key") != 0 || vm.count("delete-key2") != 0)
{
isDeleteKey = true;
// deleteId = false;
}
KeyChain keyChain;
if (isDeleteCert)
{
keyChain.deleteCertificate(name);
}
else if (isDeleteKey)
{
keyChain.deleteKey(name);
}
else
{
keyChain.deleteIdentity(name);
}
return 0;
}
示例13: ndnsec_cert_gen
//.........这里部分代码省略.........
if (it == subjectInfoItems.end())
{
std::cerr << "ERROR: unmatched info for oid [" << oid << "]" << std::endl;
return 1;
}
std::string value = *it;
subjectDescription.push_back(CertificateSubjectDescription(OID(oid), value));
it++;
}
system_clock::TimePoint notBefore;
system_clock::TimePoint notAfter;
if (vm.count("not-before") == 0)
{
notBefore = system_clock::now();
}
else
{
notBefore = fromIsoString(notBeforeStr.substr(0, 8) + "T" +
notBeforeStr.substr(8, 6));
}
if (vm.count("not-after") == 0)
{
notAfter = notBefore + days(365);
}
else
{
notAfter = fromIsoString(notAfterStr.substr(0, 8) + "T" +
notAfterStr.substr(8, 6));
if (notAfter < notBefore)
{
std::cerr << "not-before is later than not-after" << std::endl;
return 1;
}
}
if (vm.count("request") == 0)
{
std::cerr << "request file must be specified" << std::endl;
return 1;
}
shared_ptr<IdentityCertificate> selfSignedCertificate
= getIdentityCertificate(requestFile);
if (!static_cast<bool>(selfSignedCertificate))
{
std::cerr << "ERROR: input error" << std::endl;
return 1;
}
KeyChain keyChain;
Name keyName = selfSignedCertificate->getPublicKeyName();
Name signIdName;
Name prefix(certPrefix);
if (!hasSignId)
signIdName = keyChain.getDefaultIdentity();
else
signIdName = Name(signId);
shared_ptr<IdentityCertificate> certificate =
keyChain.prepareUnsignedIdentityCertificate(keyName, selfSignedCertificate->getPublicKeyInfo(),
signIdName, notBefore, notAfter,
subjectDescription, prefix);
if (!static_cast<bool>(certificate))
{
std::cerr << "ERROR: key name is not formated correctly or does not match certificate name."
<< std::endl;
return 1;
}
keyChain.createIdentity(signIdName);
Name signingCertificateName = keyChain.getDefaultCertificateNameForIdentity(signIdName);
keyChain.sign(*certificate, signingCertificateName);
Block wire = certificate->wireEncode();
try
{
using namespace CryptoPP;
StringSource ss(wire.wire(), wire.size(), true,
new Base64Encoder(new FileSink(std::cout), true, 64));
}
catch (const CryptoPP::Exception& e)
{
std::cerr << "ERROR: " << e.what() << std::endl;
return 1;
}
return 0;
}
示例14: ndnsec_key_gen
int
ndnsec_key_gen(int argc, char** argv)
{
using namespace ndn;
namespace po = boost::program_options;
std::string identityName;
bool isDefault = true;
char keyType = 'r';
std::string outputFilename;
po::options_description description("General Usage\n"
" ndnsec key-gen [-h] [-n] identity\n"
"General options");
description.add_options()
("help,h", "produce help message")
("identity,i", po::value<std::string>(&identityName),
"identity name, for example, /ndn/edu/ucla/alice")
("not_default,n",
"optional, if not specified, the target identity will be set as "
"the default identity of the system")
("dsk,d", "generate Data-Signing-Key (DSK) instead of the default Key-Signing-Key (KSK)")
("type,t", po::value<char>(&keyType)->default_value('r'),
"optional, key type, r for RSA key (default), e for ECDSA key")
// ("size,s", po::value<int>(&keySize)->default_value(2048),
// "optional, key size, 2048 (default)")
;
po::positional_options_description p;
p.add("identity", 1);
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).options(description).positional(p).run(),
vm);
po::notify(vm);
}
catch (const std::exception& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
std::cerr << description << std::endl;
return 1;
}
if (vm.count("help") != 0) {
std::cerr << description << std::endl;
return 0;
}
if (vm.count("identity") == 0) {
std::cerr << "identity must be specified" << std::endl;
std::cerr << description << std::endl;
return 1;
}
if (vm.count("not_default") != 0)
isDefault = false;
bool isKsk = (vm.count("dsk") == 0);
KeyChain keyChain;
Name keyName;
try {
switch (keyType) {
case 'r':
keyName = keyChain.generateRsaKeyPair(Name(identityName), isKsk, RsaKeyParams().getKeySize());
break;
case 'e':
keyName = keyChain.generateEcdsaKeyPair(Name(identityName), isKsk,
EcdsaKeyParams().getKeySize());
break;
default:
std::cerr << "Unrecongized key type" << "\n";
std::cerr << description << std::endl;
return 1;
}
if (0 == keyName.size()) {
std::cerr << "Error: failed to generate key" << "\n";
return 1;
}
keyChain.setDefaultKeyNameForIdentity(keyName);
shared_ptr<security::v1::IdentityCertificate> identityCert = keyChain.selfSign(keyName);
if (isDefault)
keyChain.setDefaultIdentity(Name(identityName));
io::save(*identityCert, std::cout);
}
catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
示例15: ndnsec_get_default
int
ndnsec_get_default(int argc, char** argv)
{
using namespace ndn;
namespace po = boost::program_options;
bool isGetDefaultId = true;
bool isGetDefaultKey = false;
bool isGetDefaultCert = false;
bool isQuiet = false;
std::string identityString;
std::string keyName;
po::options_description description("General Usage\n ndnsec get-default [-h] [-k|c] [-i identity|-K key] [-q]\nGeneral options");
description.add_options()
("help,h", "produce help message")
("default_key,k", "get default key")
("default_cert,c", "get default certificate")
("identity,i", po::value<std::string>(&identityString), "target identity")
("key,K", po::value<std::string>(&keyName), "target key")
("quiet,q", "don't output trailing newline")
;
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, description), vm);
po::notify(vm);
}
catch (const std::exception& e)
{
std::cerr << "ERROR: " << e.what() << std::endl;
std::cerr << description << std::endl;
return 1;
}
if (vm.count("help") != 0)
{
std::cerr << description << std::endl;;
return 0;
}
if (vm.count("default_cert") != 0)
{
isGetDefaultCert = true;
isGetDefaultId = false;
}
else if (vm.count("default_key") != 0)
{
isGetDefaultKey = true;
isGetDefaultId = false;
}
if (vm.count("quiet") != 0)
{
isQuiet = true;
}
KeyChain keyChain;
if (vm.count("key") != 0)
{
Name keyNdnName(keyName);
if (isGetDefaultCert)
{
std::cout << keyChain.getDefaultCertificateNameForKey(keyNdnName);
if (!isQuiet) std::cout << std::endl;
return 0;
}
return 1;
}
else if (vm.count("identity") != 0)
{
Name identity(identityString);
if (isGetDefaultKey)
{
std::cout << keyChain.getDefaultKeyNameForIdentity(identity);
if (!isQuiet)
std::cout << std::endl;
return 0;
}
if (isGetDefaultCert)
{
std::cout << keyChain.getDefaultCertificateNameForIdentity(identity);
if (!isQuiet)
std::cout << std::endl;
return 0;
}
return 1;
}
else
{
Name identity = keyChain.getDefaultIdentity();
if (isGetDefaultId)
{
std::cout << identity;
if (!isQuiet) std::cout << std::endl;
//.........这里部分代码省略.........