public void testGenericSignature() { // Test correct encoding. GenericSignature signature = new GenericSignature(); signature.setSignatureInfoEncoding(new Blob(experimentalSignatureInfo, false), -1); Blob signatureValue = new Blob(toBuffer(new int[] { 1, 2, 3, 4 }), false); signature.setSignature(signatureValue); freshData.setSignature(signature); Blob encoding = freshData.wireEncode(); Data decodedData = new Data(); try { decodedData.wireDecode(encoding); } catch (EncodingException ex) { Assert.Fail("Error decoding Data with GenericSignature: " + ex); } GenericSignature decodedSignature = (GenericSignature) decodedData .getSignature(); Assert.AssertEquals(experimentalSignatureType, decodedSignature.getTypeCode()); Assert.AssertTrue(new Blob(experimentalSignatureInfo, false) .equals(decodedSignature.getSignatureInfoEncoding())); Assert.AssertTrue(signatureValue.equals(decodedSignature.getSignature())); // Test bad encoding. signature = new GenericSignature(); signature.setSignatureInfoEncoding(new Blob( experimentalSignatureInfoNoSignatureType, false), -1); signature.setSignature(signatureValue); freshData.setSignature(signature); bool gotError = true; try { freshData.wireEncode(); gotError = false; } catch (Exception ex_0) { } if (!gotError) Assert.Fail("Expected encoding error for experimentalSignatureInfoNoSignatureType"); signature = new GenericSignature(); signature.setSignatureInfoEncoding(new Blob( experimentalSignatureInfoBadTlv, false), -1); signature.setSignature(signatureValue); freshData.setSignature(signature); gotError = true; try { freshData.wireEncode(); gotError = false; } catch (Exception ex_1) { } if (!gotError) Assert.Fail("Expected encoding error for experimentalSignatureInfoBadTlv"); }
/// <summary> /// Compute a new HmacWithSha256 for the data packet and verify it against the /// signature value. /// </summary> /// /// @note This method is an experimental feature. The API may change. /// <param name="data">The Data packet to verify.</param> /// <param name="key">The key for the HmacWithSha256.</param> /// <param name="wireFormat">A WireFormat object used to encode the data packet.</param> /// <returns>True if the signature verifies, otherwise false.</returns> public static bool verifyDataWithHmacWithSha256(Data data, Blob key, WireFormat wireFormat) { // wireEncode returns the cached encoding if available. SignedBlob encoding = data.wireEncode(wireFormat); byte[] newSignatureBytes = net.named_data.jndn.util.Common.computeHmacWithSha256( key.getImmutableArray(), encoding.signedBuf()); return ILOG.J2CsMapping.NIO.ByteBuffer.wrap(newSignatureBytes).equals( data.getSignature().getSignature().buf()); }
public void testEmptySignature() { // make sure nothing is set in the signature of newly created data Data data = new Data(); Sha256WithRsaSignature signature = (Sha256WithRsaSignature) data .getSignature(); Assert.AssertTrue("Key locator type on unsigned data should not be set", signature.getKeyLocator().getType() == net.named_data.jndn.KeyLocatorType.NONE); Assert.AssertTrue("Non-empty signature on unsigned data", signature .getSignature().isNull()); }
/// <summary> /// Create a deep copy of the given data object, including a clone of the /// signature object. /// </summary> /// /// <param name="data">The data object to copy.</param> public Data(Data data) { this.signature_ = new ChangeCounter( new Sha256WithRsaSignature()); this.name_ = new ChangeCounter(new Name()); this.metaInfo_ = new ChangeCounter(new MetaInfo()); this.content_ = new Blob(); this.lpPacket_ = null; this.defaultWireEncoding_ = new SignedBlob(); this.getDefaultWireEncodingChangeCount_ = 0; this.changeCount_ = 0; try { signature_ .set((data.signature_ == null) ? (net.named_data.jndn.util.ChangeCountable)(new Sha256WithRsaSignature()) : (net.named_data.jndn.util.ChangeCountable)((Signature)data.getSignature().Clone())); } catch (Exception e) { // We don't expect this to happen, so just treat it as if we got a null pointer. throw new NullReferenceException( "Data.setSignature: unexpected exception in clone(): " + e.Message); } name_.set(new Name(data.getName())); metaInfo_.set(new MetaInfo(data.getMetaInfo())); content_ = data.content_; setDefaultWireEncoding(data.defaultWireEncoding_, null); }
/// <summary> /// Wire encode the data packet, compute an HmacWithSha256 and update the /// signature value. /// </summary> /// /// @note This method is an experimental feature. The API may change. /// <param name="data">The Data object to be signed. This updates its signature.</param> /// <param name="key">The key for the HmacWithSha256.</param> /// <param name="wireFormat">A WireFormat object used to encode the data packet.</param> public static void signWithHmacWithSha256(Data data, Blob key, WireFormat wireFormat) { // Encode once to get the signed portion. SignedBlob encoding = data.wireEncode(wireFormat); byte[] signatureBytes = net.named_data.jndn.util.Common.computeHmacWithSha256( key.getImmutableArray(), encoding.signedBuf()); data.getSignature().setSignature(new Blob(signatureBytes, false)); }
static void dumpData(Data data) { Console.Out.WriteLine("name: " + data.getName().toUri()); if (data.getContent().size() > 0) { Console.Out.Write("content (raw): "); var buf = data.getContent().buf(); while(buf.remaining() > 0) Console.Out.Write((char)buf.get()); Console.Out.WriteLine(""); Console.Out.WriteLine("content (hex): " + data.getContent().toHex()); } else Console.Out.WriteLine("content: <empty>"); if (!(data.getMetaInfo().getType() == ContentType.BLOB)) { Console.Out.Write("metaInfo.type: "); if (data.getMetaInfo().getType() == ContentType.KEY) Console.Out.WriteLine("KEY"); else if (data.getMetaInfo().getType() == ContentType.LINK) Console.Out.WriteLine("LINK"); else if (data.getMetaInfo().getType() == ContentType.NACK) Console.Out.WriteLine("NACK"); else if (data.getMetaInfo().getType() == ContentType.OTHER_CODE) Console.Out.WriteLine("other code " + data.getMetaInfo().getOtherTypeCode()); } Console.Out.WriteLine("metaInfo.freshnessPeriod (milliseconds): " + (data.getMetaInfo().getFreshnessPeriod() >= 0 ? "" + data.getMetaInfo().getFreshnessPeriod() : "<none>")); Console.Out.WriteLine("metaInfo.finalBlockId: " + (data.getMetaInfo().getFinalBlockId().getValue().size() > 0 ? data.getMetaInfo().getFinalBlockId().getValue().toHex() : "<none>")); KeyLocator keyLocator = null; if (data.getSignature() is Sha256WithRsaSignature) { var signature = (Sha256WithRsaSignature)data.getSignature(); Console.Out.WriteLine("Sha256WithRsa signature.signature: " + (signature.getSignature().size() > 0 ? signature.getSignature().toHex() : "<none>")); keyLocator = signature.getKeyLocator(); } else if (data.getSignature() is Sha256WithEcdsaSignature) { var signature = (Sha256WithEcdsaSignature)data.getSignature(); Console.Out.WriteLine("Sha256WithEcdsa signature.signature: " + (signature.getSignature().size() > 0 ? signature.getSignature().toHex() : "<none>")); keyLocator = signature.getKeyLocator(); } else if (data.getSignature() is HmacWithSha256Signature) { var signature = (HmacWithSha256Signature)data.getSignature(); Console.Out.WriteLine("HmacWithSha256 signature.signature: " + (signature.getSignature().size() > 0 ? signature.getSignature().toHex() : "<none>")); keyLocator = signature.getKeyLocator(); } else if (data.getSignature() is DigestSha256Signature) { var signature = (DigestSha256Signature)data.getSignature(); Console.Out.WriteLine("DigestSha256 signature.signature: " + (signature.getSignature().size() > 0 ? signature.getSignature().toHex() : "<none>")); } else if (data.getSignature() is GenericSignature) { var signature = (GenericSignature)data.getSignature(); Console.Out.WriteLine("Generic signature.signature: " + (signature.getSignature().size() > 0 ? signature.getSignature().toHex() : "<none>")); Console.Out.WriteLine(" Type code: " + signature.getTypeCode() + " signatureInfo: " + (signature.getSignatureInfoEncoding().size() > 0 ? signature.getSignatureInfoEncoding().toHex() : "<none>")); } if (keyLocator != null) { Console.Out.Write("signature.keyLocator: "); if (keyLocator.getType() == KeyLocatorType.NONE) Console.Out.WriteLine("<none>"); else if (keyLocator.getType() ==KeyLocatorType.KEY_LOCATOR_DIGEST) Console.Out.WriteLine("KeyLocatorDigest: " + keyLocator.getKeyData().toHex()); else if (keyLocator.getType() == KeyLocatorType.KEYNAME) Console.Out.WriteLine("KeyName: " + keyLocator.getKeyName().toUri()); else Console.Out.WriteLine("<unrecognized ndn_KeyLocatorType>"); } }
/// <summary> /// Create a deep copy of the given data object, including a clone of the /// signature object. /// </summary> /// /// <param name="data">The data object to copy.</param> public Data(Data data) { this.signature_ = new ChangeCounter( new Sha256WithRsaSignature()); this.name_ = new ChangeCounter(new Name()); this.metaInfo_ = new ChangeCounter(new MetaInfo()); this.content_ = new Blob(); this.lpPacket_ = null; this.defaultWireEncoding_ = new SignedBlob(); this.defaultFullName_ = new Name(); this.getDefaultWireEncodingChangeCount_ = 0; this.changeCount_ = 0; try { signature_ .set((data.signature_ == null) ? (net.named_data.jndn.util.ChangeCountable) (new Sha256WithRsaSignature()) : (net.named_data.jndn.util.ChangeCountable) ((Signature) data.getSignature().Clone())); } catch (Exception e) { // We don't expect this to happen, so just treat it as if we got a null pointer. throw new NullReferenceException( "Data.setSignature: unexpected exception in clone(): " + e.Message); } name_.set(new Name(data.getName())); metaInfo_.set(new MetaInfo(data.getMetaInfo())); content_ = data.content_; setDefaultWireEncoding(data.defaultWireEncoding_, null); }
/// <summary> /// Sign data packet based on the certificate name. /// </summary> /// /// <param name="data">The Data object to sign and update its signature.</param> /// <param name="certificateName"></param> /// <param name="wireFormat">The WireFormat for calling encodeData.</param> public void signByCertificate(Data data, Name certificateName, WireFormat wireFormat) { DigestAlgorithm[] digestAlgorithm = new DigestAlgorithm[1]; Signature signature = makeSignatureByCertificate(certificateName, digestAlgorithm); data.setSignature(signature); // Encode once to get the signed portion. SignedBlob encoding = data.wireEncode(wireFormat); data.getSignature() .setSignature( privateKeyStorage_.sign( encoding.signedBuf(), net.named_data.jndn.security.certificate.IdentityCertificate .certificateNameToPublicKeyName(certificateName), digestAlgorithm[0])); // Encode again to include the signature. data.wireEncode(wireFormat); }
/** * Loop to encode a data packet nIterations times. * @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 keyType KeyType.RSA or EC, used if useCrypto is true. * @param encoding Set encoding[0] to the wire encoding. * @return The number of seconds for all iterations. */ private static double benchmarkEncodeDataSeconds(int nIterations, bool useComplex, bool useCrypto, KeyType keyType, Blob[] encoding) { Name name; Blob content; if (useComplex) { // Use a large name and content. name = new Name ("/ndn/ucla.edu/apps/lwndn-test/numbers.txt/%FD%05%05%E8%0C%CE%1D/%00"); StringBuilder contentStream = new StringBuilder(); int count = 1; contentStream.append(count++); while (contentStream.toString().Length < 1115) contentStream.append(" ").append(count++); content = new Blob(contentStream.toString()); } else { // Use a small name and content. name = new Name("/test"); content = new Blob("abc"); } Name.Component finalBlockId = new Name.Component(new Blob(new byte[] { (byte)0 })); // Initialize the KeyChain storage in case useCrypto is true. MemoryIdentityStorage identityStorage = new MemoryIdentityStorage(); MemoryPrivateKeyStorage privateKeyStorage = new MemoryPrivateKeyStorage(); KeyChain keyChain = new KeyChain (new IdentityManager(identityStorage, privateKeyStorage), new SelfVerifyPolicyManager(identityStorage)); Name keyName = new Name("/testname/DSK-123"); Name certificateName = keyName.getSubName(0, keyName.size() - 1).append ("KEY").append(keyName.get(-1)).append("ID-CERT").append("0"); privateKeyStorage.setKeyPairForKeyName (keyName, KeyType.RSA, new ByteBuffer(DEFAULT_RSA_PUBLIC_KEY_DER), new ByteBuffer(DEFAULT_RSA_PRIVATE_KEY_DER)); Blob signatureBits = new Blob(new byte[256]); Blob emptyBlob = new Blob(new byte[0]); double start = getNowSeconds(); for (int i = 0; i < nIterations; ++i) { Data data = new Data(name); data.setContent(content); if (useComplex) { data.getMetaInfo().setFreshnessPeriod(30000); 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 = new KeyLocator(); keyLocator.setType(KeyLocatorType.KEYNAME); keyLocator.setKeyName(certificateName); Sha256WithRsaSignature sha256Signature = (Sha256WithRsaSignature)data.getSignature(); sha256Signature.setKeyLocator(keyLocator); sha256Signature.setSignature(signatureBits); } encoding[0] = data.wireEncode(); } double finish = getNowSeconds(); return finish - start; }
/// <summary> /// Encode data in NDN-TLV and return the encoding. /// </summary> /// /// <param name="data">The Data object to encode.</param> /// <param name="signedPortionBeginOffset">If you are not encoding in order to sign, you can call encodeData(data) to ignore this returned value.</param> /// <param name="signedPortionEndOffset">If you are not encoding in order to sign, you can call encodeData(data) to ignore this returned value.</param> /// <returns>A Blob containing the encoding.</returns> public override Blob encodeData(Data data, int[] signedPortionBeginOffset, int[] signedPortionEndOffset) { TlvEncoder encoder = new TlvEncoder(1500); int saveLength = encoder.getLength(); // Encode backwards. encoder.writeBlobTlv(net.named_data.jndn.encoding.tlv.Tlv.SignatureValue, (data.getSignature()) .getSignature().buf()); int signedPortionEndOffsetFromBack = encoder.getLength(); encodeSignatureInfo(data.getSignature(), encoder); encoder.writeBlobTlv(net.named_data.jndn.encoding.tlv.Tlv.Content, data.getContent().buf()); encodeMetaInfo(data.getMetaInfo(), encoder); encodeName(data.getName(), new int[1], new int[1], encoder); int signedPortionBeginOffsetFromBack = encoder.getLength(); encoder.writeTypeAndLength(net.named_data.jndn.encoding.tlv.Tlv.Data, encoder.getLength() - saveLength); signedPortionBeginOffset[0] = encoder.getLength() - signedPortionBeginOffsetFromBack; signedPortionEndOffset[0] = encoder.getLength() - signedPortionEndOffsetFromBack; return new Blob(encoder.getOutput(), false); }
/// <summary> /// Wire encode the Data object, digest it and set its SignatureInfo to /// a DigestSha256. /// </summary> /// /// <param name="data"></param> /// <param name="wireFormat">The WireFormat for calling encodeData.</param> public void signWithSha256(Data data, WireFormat wireFormat) { data.setSignature(new DigestSha256Signature()); // Encode once to get the signed portion. SignedBlob encoding = data.wireEncode(wireFormat); // Digest and set the signature. byte[] signedPortionDigest = net.named_data.jndn.util.Common.digestSha256(encoding.signedBuf()); data.getSignature().setSignature(new Blob(signedPortionDigest, false)); // Encode again to include the signature. data.wireEncode(wireFormat); }
/// <summary> /// Decode input as a data packet in NDN-TLV and set the fields in the data /// object. /// </summary> /// /// <param name="data">The Data object whose fields are updated.</param> /// <param name="input"></param> /// <param name="signedPortionBeginOffset">If you are not decoding in order to verify, you can call decodeData(data, input) to ignore this returned value.</param> /// <param name="signedPortionEndOffset">not decoding in order to verify, you can call decodeData(data, input) to ignore this returned value.</param> /// <param name="copy">unchanged while the Blob values are used.</param> /// <exception cref="EncodingException">For invalid encoding.</exception> public override void decodeData(Data data, ByteBuffer input, int[] signedPortionBeginOffset, int[] signedPortionEndOffset, bool copy) { TlvDecoder decoder = new TlvDecoder(input); int endOffset = decoder.readNestedTlvsStart(net.named_data.jndn.encoding.tlv.Tlv.Data); signedPortionBeginOffset[0] = decoder.getOffset(); decodeName(data.getName(), new int[1], new int[1], decoder, copy); decodeMetaInfo(data.getMetaInfo(), decoder, copy); data.setContent(new Blob(decoder.readBlobTlv(net.named_data.jndn.encoding.tlv.Tlv.Content), copy)); decodeSignatureInfo(data, decoder, copy); signedPortionEndOffset[0] = decoder.getOffset(); data.getSignature().setSignature( new Blob(decoder.readBlobTlv(net.named_data.jndn.encoding.tlv.Tlv.SignatureValue), copy)); decoder.finishNestedTlvs(endOffset); }
/// <summary> /// Check whether the received data packet complies with the verification policy, /// and get the indication of the next verification step. /// </summary> /// /// <param name="data">The Data object 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">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(Data data, int stepCount, OnVerified onVerified, OnDataValidationFailed onValidationFailed) { String[] failureReason = new String[] { "unknown" }; Interest certificateInterest = getCertificateInterest(stepCount, "data", data.getName(), data.getSignature(), failureReason); if (certificateInterest == null) { try { onValidationFailed.onDataValidationFailed(data, failureReason[0]); } catch (Exception ex) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onDataValidationFailed", ex); } return null; } if (certificateInterest.getName().size() > 0) return new ValidationRequest(certificateInterest, new ConfigPolicyManager.OnCertificateDownloadComplete (this, data, stepCount, onVerified, onValidationFailed), onValidationFailed, 2, stepCount + 1); else { // Certificate is known. Verify the signature. // wireEncode returns the cached encoding if available. if (verify(data.getSignature(), data.wireEncode(), failureReason)) { try { onVerified.onVerified(data); } catch (Exception ex_0) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onVerified", ex_0); } } else { try { onValidationFailed.onDataValidationFailed(data, failureReason[0]); } catch (Exception ex_1) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onDataValidationFailed", ex_1); } } return null; } }
public void testHyperRelation() { ConfigPolicyManager policyManager = new ConfigPolicyManager(System.IO.Path.GetFullPath(new FileInfo(System.IO.Path.Combine(policyConfigDirectory.FullName,"/hyperrelation_ruleset.conf")).Name)); Name dataName = new Name("/SecurityTestSecRule/Basic/Longer/Data2"); Data data1 = new Data(dataName); Data data2 = new Data(dataName); BoostInfoTree matchedRule = friendAccess.findMatchingRule( policyManager, dataName, "data"); keyChain.sign(data1, defaultCertName); keyChain.sign(data2, shortCertName); Name signatureName1 = ((Sha256WithRsaSignature) data1.getSignature()) .getKeyLocator().getKeyName(); Name signatureName2 = ((Sha256WithRsaSignature) data2.getSignature()) .getKeyLocator().getKeyName(); String[] failureReason = new String[] { "unknown" }; AssertTrue(friendAccess.checkSignatureMatch(policyManager, signatureName1, dataName, matchedRule, failureReason)); AssertFalse(friendAccess.checkSignatureMatch(policyManager, signatureName2, dataName, matchedRule, failureReason)); dataName = new Name("/SecurityTestSecRule/Basic/Other/Data1"); data1 = new Data(dataName); data2 = new Data(dataName); matchedRule = friendAccess.findMatchingRule(policyManager, dataName, "data"); keyChain.sign(data1, defaultCertName); keyChain.sign(data2, shortCertName); signatureName1 = ((Sha256WithRsaSignature) data1.getSignature()) .getKeyLocator().getKeyName(); signatureName2 = ((Sha256WithRsaSignature) data2.getSignature()) .getKeyLocator().getKeyName(); AssertFalse(friendAccess.checkSignatureMatch(policyManager, signatureName1, dataName, matchedRule, failureReason)); AssertTrue(friendAccess.checkSignatureMatch(policyManager, signatureName2, dataName, matchedRule, failureReason)); }
private static ArrayList dumpData(Data data) { ArrayList result = new ArrayList(); ILOG.J2CsMapping.Collections.Collections.Add(result,dump("name:", data.getName().toUri())); if (data.getContent().size() > 0) { String raw = ""; ByteBuffer buf = data.getContent().buf(); while (buf.remaining() > 0) raw += (char) buf.get(); ILOG.J2CsMapping.Collections.Collections.Add(result,dump("content (raw):", raw)); ILOG.J2CsMapping.Collections.Collections.Add(result,dump("content (hex):", data.getContent().toHex())); } else ILOG.J2CsMapping.Collections.Collections.Add(result,dump("content: <empty>")); if (data.getMetaInfo().getType() != net.named_data.jndn.ContentType.BLOB) { ILOG.J2CsMapping.Collections.Collections.Add(result,dump( "metaInfo.type:", (data.getMetaInfo().getType() == net.named_data.jndn.ContentType.LINK) ? "LINK" : ((data.getMetaInfo().getType() == net.named_data.jndn.ContentType.KEY) ? "KEY" : "unknown"))); } ILOG.J2CsMapping.Collections.Collections.Add(result,dump("metaInfo.freshnessPeriod (milliseconds):", (data .getMetaInfo().getFreshnessPeriod() >= 0) ? "" + (long) data.getMetaInfo().getFreshnessPeriod() : "<none>")); ILOG.J2CsMapping.Collections.Collections.Add(result,dump("metaInfo.finalBlockId:", (data.getMetaInfo() .getFinalBlockId().getValue().size() > 0) ? data.getMetaInfo() .getFinalBlockId().toEscapedString() : "<none>")); if (data.getSignature() is Sha256WithRsaSignature) { Sha256WithRsaSignature signature = (Sha256WithRsaSignature) data .getSignature(); ILOG.J2CsMapping.Collections.Collections.Add(result,dump("signature.signature:", (signature.getSignature() .size() == 0) ? "<none>" : signature.getSignature().toHex())); if (signature.getKeyLocator().getType() != net.named_data.jndn.KeyLocatorType.NONE) { if (signature.getKeyLocator().getType() == net.named_data.jndn.KeyLocatorType.KEY_LOCATOR_DIGEST) ILOG.J2CsMapping.Collections.Collections.Add(result,dump("signature.keyLocator: KeyLocatorDigest:", signature.getKeyLocator().getKeyData().toHex())); else if (signature.getKeyLocator().getType() == net.named_data.jndn.KeyLocatorType.KEYNAME) ILOG.J2CsMapping.Collections.Collections.Add(result,dump("signature.keyLocator: KeyName:", signature .getKeyLocator().getKeyName().toUri())); else ILOG.J2CsMapping.Collections.Collections.Add(result,dump("signature.keyLocator: <unrecognized KeyLocatorType")); } else ILOG.J2CsMapping.Collections.Collections.Add(result,dump("signature.keyLocator: <none>")); } return result; }
/// <summary> /// Check if the given Data packet can satisfy this Interest. This method /// considers the Name, MinSuffixComponents, MaxSuffixComponents, /// PublisherPublicKeyLocator, and Exclude. It does not consider the /// ChildSelector or MustBeFresh. This uses the given wireFormat to get the /// Data packet encoding for the full Name. /// </summary> /// /// <param name="data">The Data packet to check.</param> /// <param name="wireFormat"></param> /// <returns>True if the given Data packet can satisfy this Interest.</returns> public bool matchesData(Data data, WireFormat wireFormat) { // Imitate ndn-cxx Interest::matchesData. int interestNameLength = getName().size(); Name dataName = data.getName(); int fullNameLength = dataName.size() + 1; // Check MinSuffixComponents. bool hasMinSuffixComponents = getMinSuffixComponents() >= 0; int minSuffixComponents = (hasMinSuffixComponents) ? getMinSuffixComponents() : 0; if (!(interestNameLength + minSuffixComponents <= fullNameLength)) return false; // Check MaxSuffixComponents. bool hasMaxSuffixComponents = getMaxSuffixComponents() >= 0; if (hasMaxSuffixComponents && !(interestNameLength + getMaxSuffixComponents() >= fullNameLength)) return false; // Check the prefix. if (interestNameLength == fullNameLength) { if (getName().get(-1).isImplicitSha256Digest()) { if (!getName().equals(data.getFullName(wireFormat))) return false; } else // The Interest Name is the same length as the Data full Name, but the // last component isn't a digest so there's no possibility of matching. return false; } else { // The Interest Name should be a strict prefix of the Data full Name, if (!getName().isPrefixOf(dataName)) return false; } // Check the Exclude. // The Exclude won't be violated if the Interest Name is the same as the // Data full Name. if (getExclude().size() > 0 && fullNameLength > interestNameLength) { if (interestNameLength == fullNameLength - 1) { // The component to exclude is the digest. if (getExclude().matches( data.getFullName(wireFormat).get(interestNameLength))) return false; } else { // The component to exclude is not the digest. if (getExclude().matches(dataName.get(interestNameLength))) return false; } } // Check the KeyLocator. KeyLocator publisherPublicKeyLocator = getKeyLocator(); if (publisherPublicKeyLocator.getType() != net.named_data.jndn.KeyLocatorType.NONE) { Signature signature = data.getSignature(); if (!net.named_data.jndn.KeyLocator.canGetFromSignature(signature)) // No KeyLocator in the Data packet. return false; if (!publisherPublicKeyLocator.equals(net.named_data.jndn.KeyLocator .getFromSignature(signature))) return false; } return true; }
/// <summary> /// Look in the IdentityStorage for the public key with the name in the /// KeyLocator (if available) and use it to verify the data packet. If the /// public key can't be found, call onVerifyFailed. /// </summary> /// /// <param name="data">The Data object 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>null for no further step for looking up a certificate chain.</returns> public override ValidationRequest checkVerificationPolicy(Data data, int stepCount, OnVerified onVerified, OnDataValidationFailed onValidationFailed) { String[] failureReason = new String[] { "unknown" }; // wireEncode returns the cached encoding if available. if (verify(data.getSignature(), data.wireEncode(), failureReason)) { try { onVerified.onVerified(data); } catch (Exception ex) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onVerified", ex); } } else { try { onValidationFailed.onDataValidationFailed(data, failureReason[0]); } catch (Exception ex_0) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onDataValidationFailed", ex_0); } } // No more steps, so return a null ValidationRequest. return null; }
/// <summary> /// Check if the given Data packet can satisfy this Interest. This method /// considers the Name, MinSuffixComponents, MaxSuffixComponents, /// PublisherPublicKeyLocator, and Exclude. It does not consider the /// ChildSelector or MustBeFresh. This uses the given wireFormat to get the /// Data packet encoding for the full Name. /// </summary> /// /// <param name="data">The Data packet to check.</param> /// <param name="wireFormat"></param> /// <returns>True if the given Data packet can satisfy this Interest.</returns> public bool matchesData(Data data, WireFormat wireFormat) { // Imitate ndn-cxx Interest::matchesData. int interestNameLength = getName().size(); Name dataName = data.getName(); int fullNameLength = dataName.size() + 1; // Check MinSuffixComponents. bool hasMinSuffixComponents = getMinSuffixComponents() >= 0; int minSuffixComponents = (hasMinSuffixComponents) ? getMinSuffixComponents() : 0; if (!(interestNameLength + minSuffixComponents <= fullNameLength)) { return(false); } // Check MaxSuffixComponents. bool hasMaxSuffixComponents = getMaxSuffixComponents() >= 0; if (hasMaxSuffixComponents && !(interestNameLength + getMaxSuffixComponents() >= fullNameLength)) { return(false); } // Check the prefix. if (interestNameLength == fullNameLength) { if (getName().get(-1).isImplicitSha256Digest()) { if (!getName().equals(data.getFullName(wireFormat))) { return(false); } } else { // The Interest Name is the same length as the Data full Name, but the // last component isn't a digest so there's no possibility of matching. return(false); } } else { // The Interest Name should be a strict prefix of the Data full Name, if (!getName().isPrefixOf(dataName)) { return(false); } } // Check the Exclude. // The Exclude won't be violated if the Interest Name is the same as the // Data full Name. if (getExclude().size() > 0 && fullNameLength > interestNameLength) { if (interestNameLength == fullNameLength - 1) { // The component to exclude is the digest. if (getExclude().matches( data.getFullName(wireFormat).get(interestNameLength))) { return(false); } } else { // The component to exclude is not the digest. if (getExclude().matches(dataName.get(interestNameLength))) { return(false); } } } // Check the KeyLocator. KeyLocator publisherPublicKeyLocator = getKeyLocator(); if (publisherPublicKeyLocator.getType() != net.named_data.jndn.KeyLocatorType.NONE) { Signature signature = data.getSignature(); if (!net.named_data.jndn.KeyLocator.canGetFromSignature(signature)) { // No KeyLocator in the Data packet. return(false); } if (!publisherPublicKeyLocator.equals(net.named_data.jndn.KeyLocator .getFromSignature(signature))) { return(false); } } return(true); }