void NdnSigner::sign( Data& data ) const
      {
        //////// configure key locator ///////////

        // encode public key
        std::string     keystr;
        CryptoPP::StringSink sink(keystr);
        m_public_key.Save(sink);

        // make key locator and insert key as key digest
        KeyLocator loc;
        auto buffer = make_shared<const Buffer>( (uint8_t*)keystr.c_str(), keystr.length() );
        loc.setKeyDigest( buffer );

        // setup signature info
        Signature sig = data.getSignature();
        SignatureInfo sinfo = sig.getSignatureInfo();
        sinfo.setSignatureType( tlv::SignatureSha256WithRsa);
        sinfo.setKeyLocator( loc );
        sig.setInfo( sinfo );
        data.setSignature( sig );

        // sign data
        Block sig_block = signBlock( data.wireEncode() );

         // set signature
         sig.setValue( sig_block );
         data.setSignature( sig );
         data.wireEncode();
      }
void
SelectorHelper::applySelectors(Interest& interest, Context* context)
{
  int minSuffix = -1;
  context->getContextOption(MIN_SUFFIX_COMP_S, minSuffix);
  
  if (minSuffix >= 0)
  {
    interest.setMinSuffixComponents(minSuffix);
  }
  
  int maxSuffix = -1;
  context->getContextOption(MAX_SUFFIX_COMP_S, maxSuffix);
  
  if (maxSuffix >= 0)
  {
    interest.setMaxSuffixComponents(maxSuffix);
  }
  
  Exclude exclusion;
  context->getContextOption(EXCLUDE_S, exclusion);
  
  if (!exclusion.empty())
  {
    interest.setExclude(exclusion);
  }
  
  bool mustBeFresh = false;
  context->getContextOption(MUST_BE_FRESH_S, mustBeFresh);
  
  if (mustBeFresh)
  {
    interest.setMustBeFresh(mustBeFresh);
  }
  
  int child = -10;
  context->getContextOption(RIGHTMOST_CHILD_S, child);
  
  if (child != -10)
  {
    interest.setChildSelector(child);
  }
  
  KeyLocator keyLocator;
  context->getContextOption(KEYLOCATOR_S, keyLocator);
  
  if (!keyLocator.empty())
  {
    interest.setPublisherPublicKeyLocator(keyLocator);
  }
}
const ndn::ConstBufferPtr
Index::computeKeyLocatorHash(const KeyLocator& keyLocator)
{
  const Block& block = keyLocator.wireEncode();
  ndn::ConstBufferPtr keyLocatorHash = ndn::crypto::sha256(block.wire(), block.size());
  return keyLocatorHash;
}
Exemple #4
0
ptr_lib::shared_ptr<IdentityCertificate>
IdentityManager::createIdentityCertificate(const Name& certificatePrefix,
                                           const PublicKey& publicKey,
                                           const Name& signerCertificateName,
                                           const MillisecondsSince1970& notBefore,
                                           const MillisecondsSince1970& notAfter)
{
  ptr_lib::shared_ptr<IdentityCertificate> certificate(new IdentityCertificate());
  Name keyName = getKeyNameFromCertificatePrefix(certificatePrefix);

  Name certificateName = certificatePrefix;
  MillisecondsSince1970 ti = ::ndn_getNowMilliseconds();
  // Get the number of seconds.
  ostringstream oss;
  oss << floor(ti / 1000.0);

  certificateName.append("ID-CERT").append(oss.str());

  certificate->setName(certificateName);
  certificate->setNotBefore(notBefore);
  certificate->setNotAfter(notAfter);
  certificate->setPublicKeyInfo(publicKey);
  certificate->addSubjectDescription(CertificateSubjectDescription("2.5.4.41", keyName.toUri()));
  certificate->encode();

  ptr_lib::shared_ptr<Sha256WithRsaSignature> sha256Sig(new Sha256WithRsaSignature());

  KeyLocator keyLocator;
  keyLocator.setType(ndn_KeyLocatorType_KEYNAME);
  keyLocator.setKeyName(signerCertificateName);

  sha256Sig->setKeyLocator(keyLocator);
  sha256Sig->getPublisherPublicKeyDigest().setPublisherPublicKeyDigest(publicKey.getDigest());

  certificate->setSignature(*sha256Sig);

  SignedBlob unsignedData = certificate->wireEncode();

  ptr_lib::shared_ptr<IdentityCertificate> signerCertificate = getCertificate(signerCertificateName);
  Name signerkeyName = signerCertificate->getPublicKeyName();

  Blob sigBits = privateKeyStorage_->sign(unsignedData, signerkeyName);

  sha256Sig->setSignature(sigBits);

  return certificate;
}
  virtual bool
  check(const Name& packetName,
        const KeyLocator& keyLocator,
        std::string& failInfo)
  {
    try
      {
        if (m_regex.match(keyLocator.getName()))
          return true;

        failInfo = "KeyLocatorChecker failed!";
        return false;
      }
    catch (KeyLocator::Error& e)
      {
        failInfo = "KeyLocator does not have name";
        return false;
      }
  }
  virtual bool
  check(const Name& packetName,
        const KeyLocator& keyLocator,
        std::string& failInfo)
  {
    try
      {
        if (m_hyperPRegex->match(packetName) &&
            m_hyperKRegex->match(keyLocator.getName()) &&
            checkRelation(m_hyperRelation,
                          m_hyperKRegex->expand(),
                          m_hyperPRegex->expand()))
          return true;

        failInfo = "KeyLocatorChecker failed!";
        return false;
      }
    catch (KeyLocator::Error& e)
      {
        failInfo = "KeyLocator does not have name";
        return false;
      }

  }
