/// <summary> /// Append a timestamp component and a random value component to interest's /// name. This ensures that the timestamp is greater than the timestamp used in /// the previous call. Then use keyChain to sign the interest which appends a /// SignatureInfo component and a component with the signature bits. If the /// interest lifetime is not set, this sets it. /// </summary> /// /// <param name="interest">The interest whose name is append with components.</param> /// <param name="keyChain">The KeyChain for calling sign.</param> /// <param name="certificateName">The certificate name of the key to use for signing.</param> /// <param name="wireFormat"></param> public void generate(Interest interest, KeyChain keyChain, Name certificateName, WireFormat wireFormat) { double timestamp; lock (lastTimestampLock_) { timestamp = Math.Round(net.named_data.jndn.util.Common.getNowMilliseconds(),MidpointRounding.AwayFromZero); while (timestamp <= lastTimestamp_) timestamp += 1.0d; // Update the timestamp now while it is locked. In the small chance that // signing fails, it just means that we have bumped the timestamp. lastTimestamp_ = timestamp; } // The timestamp is encoded as a TLV nonNegativeInteger. TlvEncoder encoder = new TlvEncoder(8); encoder.writeNonNegativeInteger((long) timestamp); interest.getName().append(new Blob(encoder.getOutput(), false)); // 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. ByteBuffer randomBuffer = ILOG.J2CsMapping.NIO.ByteBuffer.allocate(8); // Note: SecureRandom is thread safe. net.named_data.jndn.util.Common.getRandom().nextBytes(randomBuffer.array()); interest.getName().append(new Blob(randomBuffer, false)); keyChain.sign(interest, certificateName, wireFormat); if (interest.getInterestLifetimeMilliseconds() < 0) // The caller has not set the interest lifetime, so set it here. interest.setInterestLifetimeMilliseconds(1000.0d); }
public void testMaxNdnPacketSize() { // Construct an interest whose encoding is one byte larger than getMaxNdnPacketSize. int targetSize = net.named_data.jndn.Face.getMaxNdnPacketSize() + 1; // Start with an interest which is almost the right size. Interest interest = new Interest(); interest.getName().append(new byte[targetSize]); int initialSize = interest.wireEncode().size(); // Now replace the component with the desired size which trims off the extra encoding. interest.setName(new Name().append(new byte[targetSize - (initialSize - targetSize)])); int interestSize = interest.wireEncode().size(); AssertEquals("Wrong interest size for MaxNdnPacketSize", targetSize, interestSize); CallbackCounter counter = new CallbackCounter(); bool gotError = true; try { face.expressInterest(interest, counter, counter); gotError = false; } catch (Exception ex) { } if (!gotError) Fail("expressInterest didn't throw an exception when the interest size exceeds getMaxNdnPacketSize()"); }
public void getMatchedFilters(Interest interest, ArrayList matchedFilters) { for (int i = 0; i < table_.Count; ++i) { InterestFilterTable.Entry entry = table_[i]; if (entry.getFilter().doesMatch(interest.getName())) ILOG.J2CsMapping.Collections.Collections.Add(matchedFilters,entry); } }
/// <summary> /// Create a new interest as a deep copy of the given interest. /// </summary> /// /// <param name="interest">The interest to copy.</param> public Interest(Interest interest) { this.name_ = new ChangeCounter(new Name()); this.minSuffixComponents_ = -1; this.maxSuffixComponents_ = -1; this.keyLocator_ = new ChangeCounter( new KeyLocator()); this.exclude_ = new ChangeCounter(new Exclude()); this.childSelector_ = -1; this.mustBeFresh_ = true; this.interestLifetimeMilliseconds_ = -1; this.nonce_ = new Blob(); this.getNonceChangeCount_ = 0; this.lpPacket_ = null; this.linkWireEncoding_ = new Blob(); this.linkWireEncodingFormat_ = null; this.forwardingHint_ = new ChangeCounter( new DelegationSet()); this.parameters_ = new Blob(); this.link_ = new ChangeCounter(null); this.selectedDelegationIndex_ = -1; this.defaultWireEncoding_ = new SignedBlob(); this.getDefaultWireEncodingChangeCount_ = 0; this.changeCount_ = 0; name_.set(new Name(interest.getName())); minSuffixComponents_ = interest.minSuffixComponents_; maxSuffixComponents_ = interest.maxSuffixComponents_; keyLocator_.set(new KeyLocator(interest.getKeyLocator())); exclude_.set(new Exclude(interest.getExclude())); childSelector_ = interest.childSelector_; mustBeFresh_ = interest.mustBeFresh_; interestLifetimeMilliseconds_ = interest.interestLifetimeMilliseconds_; nonce_ = interest.getNonce(); forwardingHint_.set(new DelegationSet(interest.getForwardingHint())); parameters_ = interest.parameters_; linkWireEncoding_ = interest.linkWireEncoding_; linkWireEncodingFormat_ = interest.linkWireEncodingFormat_; if (interest.link_.get() != null) { link_.set(new Link((Link)interest.link_.get())); } selectedDelegationIndex_ = interest.selectedDelegationIndex_; setDefaultWireEncoding(interest.getDefaultWireEncoding(), interest.defaultWireEncodingFormat_); }
/// <summary> /// Do the work of expressInterest once we know we are connected. Add the entry /// to the PIT, encode and send the interest. /// </summary> /// /// <param name="pendingInterestId"></param> /// <param name="interestCopy"></param> /// <param name="onData"></param> /// <param name="onTimeout"></param> /// <param name="onNetworkNack"></param> /// <param name="wireFormat">A WireFormat object used to encode the message.</param> /// <param name="face"></param> /// <exception cref="IOException">For I/O error in sending the interest.</exception> /// <exception cref="System.Exception">If the encoded interest size exceeds getMaxNdnPacketSize().</exception> internal void expressInterestHelper(long pendingInterestId, Interest interestCopy, OnData onData, OnTimeout onTimeout, OnNetworkNack onNetworkNack, WireFormat wireFormat, Face face) { PendingInterestTable.Entry pendingInterest = pendingInterestTable_ .add(pendingInterestId, interestCopy, onData, onTimeout, onNetworkNack); if (pendingInterest == null) { // removePendingInterest was already called with the pendingInterestId. return; } if (onTimeout != null || interestCopy.getInterestLifetimeMilliseconds() >= 0.0d) { // Set up the timeout. double delayMilliseconds = interestCopy .getInterestLifetimeMilliseconds(); if (delayMilliseconds < 0.0d) { // Use a default timeout delay. delayMilliseconds = 4000.0d; } face.callLater(delayMilliseconds, new Node.Anonymous_C0(this, pendingInterest)); } // Special case: For timeoutPrefix_ we don't actually send the interest. if (!timeoutPrefix_.match(interestCopy.getName())) { Blob encoding = interestCopy.wireEncode(wireFormat); if (encoding.size() > getMaxNdnPacketSize()) { throw new Exception( "The encoded interest size exceeds the maximum limit getMaxNdnPacketSize()"); } transport_.send(encoding.buf()); } }
public void onTimeout(Interest interest) { if (retry_ > 0) { // Issue the same expressInterest as in verifyData except decrement // retry. KeyChain.VerifyCallbacksForVerifyInterest callbacks = new KeyChain.VerifyCallbacksForVerifyInterest ( outer_KeyChain, nextStep_, retry_ - 1, onValidationFailed_, originalInterest_); try { outer_KeyChain.face_.expressInterest(interest, callbacks, callbacks); } catch (IOException ex) { try { onValidationFailed_.onInterestValidationFailed( originalInterest_, "Error in expressInterest to retry after timeout for fetching " + interest.getName().toUri() + ": " + ex); } catch (Exception exception) { net.named_data.jndn.security.KeyChain.logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onInterestValidationFailed", exception); } } } else { try { onValidationFailed_.onInterestValidationFailed( originalInterest_, "The retry count is zero after timeout for fetching " + interest.getName().toUri()); } catch (Exception ex_0) { net.named_data.jndn.security.KeyChain.logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onInterestValidationFailed", ex_0); } } }
public void testEncodeDecodeInterestWithLink() { Link link1 = new Link(); link1.setName(new Name("test")); link1.addDelegation(10, new Name("/test1")); link1.addDelegation(20, new Name("/test2")); link1.addDelegation(100, new Name("/test3")); try { keyChain.sign(link1, certificateName); } catch (SecurityException ex) { Assert.Fail(ex.Message); } Interest interestA = new Interest(); interestA.setName(new Name("/Test/Encode/Decode/With/Link")); interestA.setChildSelector(1); interestA.setInterestLifetimeMilliseconds(10000); interestA.setLinkWireEncoding(link1.wireEncode()); Blob interestEncoding = interestA.wireEncode(); Interest interestB = new Interest(); try { interestB.wireDecode(interestEncoding); } catch (EncodingException ex_0) { Assert.Fail(ex_0.Message); } Assert.AssertEquals(interestA.getName(), interestB.getName()); Link link2 = null; try { link2 = interestB.getLink(); } catch (Exception ex_1) { Assert.Fail("interestB.getLink(): " + ex_1.Message); } Assert.AssertTrue("Interest link object not specified", link2 != null); DelegationSet delegations = link2.getDelegations(); for (int i = 0; i < delegations.size(); ++i) { if (i == 0) { Assert.AssertEquals(10, delegations.get(i).getPreference()); Assert.AssertEquals(new Name("/test1"), delegations.get(i).getName()); } if (i == 1) { Assert.AssertEquals(20, delegations.get(i).getPreference()); Assert.AssertEquals(new Name("/test2"), delegations.get(i).getName()); } if (i == 2) { Assert.AssertEquals(100, delegations.get(i).getPreference()); Assert.AssertEquals(new Name("/test3"), delegations.get(i).getName()); } } }
public void onInterest(Name prefix, Interest interest, Face face, long interestFilterId, InterestFilter filter) { ++interestCallbackCount[0]; Data data = new Data(interest.getName()); data.setContent(new Blob("SUCCESS")); try { outer_TestFaceCallRegisterMethods.keyChain.sign(data, outer_TestFaceCallRegisterMethods.certificateName); } catch (SecurityException ex) { net.named_data.jndn.tests.integration_tests.TestFaceCallRegisterMethods.logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex); } try { face.putData(data); } catch (IOException ex_0) { net.named_data.jndn.tests.integration_tests.TestFaceCallRegisterMethods.logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex_0); } }
/// <summary> /// Create a new interest as a deep copy of the given interest. /// </summary> /// /// <param name="interest">The interest to copy.</param> public Interest(Interest interest) { this.name_ = new ChangeCounter(new Name()); this.minSuffixComponents_ = -1; this.maxSuffixComponents_ = -1; this.keyLocator_ = new ChangeCounter( new KeyLocator()); this.exclude_ = new ChangeCounter(new Exclude()); this.childSelector_ = -1; this.mustBeFresh_ = true; this.interestLifetimeMilliseconds_ = -1; this.nonce_ = new Blob(); this.getNonceChangeCount_ = 0; this.lpPacket_ = null; this.linkWireEncoding_ = new Blob(); this.linkWireEncodingFormat_ = null; this.link_ = new ChangeCounter(null); this.selectedDelegationIndex_ = -1; this.defaultWireEncoding_ = new SignedBlob(); this.getDefaultWireEncodingChangeCount_ = 0; this.changeCount_ = 0; name_.set(new Name(interest.getName())); minSuffixComponents_ = interest.minSuffixComponents_; maxSuffixComponents_ = interest.maxSuffixComponents_; keyLocator_.set(new KeyLocator(interest.getKeyLocator())); exclude_.set(new Exclude(interest.getExclude())); childSelector_ = interest.childSelector_; mustBeFresh_ = interest.mustBeFresh_; interestLifetimeMilliseconds_ = interest.interestLifetimeMilliseconds_; nonce_ = interest.getNonce(); linkWireEncoding_ = interest.linkWireEncoding_; linkWireEncodingFormat_ = interest.linkWireEncodingFormat_; if (interest.link_.get() != null) link_.set(new Link((Link) interest.link_.get())); selectedDelegationIndex_ = interest.selectedDelegationIndex_; setDefaultWireEncoding(interest.getDefaultWireEncoding(), interest.defaultWireEncodingFormat_); }
private static ArrayList dumpInterest(Interest interest) { ArrayList result = new ArrayList(); ILOG.J2CsMapping.Collections.Collections.Add(result,dump("name:", interest.getName().toUri())); ILOG.J2CsMapping.Collections.Collections.Add(result,dump( "minSuffixComponents:", (interest.getMinSuffixComponents() >= 0) ? (Object) (interest.getMinSuffixComponents()) : (Object) ("<none>"))); ILOG.J2CsMapping.Collections.Collections.Add(result,dump( "maxSuffixComponents:", (interest.getMaxSuffixComponents() >= 0) ? (Object) (interest.getMaxSuffixComponents()) : (Object) ("<none>"))); if (interest.getKeyLocator().getType() != net.named_data.jndn.KeyLocatorType.NONE) { if (interest.getKeyLocator().getType() == net.named_data.jndn.KeyLocatorType.KEY_LOCATOR_DIGEST) ILOG.J2CsMapping.Collections.Collections.Add(result,dump("keyLocator: KeyLocatorDigest:", interest .getKeyLocator().getKeyData().toHex())); else if (interest.getKeyLocator().getType() == net.named_data.jndn.KeyLocatorType.KEYNAME) ILOG.J2CsMapping.Collections.Collections.Add(result,dump("keyLocator: KeyName:", interest .getKeyLocator().getKeyName().toUri())); else ILOG.J2CsMapping.Collections.Collections.Add(result,dump("keyLocator: <unrecognized KeyLocatorType")); } else ILOG.J2CsMapping.Collections.Collections.Add(result,dump("keyLocator: <none>")); ILOG.J2CsMapping.Collections.Collections.Add(result,dump("exclude:", (interest.getExclude().size() > 0) ? interest .getExclude().toUri() : "<none>")); ILOG.J2CsMapping.Collections.Collections.Add(result,dump("childSelector:", (interest.getChildSelector() >= 0) ? (Object) (interest.getChildSelector()) : (Object) ("<none>"))); ILOG.J2CsMapping.Collections.Collections.Add(result,dump("mustBeFresh:", (interest.getMustBeFresh()) ? "true" : "false")); ILOG.J2CsMapping.Collections.Collections.Add(result,dump("nonce:", (interest.getNonce().size() == 0) ? "<none>" : interest.getNonce().toHex())); ILOG.J2CsMapping.Collections.Collections.Add(result,dump("lifetimeMilliseconds:", (interest.getInterestLifetimeMilliseconds() < 0) ? "<none>" : "" + (long) interest.getInterestLifetimeMilliseconds())); return result; }
/// <summary> /// Append a SignatureInfo to the Interest name, sign the name components and /// append a final name component with the signature bits. /// </summary> /// /// <param name="interest"></param> /// <param name="certificateName">The certificate name of the key to use for signing.</param> /// <param name="wireFormat">A WireFormat object used to encode the input.</param> public void signInterestByCertificate(Interest interest, Name certificateName, WireFormat wireFormat) { DigestAlgorithm[] digestAlgorithm = new DigestAlgorithm[1]; Signature signature = makeSignatureByCertificate(certificateName, digestAlgorithm); // Append the encoded SignatureInfo. interest.getName().append(wireFormat.encodeSignatureInfo(signature)); // Append an empty signature so that the "signedPortion" is correct. interest.getName().append(new Name.Component()); // Encode once to get the signed portion, and sign. SignedBlob encoding = interest.wireEncode(wireFormat); signature.setSignature(privateKeyStorage_.sign(encoding.signedBuf(), net.named_data.jndn.security.certificate.IdentityCertificate .certificateNameToPublicKeyName(certificateName), digestAlgorithm[0])); // Remove the empty signature and append the real one. interest.setName(interest.getName().getPrefix(-1) .append(wireFormat.encodeSignatureValue(signature))); }
public void onInterest(Name prefix, Interest interest, Face face, long interestFilterId, InterestFilter filter) { ++responseCount_; // Make and sign a Data packet. var data = new Data(interest.getName()); var content = "Echo " + interest.getName().toUri(); data.setContent(new Blob(content)); try { keyChain_.sign(data, certificateName_); } catch (SecurityException exception) { // Don't expect this to happen. throw new SecurityException ("SecurityException in sign: " + exception); } Console.Out.WriteLine("Sent content " + content); try { face.putData(data); } catch (Exception ex) { Console.Out.WriteLine("Echo: Exception in sending data " + ex); } }
/// <summary> /// Use wireFormat.decodeSignatureInfoAndValue to decode the last two name /// components of the signed interest. Look in the IdentityStorage for the /// public key with the name in the KeyLocator (if available) and use it to /// verify the interest. If the public key can't be found, call onVerifyFailed. /// </summary> /// /// <param name="interest">The interest with the signature to check.</param> /// <param name="stepCount"></param> /// <param name="onVerified">NOTE: The library will log any exceptions thrown by this callback, but for better error handling the callback should catch and properly handle any exceptions.</param> /// <param name="onValidationFailed">onValidationFailed.onInterestValidationFailed(interest, reason). NOTE: The library will log any exceptions thrown by this callback, but for better error handling the callback should catch and properly handle any exceptions.</param> /// <returns>null for no further step for looking up a certificate chain.</returns> public override ValidationRequest checkVerificationPolicy(Interest interest, int stepCount, OnVerifiedInterest onVerified, OnInterestValidationFailed onValidationFailed, WireFormat wireFormat) { if (interest.getName().size() < 2) { try { onValidationFailed.onInterestValidationFailed(interest, "The signed interest has less than 2 components: " + interest.getName().toUri()); } catch (Exception exception) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onInterestValidationFailed", exception); } return null; } // Decode the last two name components of the signed interest Signature signature; try { signature = wireFormat.decodeSignatureInfoAndValue(interest .getName().get(-2).getValue().buf(), interest.getName() .get(-1).getValue().buf(), false); } catch (EncodingException ex) { logger_.log( ILOG.J2CsMapping.Util.Logging.Level.INFO, "Cannot decode the signed interest SignatureInfo and value", ex); try { onValidationFailed.onInterestValidationFailed(interest, "Error decoding the signed interest signature: " + ex); } catch (Exception exception_0) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onInterestValidationFailed", exception_0); } return null; } String[] failureReason = new String[] { "unknown" }; // wireEncode returns the cached encoding if available. if (verify(signature, interest.wireEncode(wireFormat), failureReason)) { try { onVerified.onVerifiedInterest(interest); } catch (Exception ex_1) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onVerifiedInterest", ex_1); } } else { try { onValidationFailed.onInterestValidationFailed(interest, failureReason[0]); } catch (Exception ex_2) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onInterestValidationFailed", ex_2); } } // No more steps, so return a null ValidationRequest. return null; }
/// <summary> /// Do the work of expressInterest once we know we are connected. Add the entry /// to the PIT, encode and send the interest. /// </summary> /// /// <param name="pendingInterestId"></param> /// <param name="interestCopy"></param> /// <param name="onData"></param> /// <param name="onTimeout"></param> /// <param name="onNetworkNack"></param> /// <param name="wireFormat">A WireFormat object used to encode the message.</param> /// <param name="face"></param> /// <exception cref="IOException">For I/O error in sending the interest.</exception> /// <exception cref="System.Exception">If the encoded interest size exceeds getMaxNdnPacketSize().</exception> internal void expressInterestHelper(long pendingInterestId, Interest interestCopy, OnData onData, OnTimeout onTimeout, OnNetworkNack onNetworkNack, WireFormat wireFormat, Face face) { PendingInterestTable.Entry pendingInterest = pendingInterestTable_ .add(pendingInterestId, interestCopy, onData, onTimeout, onNetworkNack); if (pendingInterest == null) // removePendingInterest was already called with the pendingInterestId. return; if (onTimeout != null || interestCopy.getInterestLifetimeMilliseconds() >= 0.0d) { // Set up the timeout. double delayMilliseconds = interestCopy .getInterestLifetimeMilliseconds(); if (delayMilliseconds < 0.0d) // Use a default timeout delay. delayMilliseconds = 4000.0d; face.callLater(delayMilliseconds, new Node.Anonymous_C0 (this, pendingInterest)); } // Special case: For timeoutPrefix_ we don't actually send the interest. if (!timeoutPrefix_.match(interestCopy.getName())) { Blob encoding = interestCopy.wireEncode(wireFormat); if (encoding.size() > getMaxNdnPacketSize()) throw new Exception( "The encoded interest size exceeds the maximum limit getMaxNdnPacketSize()"); transport_.send(encoding.buf()); } }
public void onInterest(Name prefix, Interest interest, Face face, long interestFilterId, InterestFilter filter) { doCleanup(); Name.Component selectedComponent = null; Blob selectedEncoding = null; // We need to iterate over both arrays. int totalSize = staleTimeCache_.Count + noStaleTimeCache_.Count; for (int i = 0; i < totalSize; ++i) { MemoryContentCache.Content content; if (i < staleTimeCache_.Count) content = staleTimeCache_[i]; else // We have iterated over the first array. Get from the second. content = noStaleTimeCache_[i - staleTimeCache_.Count]; if (interest.matchesName(content.getName())) { if (interest.getChildSelector() < 0) { // No child selector, so send the first match that we have found. try { face.send(content.getDataEncoding()); } catch (IOException ex) { ILOG.J2CsMapping.Util.Logging.Logger.getLogger(typeof(MemoryContentCache).FullName) .log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex); } return; } else { // Update selectedEncoding based on the child selector. Name.Component component; if (content.getName().size() > interest.getName().size()) component = content.getName().get( interest.getName().size()); else component = emptyComponent_; bool gotBetterMatch = false; if (selectedEncoding == null) // Save the first match. gotBetterMatch = true; else { if (interest.getChildSelector() == 0) { // Leftmost child. if (component.compare(selectedComponent) < 0) gotBetterMatch = true; } else { // Rightmost child. if (component.compare(selectedComponent) > 0) gotBetterMatch = true; } } if (gotBetterMatch) { selectedComponent = component; selectedEncoding = content.getDataEncoding(); } } } } if (selectedEncoding != null) { // We found the leftmost or rightmost child. try { face.send(selectedEncoding); } catch (IOException ex_0) { ILOG.J2CsMapping.Util.Logging.Logger.getLogger(typeof(MemoryContentCache).FullName).log( ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex_0); } } else { // Call the onDataNotFound callback (if defined). Object onDataNotFound = ILOG.J2CsMapping.Collections.Collections.Get(onDataNotFoundForPrefix_,prefix.toUri()); if (onDataNotFound != null) { try { ((OnInterestCallback) onDataNotFound).onInterest(prefix, interest, face, interestFilterId, filter); } catch (Exception ex_1) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onDataNotFound", ex_1); } } } }
/// <summary> /// This is called from an expressInterest OnData to check that the encryption /// key contained in data fits the timeSlot. This sends a refined interest if /// required. /// </summary> /// /// <param name="interest">The interest given to expressInterest.</param> /// <param name="data">The fetched Data packet.</param> /// <param name="timeSlot_0">The time slot as milliseconds since Jan 1, 1970 UTC.</param> /// <param name="onEncryptedKeys_1">encrypted content key Data packets. If onEncryptedKeys is null, this does not use it.</param> internal void handleCoveringKey(Interest interest, Data data, double timeSlot_0, Producer.OnEncryptedKeys onEncryptedKeys_1, net.named_data.jndn.encrypt.EncryptError.OnError onError_2) { double timeCount = Math.Round(timeSlot_0,MidpointRounding.AwayFromZero); Producer.KeyRequest keyRequest = (Producer.KeyRequest ) ILOG.J2CsMapping.Collections.Collections.Get(keyRequests_,timeCount); Name interestName = interest.getName(); Name keyName = data.getName(); double begin = net.named_data.jndn.encrypt.Schedule.fromIsoString(keyName .get(START_TIME_STAMP_INDEX).getValue().toString()); double end = net.named_data.jndn.encrypt.Schedule.fromIsoString(keyName.get(END_TIME_STAMP_INDEX) .getValue().toString()); if (timeSlot_0 >= end) { // If the received E-KEY covers some earlier period, try to retrieve an // E-KEY covering a later one. Exclude timeRange = new Exclude(interest.getExclude()); excludeBefore(timeRange, keyName.get(START_TIME_STAMP_INDEX)); ILOG.J2CsMapping.Collections.Collections.Put(keyRequest.repeatAttempts,interestName,0); sendKeyInterest(new Interest(interestName).setExclude(timeRange) .setChildSelector(1), timeSlot_0, onEncryptedKeys_1, onError_2); } else { // If the received E-KEY covers the content key, encrypt the content. Blob encryptionKey = data.getContent(); // If everything is correct, save the E-KEY as the current key. if (encryptContentKey(encryptionKey, keyName, timeSlot_0, onEncryptedKeys_1, onError_2)) { Producer.KeyInfo keyInfo = (Producer.KeyInfo ) ILOG.J2CsMapping.Collections.Collections.Get(eKeyInfo_,interestName); keyInfo.beginTimeSlot = begin; keyInfo.endTimeSlot = end; keyInfo.keyBits = encryptionKey; } } }
/// <summary> /// Extract the signature information from the interest name. /// </summary> /// /// <param name="interest">The interest whose signature is needed.</param> /// <param name="wireFormat"></param> /// <param name="failureReason"></param> /// <returns>A shared_ptr for the Signature object. This is null if can't decode.</returns> private static Signature extractSignature(Interest interest, WireFormat wireFormat, String[] failureReason) { if (interest.getName().size() < 2) { failureReason[0] = "The signed interest has less than 2 components: " + interest.getName().toUri(); return null; } try { return wireFormat.decodeSignatureInfoAndValue(interest.getName() .get(-2).getValue().buf(), interest.getName().get(-1) .getValue().buf(), false); } catch (EncodingException ex) { failureReason[0] = "Error decoding the signed interest signature: " + ex; return null; } }
/// <summary> /// Check whether the received signed interest complies with the verification /// policy, and get the indication of the next verification step. /// </summary> /// /// <param name="interest">The interest with the signature to check.</param> /// <param name="stepCount"></param> /// <param name="onVerified">better error handling the callback should catch and properly handle any exceptions.</param> /// <param name="onValidationFailed">NOTE: The library will log any exceptions thrown by this callback, but for better error handling the callback should catch and properly handle any exceptions.</param> /// <returns>the indication of next verification step, null if there is no /// further step.</returns> public override sealed ValidationRequest checkVerificationPolicy(Interest interest, int stepCount, OnVerifiedInterest onVerified, OnInterestValidationFailed onValidationFailed, WireFormat wireFormat) { String[] failureReason = new String[] { "unknown" }; Signature signature = extractSignature(interest, wireFormat, failureReason); if (signature == null) { // Can't get the signature from the interest name. try { onValidationFailed.onInterestValidationFailed(interest, failureReason[0]); } catch (Exception ex) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onInterestValidationFailed", ex); } return null; } // For command interests, we need to ignore the last 4 components when // matching the name. Interest certificateInterest = getCertificateInterest(stepCount, "interest", interest.getName().getPrefix(-4), signature, failureReason); if (certificateInterest == null) { try { onValidationFailed.onInterestValidationFailed(interest, failureReason[0]); } catch (Exception ex_0) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onInterestValidationFailed", ex_0); } return null; } if (certificateInterest.getName().size() > 0) return new ValidationRequest(certificateInterest, new ConfigPolicyManager.OnCertificateDownloadCompleteForInterest (this, interest, stepCount, onVerified, onValidationFailed, wireFormat), new ConfigPolicyManager.OnVerifyInterestFailedWrapper ( onValidationFailed, interest), 2, stepCount + 1); else { // For interests, we must check that the timestamp is fresh enough. // This is done after (possibly) downloading the certificate to avoid filling // the cache with bad keys. Name signatureName = net.named_data.jndn.KeyLocator.getFromSignature(signature) .getKeyName(); Name keyName = net.named_data.jndn.security.certificate.IdentityCertificate .certificateNameToPublicKeyName(signatureName); double timestamp = interest.getName().get(-4).toNumber(); if (!interestTimestampIsFresh(keyName, timestamp, failureReason)) { try { onValidationFailed.onInterestValidationFailed(interest, failureReason[0]); } catch (Exception ex_1) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onInterestValidationFailed", ex_1); } return null; } // Certificate is known. Verify the signature. // wireEncode returns the cached encoding if available. if (verify(signature, interest.wireEncode(), failureReason)) { try { onVerified.onVerifiedInterest(interest); } catch (Exception ex_2) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onVerifiedInterest", ex_2); } updateTimestampForKey(keyName, timestamp); } else { try { onValidationFailed.onInterestValidationFailed(interest, failureReason[0]); } catch (Exception ex_3) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onInterestValidationFailed", ex_3); } } return null; } }
public virtual void onTimeout(Interest interest) { try { onError_.onError(net.named_data.jndn.util.SegmentFetcher.ErrorCode.INTEREST_TIMEOUT, "Time out for interest " + interest.getName().toUri()); } catch (Exception ex) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", ex); } }
/// <summary> /// This is called from an expressInterest timeout to update the state of /// keyRequest. Re-express the interest if the number of retrials is less than /// the max limit. /// </summary> /// /// <param name="interest">The timed-out interest.</param> /// <param name="timeSlot_0">The time slot as milliseconds since Jan 1, 1970 UTC.</param> /// <param name="onEncryptedKeys_1">encrypted content key Data packets. If onEncryptedKeys is null, this does not use it.</param> internal void handleTimeout(Interest interest, double timeSlot_0, Producer.OnEncryptedKeys onEncryptedKeys_1, net.named_data.jndn.encrypt.EncryptError.OnError onError_2) { double timeCount = Math.Round(timeSlot_0,MidpointRounding.AwayFromZero); Producer.KeyRequest keyRequest = (Producer.KeyRequest ) ILOG.J2CsMapping.Collections.Collections.Get(keyRequests_,timeCount); Name interestName = interest.getName(); if ((int) (Int32) ILOG.J2CsMapping.Collections.Collections.Get(keyRequest.repeatAttempts,interestName) < maxRepeatAttempts_) { // Increase the retrial count. ILOG.J2CsMapping.Collections.Collections.Put(keyRequest.repeatAttempts,interestName,(int) (Int32) ILOG.J2CsMapping.Collections.Collections.Get(keyRequest.repeatAttempts,interestName) + 1); sendKeyInterest(interest, timeSlot_0, onEncryptedKeys_1, onError_2); } else // No more retrials. updateKeyRequest(keyRequest, timeCount, onEncryptedKeys_1); }
/// <summary> /// Do the work of registerPrefix to register with NFD. /// </summary> /// /// <param name="registeredPrefixId">registeredPrefixTable_ (assuming it has already been done).</param> /// <param name="prefix"></param> /// <param name="onInterest"></param> /// <param name="onRegisterFailed"></param> /// <param name="onRegisterSuccess"></param> /// <param name="flags"></param> /// <param name="commandKeyChain"></param> /// <param name="commandCertificateName"></param> /// <param name="wireFormat_0"></param> /// <param name="face_1"></param> /// <exception cref="System.Security.SecurityException">If cannot find the private key for thecertificateName.</exception> private void nfdRegisterPrefix(long registeredPrefixId, Name prefix, OnInterestCallback onInterest, OnRegisterFailed onRegisterFailed, OnRegisterSuccess onRegisterSuccess, ForwardingFlags flags, KeyChain commandKeyChain, Name commandCertificateName, WireFormat wireFormat_0, Face face_1) { if (commandKeyChain == null) throw new Exception( "registerPrefix: The command KeyChain has not been set. You must call setCommandSigningInfo."); if (commandCertificateName.size() == 0) throw new Exception( "registerPrefix: The command certificate name has not been set. You must call setCommandSigningInfo."); ControlParameters controlParameters = new ControlParameters(); controlParameters.setName(prefix); controlParameters.setForwardingFlags(flags); Interest commandInterest = new Interest(); // Determine whether to use remote prefix registration. bool faceIsLocal; try { faceIsLocal = isLocal(); } catch (IOException ex) { logger_.log( ILOG.J2CsMapping.Util.Logging.Level.INFO, "Register prefix failed: Error attempting to determine if the face is local: {0}", ex); try { onRegisterFailed.onRegisterFailed(prefix); } catch (Exception exception) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterFailed", exception); } return; } if (faceIsLocal) { commandInterest.setName(new Name("/localhost/nfd/rib/register")); // The interest is answered by the local host, so set a short timeout. commandInterest.setInterestLifetimeMilliseconds(2000.0d); } else { commandInterest.setName(new Name("/localhop/nfd/rib/register")); // The host is remote, so set a longer timeout. commandInterest.setInterestLifetimeMilliseconds(4000.0d); } // NFD only accepts TlvWireFormat packets. commandInterest.getName().append( controlParameters.wireEncode(net.named_data.jndn.encoding.TlvWireFormat.get())); makeCommandInterest(commandInterest, commandKeyChain, commandCertificateName, net.named_data.jndn.encoding.TlvWireFormat.get()); // Send the registration interest. Node.RegisterResponse response = new Node.RegisterResponse ( new RegisterResponse.Info(prefix, onRegisterFailed, onRegisterSuccess, registeredPrefixId, onInterest, face_1), this); try { expressInterest(getNextEntryId(), commandInterest, response, response, null, wireFormat_0, face_1); } catch (IOException ex_2) { // Can't send the interest. Call onRegisterFailed. logger_.log( ILOG.J2CsMapping.Util.Logging.Level.INFO, "Register prefix failed: Error sending the register prefix interest to the forwarder: {0}", ex_2); try { onRegisterFailed.onRegisterFailed(prefix); } catch (Exception exception_3) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterFailed", exception_3); } } }
static void dumpInterest(Interest interest) { Console.Out.WriteLine("name: " + interest.getName().toUri()); Console.Out.WriteLine("minSuffixComponents: " + (interest.getMinSuffixComponents() >= 0 ? "" + interest.getMinSuffixComponents() : "<none>")); Console.Out.WriteLine("maxSuffixComponents: " + (interest.getMaxSuffixComponents() >= 0 ? "" + interest.getMaxSuffixComponents() : "<none>")); Console.Out.Write("keyLocator: "); if (interest.getKeyLocator().getType() == KeyLocatorType.NONE) Console.Out.WriteLine("<none>"); else if (interest.getKeyLocator().getType() ==KeyLocatorType.KEY_LOCATOR_DIGEST) Console.Out.WriteLine("KeyLocatorDigest: " + interest.getKeyLocator().getKeyData().toHex()); else if (interest.getKeyLocator().getType() == KeyLocatorType.KEYNAME) Console.Out.WriteLine("KeyName: " + interest.getKeyLocator().getKeyName().toUri()); else Console.Out.WriteLine("<unrecognized ndn_KeyLocatorType>"); Console.Out.WriteLine ("exclude: " + (interest.getExclude().size() > 0 ? interest.getExclude().toUri() : "<none>")); Console.Out.WriteLine("lifetimeMilliseconds: " + (interest.getInterestLifetimeMilliseconds() >= 0 ? "" + interest.getInterestLifetimeMilliseconds() : "<none>")); Console.Out.WriteLine("childSelector: " + (interest.getChildSelector() >= 0 ? "" + interest.getChildSelector() : "<none>")); Console.Out.WriteLine("mustBeFresh: " + interest.getMustBeFresh()); Console.Out.WriteLine("nonce: " + (interest.getNonce().size() > 0 ? "" + interest.getNonce().toHex() : "<none>")); }
/// <summary> /// Do the work of registerPrefix to register with NFD. /// </summary> /// /// <param name="registeredPrefixId">registeredPrefixTable_ (assuming it has already been done).</param> /// <param name="prefix"></param> /// <param name="onInterest"></param> /// <param name="onRegisterFailed"></param> /// <param name="onRegisterSuccess"></param> /// <param name="flags"></param> /// <param name="commandKeyChain"></param> /// <param name="commandCertificateName"></param> /// <param name="wireFormat_0"></param> /// <param name="face_1"></param> /// <exception cref="System.Security.SecurityException">If cannot find the private key for thecertificateName.</exception> private void nfdRegisterPrefix(long registeredPrefixId, Name prefix, OnInterestCallback onInterest, OnRegisterFailed onRegisterFailed, OnRegisterSuccess onRegisterSuccess, ForwardingFlags flags, KeyChain commandKeyChain, Name commandCertificateName, WireFormat wireFormat_0, Face face_1) { if (commandKeyChain == null) { throw new Exception( "registerPrefix: The command KeyChain has not been set. You must call setCommandSigningInfo."); } if (commandCertificateName.size() == 0) { throw new Exception( "registerPrefix: The command certificate name has not been set. You must call setCommandSigningInfo."); } ControlParameters controlParameters = new ControlParameters(); controlParameters.setName(prefix); controlParameters.setForwardingFlags(flags); Interest commandInterest = new Interest(); // Determine whether to use remote prefix registration. bool faceIsLocal; try { faceIsLocal = isLocal(); } catch (IOException ex) { logger_.log( ILOG.J2CsMapping.Util.Logging.Level.INFO, "Register prefix failed: Error attempting to determine if the face is local: {0}", ex); try { onRegisterFailed.onRegisterFailed(prefix); } catch (Exception exception) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterFailed", exception); } return; } if (faceIsLocal) { commandInterest.setName(new Name("/localhost/nfd/rib/register")); // The interest is answered by the local host, so set a short timeout. commandInterest.setInterestLifetimeMilliseconds(2000.0d); } else { commandInterest.setName(new Name("/localhop/nfd/rib/register")); // The host is remote, so set a longer timeout. commandInterest.setInterestLifetimeMilliseconds(4000.0d); } // NFD only accepts TlvWireFormat packets. commandInterest.getName().append( controlParameters.wireEncode(net.named_data.jndn.encoding.TlvWireFormat.get())); makeCommandInterest(commandInterest, commandKeyChain, commandCertificateName, net.named_data.jndn.encoding.TlvWireFormat.get()); // Send the registration interest. Node.RegisterResponse response = new Node.RegisterResponse( new RegisterResponse.Info(prefix, onRegisterFailed, onRegisterSuccess, registeredPrefixId, onInterest, face_1), this); try { expressInterest(getNextEntryId(), commandInterest, response, response, null, wireFormat_0, face_1); } catch (IOException ex_2) { // Can't send the interest. Call onRegisterFailed. logger_.log( ILOG.J2CsMapping.Util.Logging.Level.INFO, "Register prefix failed: Error sending the register prefix interest to the forwarder: {0}", ex_2); try { onRegisterFailed.onRegisterFailed(prefix); } catch (Exception exception_3) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterFailed", exception_3); } } }
/// <summary> /// Decode input as an interest in NDN-TLV and set the fields of the interest /// object. /// </summary> /// /// <param name="interest">The Interest object whose fields are updated.</param> /// <param name="input"></param> /// <param name="signedPortionBeginOffset">name component and ends just before the final name component (which is assumed to be a signature for a signed interest).</param> /// <param name="signedPortionEndOffset">name component and ends just before the final name component (which is assumed to be a signature for a signed interest).</param> /// <param name="copy">unchanged while the Blob values are used.</param> /// <exception cref="EncodingException">For invalid encoding.</exception> public override void decodeInterest(Interest interest, ByteBuffer input, int[] signedPortionBeginOffset, int[] signedPortionEndOffset, bool copy) { TlvDecoder decoder = new TlvDecoder(input); int endOffset = decoder.readNestedTlvsStart(net.named_data.jndn.encoding.tlv.Tlv.Interest); decodeName(interest.getName(), signedPortionBeginOffset, signedPortionEndOffset, decoder, copy); if (decoder.peekType(net.named_data.jndn.encoding.tlv.Tlv.Selectors, endOffset)) decodeSelectors(interest, decoder, copy); // Require a Nonce, but don't force it to be 4 bytes. ByteBuffer nonce = decoder.readBlobTlv(net.named_data.jndn.encoding.tlv.Tlv.Nonce); interest.setInterestLifetimeMilliseconds(decoder .readOptionalNonNegativeIntegerTlv(net.named_data.jndn.encoding.tlv.Tlv.InterestLifetime, endOffset)); if (decoder.peekType(net.named_data.jndn.encoding.tlv.Tlv.Data, endOffset)) { // Get the bytes of the Link TLV. int linkBeginOffset = decoder.getOffset(); int linkEndOffset = decoder.readNestedTlvsStart(net.named_data.jndn.encoding.tlv.Tlv.Data); decoder.seek(linkEndOffset); interest.setLinkWireEncoding( new Blob(decoder.getSlice(linkBeginOffset, linkEndOffset), copy), this); } else interest.unsetLink(); interest.setSelectedDelegationIndex((int) decoder .readOptionalNonNegativeIntegerTlv(net.named_data.jndn.encoding.tlv.Tlv.SelectedDelegation, endOffset)); if (interest.getSelectedDelegationIndex() >= 0 && !interest.hasLink()) throw new EncodingException( "Interest has a selected delegation, but no link object"); // Set the nonce last because setting other interest fields clears it. interest.setNonce(new Blob(nonce, copy)); decoder.finishNestedTlvs(endOffset); }
static void Main(string[] args) { var interest = new Interest(); interest.wireDecode(new Blob(TlvInterest)); Console.Out.WriteLine("Interest:"); dumpInterest(interest); // Set the name again to clear the cached encoding so we encode again. interest.setName(interest.getName()); var encoding = interest.wireEncode(); Console.Out.WriteLine(""); Console.Out.WriteLine("Re-encoded interest " + encoding.toHex()); var reDecodedInterest = new Interest(); reDecodedInterest.wireDecode(encoding); Console.Out.WriteLine(""); Console.Out.WriteLine("Re-decoded Interest:"); dumpInterest(reDecodedInterest); var freshInterest = new Interest(new Name("/ndn/abc")); freshInterest.setMinSuffixComponents(4); freshInterest.setMaxSuffixComponents(6); freshInterest.setInterestLifetimeMilliseconds(30000); freshInterest.setChildSelector(1); freshInterest.setMustBeFresh(true); freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST); freshInterest.getKeyLocator().setKeyData (new Blob(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F })); freshInterest.getExclude().appendComponent(new Name("abc").get(0)).appendAny(); var identityStorage = new MemoryIdentityStorage(); var privateKeyStorage = new MemoryPrivateKeyStorage(); var keyChain = new KeyChain (new IdentityManager(identityStorage, privateKeyStorage), new SelfVerifyPolicyManager(identityStorage)); // Initialize the storage. var keyName = new Name("/testname/DSK-123"); var certificateName = keyName.getSubName(0, keyName.size() - 1).append ("KEY").append(keyName.get(-1)).append("ID-CERT").append("0"); identityStorage.addKey(keyName, KeyType.RSA, new Blob(DEFAULT_RSA_PUBLIC_KEY_DER)); privateKeyStorage.setKeyPairForKeyName (keyName, KeyType.RSA, new ByteBuffer(DEFAULT_RSA_PUBLIC_KEY_DER), new ByteBuffer(DEFAULT_RSA_PRIVATE_KEY_DER)); // Make a Face just so that we can sign the interest. var face = new Face("localhost"); face.setCommandSigningInfo(keyChain, certificateName); face.makeCommandInterest(freshInterest); Interest reDecodedFreshInterest = new Interest(); reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()); Console.Out.WriteLine(""); Console.Out.WriteLine("Re-decoded fresh Interest:"); dumpInterest(reDecodedFreshInterest); VerifyCallbacks callbacks = new VerifyCallbacks("Freshly-signed Interest"); keyChain.verifyInterest(reDecodedFreshInterest, callbacks, callbacks); }
/// <summary> /// Encode interest using NDN-TLV and return the encoding. /// </summary> /// /// <param name="interest">The Interest object to encode.</param> /// <param name="signedPortionBeginOffset">name component and ends just before the final name component (which is assumed to be a signature for a signed interest).</param> /// <param name="signedPortionEndOffset">name component and ends just before the final name component (which is assumed to be a signature for a signed interest).</param> /// <returns>A Blob containing the encoding.</returns> public override Blob encodeInterest(Interest interest, int[] signedPortionBeginOffset, int[] signedPortionEndOffset) { TlvEncoder encoder = new TlvEncoder(); int saveLength = encoder.getLength(); // Encode backwards. encoder.writeOptionalNonNegativeIntegerTlv(net.named_data.jndn.encoding.tlv.Tlv.SelectedDelegation, interest.getSelectedDelegationIndex()); try { Blob linkWireEncoding = interest.getLinkWireEncoding(this); if (!linkWireEncoding.isNull()) // Encode the entire link as is. encoder.writeBuffer(linkWireEncoding.buf()); } catch (EncodingException ex) { throw new Exception(ex.Message); } encoder.writeOptionalNonNegativeIntegerTlvFromDouble( net.named_data.jndn.encoding.tlv.Tlv.InterestLifetime, interest.getInterestLifetimeMilliseconds()); // Encode the Nonce as 4 bytes. if (interest.getNonce().size() == 0) { // This is the most common case. Generate a nonce. ByteBuffer nonce = ILOG.J2CsMapping.NIO.ByteBuffer.allocate(4); random_.nextBytes(nonce.array()); encoder.writeBlobTlv(net.named_data.jndn.encoding.tlv.Tlv.Nonce, nonce); } else if (interest.getNonce().size() < 4) { ByteBuffer nonce_0 = ILOG.J2CsMapping.NIO.ByteBuffer.allocate(4); // Copy existing nonce bytes. nonce_0.put(interest.getNonce().buf()); // Generate random bytes for remaining bytes in the nonce. for (int i = 0; i < 4 - interest.getNonce().size(); ++i) nonce_0.put((byte) random_.Next()); nonce_0.flip(); encoder.writeBlobTlv(net.named_data.jndn.encoding.tlv.Tlv.Nonce, nonce_0); } else if (interest.getNonce().size() == 4) // Use the nonce as-is. encoder.writeBlobTlv(net.named_data.jndn.encoding.tlv.Tlv.Nonce, interest.getNonce().buf()); else { // Truncate. ByteBuffer nonce_1 = interest.getNonce().buf(); // buf() returns a new ByteBuffer, so we can change its limit. nonce_1.limit(nonce_1.position() + 4); encoder.writeBlobTlv(net.named_data.jndn.encoding.tlv.Tlv.Nonce, nonce_1); } encodeSelectors(interest, encoder); int[] tempSignedPortionBeginOffset = new int[1]; int[] tempSignedPortionEndOffset = new int[1]; encodeName(interest.getName(), tempSignedPortionBeginOffset, tempSignedPortionEndOffset, encoder); int signedPortionBeginOffsetFromBack = encoder.getLength() - tempSignedPortionBeginOffset[0]; int signedPortionEndOffsetFromBack = encoder.getLength() - tempSignedPortionEndOffset[0]; encoder.writeTypeAndLength(net.named_data.jndn.encoding.tlv.Tlv.Interest, encoder.getLength() - saveLength); signedPortionBeginOffset[0] = encoder.getLength() - signedPortionBeginOffsetFromBack; signedPortionEndOffset[0] = encoder.getLength() - signedPortionEndOffsetFromBack; return new Blob(encoder.getOutput(), false); }
/// <summary> /// Append a SignatureInfo for DigestSha256 to the Interest name, digest the /// name components and append a final name component with the signature bits /// (which is the digest). /// </summary> /// /// <param name="interest"></param> /// <param name="wireFormat">A WireFormat object used to encode the input.</param> public void signInterestWithSha256(Interest interest, WireFormat wireFormat) { DigestSha256Signature signature = new DigestSha256Signature(); // Append the encoded SignatureInfo. interest.getName().append(wireFormat.encodeSignatureInfo(signature)); // Append an empty signature so that the "signedPortion" is correct. interest.getName().append(new Name.Component()); // Encode once to get the signed portion. SignedBlob encoding = interest.wireEncode(wireFormat); // Digest and set the signature. byte[] signedPortionDigest = net.named_data.jndn.util.Common.digestSha256(encoding.signedBuf()); signature.setSignature(new Blob(signedPortionDigest, false)); // Remove the empty signature and append the real one. interest.setName(interest.getName().getPrefix(-1) .append(wireFormat.encodeSignatureValue(signature))); }
public void testMatchesData() { Interest interest = new Interest(new Name("/A")); interest.setMinSuffixComponents(2); interest.setMaxSuffixComponents(2); interest.getKeyLocator().setType(net.named_data.jndn.KeyLocatorType.KEYNAME); interest.getKeyLocator().setKeyName(new Name("/B")); interest.getExclude().appendComponent(new Name.Component("J")); interest.getExclude().appendAny(); Data data = new Data(new Name("/A/D")); Sha256WithRsaSignature signature = new Sha256WithRsaSignature(); signature.getKeyLocator().setType(net.named_data.jndn.KeyLocatorType.KEYNAME); signature.getKeyLocator().setKeyName(new Name("/B")); data.setSignature(signature); Assert.AssertEquals(true, interest.matchesData(data)); // Check violating MinSuffixComponents. Data data1 = new Data(data); data1.setName(new Name("/A")); Assert.AssertEquals(false, interest.matchesData(data1)); Interest interest1 = new Interest(interest); interest1.setMinSuffixComponents(1); Assert.AssertEquals(true, interest1.matchesData(data1)); // Check violating MaxSuffixComponents. Data data2 = new Data(data); data2.setName(new Name("/A/E/F")); Assert.AssertEquals(false, interest.matchesData(data2)); Interest interest2 = new Interest(interest); interest2.setMaxSuffixComponents(3); Assert.AssertEquals(true, interest2.matchesData(data2)); // Check violating PublisherPublicKeyLocator. Data data3 = new Data(data); Sha256WithRsaSignature signature3 = new Sha256WithRsaSignature(); signature3.getKeyLocator().setType(net.named_data.jndn.KeyLocatorType.KEYNAME); signature3.getKeyLocator().setKeyName(new Name("/G")); data3.setSignature(signature3); Assert.AssertEquals(false, interest.matchesData(data3)); Interest interest3 = new Interest(interest); interest3.getKeyLocator().setType(net.named_data.jndn.KeyLocatorType.KEYNAME); interest3.getKeyLocator().setKeyName(new Name("/G")); Assert.AssertEquals(true, interest3.matchesData(data3)); Data data4 = new Data(data); data4.setSignature(new DigestSha256Signature()); Assert.AssertEquals(false, interest.matchesData(data4)); Interest interest4 = new Interest(interest); interest4.setKeyLocator(new KeyLocator()); Assert.AssertEquals(true, interest4.matchesData(data4)); // Check violating Exclude. Data data5 = new Data(data); data5.setName(new Name("/A/J")); Assert.AssertEquals(false, interest.matchesData(data5)); Interest interest5 = new Interest(interest); interest5.getExclude().clear(); interest5.getExclude().appendComponent(new Name.Component("K")); interest5.getExclude().appendAny(); Assert.AssertEquals(true, interest5.matchesData(data5)); // Check violating Name. Data data6 = new Data(data); data6.setName(new Name("/H/I")); Assert.AssertEquals(false, interest.matchesData(data6)); Data data7 = new Data(data); data7.setName(new Name("/A/B")); Interest interest7 = new Interest( new Name( "/A/B/sha256digest=" + "54008e240a7eea2714a161dfddf0dd6ced223b3856e9da96792151e180f3b128")); Assert.AssertEquals(true, interest7.matchesData(data7)); // Check violating the implicit digest. Interest interest7b = new Interest(new Name( "/A/B/%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00" + "%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00")); Assert.AssertEquals(false, interest7b.matchesData(data7)); // Check excluding the implicit digest. Interest interest8 = new Interest(new Name("/A/B")); interest8.getExclude().appendComponent(interest7.getName().get(2)); Assert.AssertEquals(false, interest8.matchesData(data7)); }