static void Main(string[] args)
        {
            var data = new Data();
              data.wireDecode(new Blob(TlvData));

              // Use a hard-wired secret for testing. In a real application the signer
              // ensures that the verifier knows the shared key and its keyName.
              var key = new Blob(new byte[] {
             0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
            16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
              });

              if (KeyChain.verifyDataWithHmacWithSha256(data, key))
            Console.Out.WriteLine("Hard-coded data signature verification: VERIFIED");
              else
            Console.Out.WriteLine("Hard-coded data signature verification: FAILED");

              var freshData = new Data(new Name("/ndn/abc"));
              var signature = new HmacWithSha256Signature();
              signature.getKeyLocator().setType(KeyLocatorType.KEYNAME);
              signature.getKeyLocator().setKeyName(new Name("key1"));
              freshData.setSignature(signature);
              freshData.setContent(new Blob("SUCCESS!"));
              Console.Out.WriteLine("Signing fresh data packet " + freshData.getName().toUri());
              KeyChain.signWithHmacWithSha256(freshData, key);

              if (KeyChain.verifyDataWithHmacWithSha256(freshData, key))
            Console.Out.WriteLine("Freshly-signed data signature verification: VERIFIED");
              else
            Console.Out.WriteLine("Freshly-signed data signature verification: FAILED");
        }
예제 #2
0
        /// <summary>
        /// Create an IdentityCertificate from the content in the data packet.
        /// </summary>
        ///
        /// <param name="data">The data packet with the content to decode.</param>
        public IdentityCertificate(Data data)
            : base(data)
        {
            this.publicKeyName_ = new Name();

            if (!isCorrectName(data.getName()))
                throw new SecurityException("Wrong Identity Certificate Name!");

            setPublicKeyName();
        }
예제 #3
0
 /// <summary>
 /// Create a Certificate from the content in the data packet.
 /// </summary>
 ///
 /// <param name="data">The data packet with the content to decode.</param>
 public Certificate(Data data)
     : base(data)
 {
     this.subjectDescriptionList_ = new ArrayList();
     this.extensionList_ = new ArrayList();
     this.notBefore_ = System.Double.MaxValue;
     this.notAfter_ = -System.Double.MaxValue;
     this.key_ = new PublicKey();
     decode();
 }
예제 #4
0
        /// <summary>
        /// Prepare an encrypted data packet by encrypting the payload using the key
        /// according to the params. In addition, this prepares the encoded
        /// EncryptedContent with the encryption result using keyName and params. The
        /// encoding is set as the content of the data packet. If params defines an
        /// asymmetric encryption algorithm and the payload is larger than the maximum
        /// plaintext size, this encrypts the payload with a symmetric key that is
        /// asymmetrically encrypted and provided as a nonce in the content of the data
        /// packet. The packet's /{dataName}/ is updated to be
        /// /{dataName}/FOR/{keyName}
        /// </summary>
        ///
        /// <param name="data">The data packet which is updated.</param>
        /// <param name="payload">The payload to encrypt.</param>
        /// <param name="keyName">The key name for the EncryptedContent.</param>
        /// <param name="key">The encryption key value.</param>
        /// <param name="params">The parameters for encryption.</param>
        public static void encryptData(Data data, Blob payload, Name keyName,
				Blob key, EncryptParams paras)
        {
            data.getName().append(NAME_COMPONENT_FOR).append(keyName);

            EncryptAlgorithmType algorithmType = paras.getAlgorithmType();

            if (algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc
                    || algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesEcb) {
                EncryptedContent content = encryptSymmetric(payload, key, keyName,
                        paras);
                data.setContent(content.wireEncode(net.named_data.jndn.encoding.TlvWireFormat.get()));
            } else if (algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaPkcs
                    || algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep) {
                // Java doesn't have a direct way to get the maximum plain text size, so
                // try to encrypt the payload first and catch the error if it is too big.
                try {
                    EncryptedContent content_0 = encryptAsymmetric(payload, key,
                            keyName, paras);
                    data.setContent(content_0.wireEncode(net.named_data.jndn.encoding.TlvWireFormat.get()));
                    return;
                } catch (IllegalBlockSizeException ex) {
                    // The payload is larger than the maximum plaintext size. Continue.
                }

                // 128-bit nonce.
                ByteBuffer nonceKeyBuffer = ILOG.J2CsMapping.NIO.ByteBuffer.allocate(16);
                net.named_data.jndn.util.Common.getRandom().nextBytes(nonceKeyBuffer.array());
                Blob nonceKey = new Blob(nonceKeyBuffer, false);

                Name nonceKeyName = new Name(keyName);
                nonceKeyName.append("nonce");

                EncryptParams symmetricParams = new EncryptParams(
                        net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc, net.named_data.jndn.encrypt.algo.AesAlgorithm.BLOCK_SIZE);

                EncryptedContent nonceContent = encryptSymmetric(payload, nonceKey,
                        nonceKeyName, symmetricParams);

                EncryptedContent payloadContent = encryptAsymmetric(nonceKey, key,
                        keyName, paras);

                Blob nonceContentEncoding = nonceContent.wireEncode();
                Blob payloadContentEncoding = payloadContent.wireEncode();
                ByteBuffer content_1 = ILOG.J2CsMapping.NIO.ByteBuffer.allocate(nonceContentEncoding
                        .size() + payloadContentEncoding.size());
                content_1.put(payloadContentEncoding.buf());
                content_1.put(nonceContentEncoding.buf());
                content_1.flip();

                data.setContent(new Blob(content_1, false));
            } else
                throw new Exception("Unsupported encryption method");
        }
        /// <summary>
        /// Override to call onVerified.onVerified(data) and to indicate no further
        /// verification step.
        /// </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">Override to ignore this.</param>
        /// <returns>null for no further step.</returns>
        public override sealed ValidationRequest checkVerificationPolicy(Data data,
				int stepCount, OnVerified onVerified,
				OnDataValidationFailed onValidationFailed)
        {
            try {
                onVerified.onVerified(data);
            } catch (Exception ex) {
                logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onVerified", ex);
            }
            return null;
        }