Exemple #7
0
bool
KeyLocator::operator==(const KeyLocator& other) const
{
  return wireEncode() == other.wireEncode();
}
std::pair<int64_t,Name>
Index::selectChild(const Interest& interest,
                   IndexContainer::const_iterator startingPoint) const
{
  BOOST_ASSERT(startingPoint != m_indexContainer.end());
  bool isLeftmost = (interest.getChildSelector() <= 0);
  ndn::ConstBufferPtr hash;
  if (!interest.getPublisherPublicKeyLocator().empty())
    {
      KeyLocator keyLocator = interest.getPublisherPublicKeyLocator();
      const Block& block = keyLocator.wireEncode();
      hash = ndn::crypto::sha256(block.wire(), block.size());
    }

  if (isLeftmost)
    {
      for (IndexContainer::const_iterator it = startingPoint;
           it != m_indexContainer.end(); ++it)
        {
          if (!interest.getName().isPrefixOf(it->getName()))
            return std::make_pair(0, Name());
          if (matchesSimpleSelectors(interest, hash, (*it)))
            return std::make_pair(it->getId(), it->getName());
        }
    }
  else
    {
      IndexContainer::const_iterator boundary = m_indexContainer.lower_bound(interest.getName());
      if (boundary == m_indexContainer.end() || !interest.getName().isPrefixOf(boundary->getName()))
        return std::make_pair(0, Name());
      Name successor = interest.getName().getSuccessor();
      IndexContainer::const_iterator last = interest.getName().size() == 0 ?
                    m_indexContainer.end() : m_indexContainer.lower_bound(interest.getName().getSuccessor());
      while (true)
        {
          IndexContainer::const_iterator prev = last;
            if (prev != boundary) {
                --prev;
            }
          if (prev == boundary)
            {
              bool isMatch = matchesSimpleSelectors(interest, hash, (*prev));
              if (isMatch)
                {
                  return std::make_pair(prev->getId(), prev->getName());
                }
              else
                return std::make_pair(0, Name());
            }
          IndexContainer::const_iterator first =
            m_indexContainer.lower_bound(prev->getName().getPrefix(interest.getName().size() + 1));
          IndexContainer::const_iterator match =
                     std::find_if(first, last, bind(&matchesSimpleSelectors, interest, hash, _1));
          if (match != last)
            {
              return std::make_pair(match->getId(), match->getName());
            }
          last = first;
        }
    }
  return std::make_pair(0, Name());
}
/**
 * Loop to encode a data packet nIterations times using C++.
 * @param nIterations The number of iterations.
 * @param useComplex If true, use a large name, large content and all fields.  If false, use a small name, small content
 * and only required fields.
 * @param useCrypto If true, sign the data packet.  If false, use a blank signature.
 * @param encoding Set this to the wire encoding.
 * @return The number of seconds for all iterations.
 */
static double
benchmarkEncodeDataSecondsCpp(int nIterations, bool useComplex, bool useCrypto, Blob& encoding)
{
  Name name;
  Blob content;
  if (useComplex) {
    // Use a large name and content.
    name = Name("/ndn/ucla.edu/apps/lwndn-test/numbers.txt/%FD%05%05%E8%0C%CE%1D/%00");

    ostringstream contentStream;
    int count = 1;
    contentStream << (count++);
    while (contentStream.str().length() < 1115)
      contentStream << " " << (count++);
    content = Blob((uint8_t*)contentStream.str().c_str(), contentStream.str().length());
  }
  else {
    // Use a small name and content.
    name = Name("/test");
    content = Blob((uint8_t*)"abc", 3);
  }
  Blob finalBlockId((uint8_t*)"\x00", 1);

  // 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");
  Name certificateName = keyName.getSubName(0, keyName.size() - 1).append("KEY").append
    (keyName.get(keyName.size() - 1)).append("ID-CERT").append("0");
  privateKeyStorage->setKeyPairForKeyName
    (keyName, KEY_TYPE_RSA, DEFAULT_RSA_PUBLIC_KEY_DER,
     sizeof(DEFAULT_RSA_PUBLIC_KEY_DER), DEFAULT_RSA_PRIVATE_KEY_DER,
     sizeof(DEFAULT_RSA_PRIVATE_KEY_DER));

  uint8_t signatureBitsArray[256];
  memset(signatureBitsArray, 0, sizeof(signatureBitsArray));
  Blob signatureBits(signatureBitsArray, sizeof(signatureBitsArray));

  double start = getNowSeconds();
  for (int i = 0; i < nIterations; ++i) {
    Data data(name);
    data.setContent(content);
    if (useComplex) {
      data.getMetaInfo().setFreshnessPeriod(1000);
      data.getMetaInfo().setFinalBlockId(finalBlockId);
    }

    if (useCrypto)
      // This sets the signature fields.
      keyChain.sign(data, certificateName);
    else {
      // Imitate IdentityManager::signByCertificate to set up the signature fields, but don't sign.
      KeyLocator keyLocator;
      keyLocator.setType(ndn_KeyLocatorType_KEYNAME);
      keyLocator.setKeyName(certificateName);
      Sha256WithRsaSignature* sha256Signature = (Sha256WithRsaSignature*)data.getSignature();
      sha256Signature->setKeyLocator(keyLocator);
      sha256Signature->setSignature(signatureBits);
    }

    encoding = data.wireEncode();
  }
  double finish = getNowSeconds();

  return finish - start;
}