예제 #6
0
        /// <summary>
        /// Create a Link, copying values from the other Data object. If the content
        /// can be decoded using the default wire encoding, then update the list
        /// of delegations.
        /// </summary>
        ///
        /// <param name="data">The Data object to copy values from.</param>
        public Link(Data data)
            : base(data)
        {
            this.delegations_ = new DelegationSet();

            if (!getContent().isNull()) {
                try {
                    delegations_.wireDecode(getContent());
                    getMetaInfo().setType(net.named_data.jndn.ContentType.LINK);
                } catch (EncodingException ex) {
                    delegations_.clear();
                }
            }
        }
예제 #7
0
 /// <summary>
 /// Check if this PolicyManager has a verification rule for the received data.
 /// </summary>
 ///
 /// <param name="data">The received data packet.</param>
 /// <returns>true if the data must be verified, otherwise false.</returns>
 public abstract bool requireVerify(Data data);
예제 #8
0
        /// <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 abstract ValidationRequest checkVerificationPolicy(Data data,
				int stepCount, OnVerified onVerified,
				OnDataValidationFailed onValidationFailed);
예제 #9
0
 /// <summary>
 /// Check if the received data packet can escape from verification and be
 /// trusted as valid.
 /// </summary>
 ///
 /// <param name="data">The received data packet.</param>
 /// <returns>true if the data does not need to be verified to be trusted as
 /// valid, otherwise false.</returns>
 public abstract bool skipVerifyAndTrust(Data data);
예제 #10
0
        public void verifyData(Data data, OnVerified verifiedCallback,
				OnDataValidationFailed failedCallback)
        {
            keyChain_.verifyData(data, verifiedCallback, failedCallback);
        }
예제 #11
0
 public void testDump()
 {
     Data data = new Data();
     try {
         data.wireDecode(codedData);
     } catch (EncodingException ex) {
         Assert.Fail("Can't decode codedData");
     }
     Assert.AssertArrayEquals("Initial dump does not have expected format",
             ILOG.J2CsMapping.Collections.Collections.ToArray(dumpData(data)), ILOG.J2CsMapping.Collections.Collections.ToArray(initialDump));
 }
예제 #12
0
 /// <summary>
 /// The OnInterestCallback calls this to put a Data packet which satisfies an
 /// Interest.
 /// This uses the default WireFormat.getDefaultWireFormat() to encode data.
 /// </summary>
 ///
 /// <param name="data">The Data packet which satisfies the interest.</param>
 /// <exception cref="System.Exception">If the encoded Data packet size exceeds getMaxNdnPacketSize().</exception>
 public void putData(Data data)
 {
     putData(data, net.named_data.jndn.encoding.WireFormat.getDefaultWireFormat());
 }
 public virtual void onVerified(Data data)
 {
     ++onVerifiedCallCount_;
 }
예제 #14
0
        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;
        }
예제 #15
0
        private static Data createFreshData()
        {
            Data freshData = new Data(new Name("/ndn/abc"));
            freshData.setContent(new Blob("SUCCESS!"));
            freshData.getMetaInfo().setFreshnessPeriod(5000);
            freshData.getMetaInfo().setFinalBlockId(new Name("/%00%09").get(0));

            return freshData;
        }
예제 #16
0
        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");
        }
예제 #17
0
        public void testFullName()
        {
            Data data = new Data();
            try {
                data.wireDecode(codedData);
            } catch (EncodingException ex) {
                Assert.Fail("Can't decode codedData");
            }

            // Check the full name format.
            Assert.AssertEquals(data.getName().size() + 1, data.getFullName().size());
            Assert.AssertEquals(data.getName(), data.getFullName().getPrefix(-1));
            Assert.AssertEquals(32, data.getFullName().get(-1).getValue().size());

            // Check the independent digest calculation.
            Blob newDigest = new Blob(net.named_data.jndn.util.Common.digestSha256(codedData));
            Assert.AssertTrue(newDigest.equals(data.getFullName().get(-1).getValue()));

            // Check the expected URI.
            Assert.AssertEquals(
                    "/ndn/abc/sha256digest="
                            + "96556d685dcb1af04be4ae57f0e7223457d4055ea9b3d07c0d337bef4a8b3ee9",
                    data.getFullName().toUri());

            // Changing the Data packet should change the full name.
            Name saveFullName = new Name(data.getFullName());
            data.setContent(new Blob());
            Assert.AssertFalse(data.getFullName().get(-1).equals(saveFullName.get(-1)));
        }
예제 #18
0
        public void testEncodeDecode()
        {
            Data data = new Data();
            try {
                data.wireDecode(codedData);
            } catch (EncodingException ex) {
                Assert.Fail("Can't decode codedData");
            }
            // Set the content again to clear the cached encoding so we encode again.
            data.setContent(data.getContent());
            Blob encoding = data.wireEncode();

            Data reDecodedData = new Data();
            try {
                reDecodedData.wireDecode(encoding);
            } catch (EncodingException ex_0) {
                Assert.Fail("Can't decode reDecodedData");
            }
            Assert.AssertArrayEquals("Re-decoded data does not match original dump",
                    ILOG.J2CsMapping.Collections.Collections.ToArray(initialDump), ILOG.J2CsMapping.Collections.Collections.ToArray(dumpData(reDecodedData)));
        }
예제 #19
0
 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());
 }
예제 #20
0
        public void setUp()
        {
            // Don't show INFO log messages.
            ILOG.J2CsMapping.Util.Logging.Logger.getLogger("").setLevel(ILOG.J2CsMapping.Util.Logging.Level.WARNING);

            credentials = new CredentialStorage();
            freshData = createFreshData();
        }
 public virtual void onDataValidationFailed(Data data, String reason)
 {
     ++onValidationFailedCallCount_;
 }
 /// <summary>
 /// Always return true to use the self-verification rule for the received data.
 /// </summary>
 ///
 /// <param name="data">The received data packet.</param>
 /// <returns>true.</returns>
 public override bool requireVerify(Data data)
 {
     return true;
 }
예제 #23
0
 /// <summary>
 /// The OnInterestCallback calls this to put a Data packet which satisfies an
 /// Interest.
 /// </summary>
 ///
 /// <param name="data">The Data packet which satisfies the interest.</param>
 /// <param name="wireFormat">A WireFormat object used to encode the Data packet.</param>
 /// <exception cref="System.Exception">If the encoded Data packet size exceeds getMaxNdnPacketSize().</exception>
 public void putData(Data data, WireFormat wireFormat)
 {
     node_.putData(data, wireFormat);
 }
        /// <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;
        }
예제 #25
0
 public void signData(Data data, Name certificateName)
 {
     if (certificateName.size() == 0)
         certificateName = defaultCertName_;
     keyChain_.sign(data, certificateName);
 }
예제 #26
0
 public void testCopyFields()
 {
     Data data = new Data(freshData.getName());
     data.setContent(freshData.getContent());
     data.setMetaInfo(freshData.getMetaInfo());
     try {
         credentials.signData(data);
     } catch (SecurityException ex) {
         Assert.Fail("Error calling signData" + ex.Message);
     }
     ArrayList freshDump = dumpData(data);
     Assert.AssertTrue("Freshly created data does not match original dump",
             dataDumpsEqual(freshDump, initialDump));
 }
 /// <summary>
 /// Never skip verification.
 /// </summary>
 ///
 /// <param name="data">The received data packet.</param>
 /// <returns>false.</returns>
 public override bool skipVerifyAndTrust(Data data)
 {
     return false;
 }
예제 #28
0
 public void signData(Data data)
 {
     signData(data, new Name());
 }
 public virtual void onData(Interest interest, Data data)
 {
     interest_ = interest;
     data_ = data;
     ++onDataCallCount_;
 }
예제 #30
0
 public void signDataWithSha256(Data data)
 {
     keyChain_.signWithSha256(data);
 }