Exemplo n.º 1
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;
        }
Exemplo n.º 2
0
            /// <summary>
            /// We received the response.
            /// </summary>
            ///
            /// <param name="interest"></param>
            /// <param name="responseData"></param>
            public virtual void onData(Interest interest, Data responseData)
            {
                // Decode responseData.getContent() and check for a success code.
                ControlResponse controlResponse = new ControlResponse();

                try {
                    controlResponse.wireDecode(responseData.getContent(),
                                               net.named_data.jndn.encoding.TlvWireFormat.get());
                } catch (EncodingException ex) {
                    net.named_data.jndn.Node.logger_.log(
                        ILOG.J2CsMapping.Util.Logging.Level.INFO,
                        "Register prefix failed: Error decoding the NFD response: {0}",
                        ex);
                    try {
                        info_.onRegisterFailed_.onRegisterFailed(info_.prefix_);
                    } catch (Exception exception) {
                        net.named_data.jndn.Node.logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterFailed",
                                                             exception);
                    }
                    return;
                }

                // Status code 200 is "OK".
                if (controlResponse.getStatusCode() != 200)
                {
                    net.named_data.jndn.Node.logger_.log(
                        ILOG.J2CsMapping.Util.Logging.Level.INFO,
                        "Register prefix failed: Expected NFD status code 200, got: {0}",
                        controlResponse.getStatusCode());
                    try {
                        info_.onRegisterFailed_.onRegisterFailed(info_.prefix_);
                    } catch (Exception ex_0) {
                        net.named_data.jndn.Node.logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterFailed", ex_0);
                    }
                    return;
                }

                // Success, so we can add to the registered prefix table.
                if (info_.registeredPrefixId_ != 0)
                {
                    long interestFilterId = 0;
                    if (info_.onInterest_ != null)
                    {
                        // registerPrefix was called with the "combined" form that includes the
                        // callback, so add an InterestFilterEntry.
                        interestFilterId = parent_.getNextEntryId();
                        parent_.setInterestFilter(interestFilterId,
                                                  new InterestFilter(info_.prefix_),
                                                  info_.onInterest_, info_.face_);
                    }

                    if (!parent_.registeredPrefixTable_.add(
                            info_.registeredPrefixId_, info_.prefix_,
                            interestFilterId))
                    {
                        // removeRegisteredPrefix was already called with the registeredPrefixId.
                        if (interestFilterId > 0)
                        {
                            // Remove the related interest filter we just added.
                            parent_.unsetInterestFilter(interestFilterId);
                        }

                        return;
                    }
                }

                net.named_data.jndn.Node.logger_.log(
                    ILOG.J2CsMapping.Util.Logging.Level.INFO,
                    "Register prefix succeeded with the NFD forwarder for prefix {0}",
                    info_.prefix_.toUri());
                if (info_.onRegisterSuccess_ != null)
                {
                    try {
                        info_.onRegisterSuccess_.onRegisterSuccess(info_.prefix_,
                                                                   info_.registeredPrefixId_);
                    } catch (Exception ex_1) {
                        net.named_data.jndn.Node.logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterSuccess", ex_1);
                    }
                }
            }
Exemplo n.º 3
0
        public void testContentAsymmetricEncryptLarge()
        {
            /* foreach */
            foreach (TestEncryptor.AsymmetricEncryptInput  input  in  encryptorRsaTestInputs) {
                Blob largeContent = new Blob(toBuffer(new int[] { 0x73, 0x5a, 0xbd,
                        0x47, 0x0c, 0xfe, 0xf8, 0x7d, 0x2e, 0x17, 0xaa, 0x11, 0x6f,
                        0x23, 0xc5, 0x10, 0x23, 0x36, 0x88, 0xc4, 0x2a, 0x0f, 0x9a,
                        0x72, 0x54, 0x31, 0xa8, 0xb3, 0x51, 0x18, 0x9f, 0x0e, 0x1b,
                        0x93, 0x62, 0xd9, 0xc4, 0xf5, 0xf4, 0x3d, 0x61, 0x9a, 0xca,
                        0x05, 0x65, 0x6b, 0xc6, 0x41, 0xf9, 0xd5, 0x1c, 0x67, 0xc1,
                        0xd0, 0xd5, 0x6f, 0x7b, 0x70, 0xb8, 0x8f, 0xdb, 0x19, 0x68,
                        0x7c, 0xe0, 0x2d, 0x04, 0x49, 0xa9, 0xa2, 0x77, 0x4e, 0xfc,
                        0x60, 0x0d, 0x7c, 0x1b, 0x93, 0x6c, 0xd2, 0x61, 0xc4, 0x6b,
                        0x01, 0xe9, 0x12, 0x28, 0x6d, 0xf5, 0x78, 0xe9, 0x99, 0x0b,
                        0x9c, 0x4f, 0x90, 0x34, 0x3e, 0x06, 0x92, 0x57, 0xe3, 0x7a,
                        0x8f, 0x13, 0xc7, 0xf3, 0xfe, 0xf0, 0xe2, 0x59, 0x48, 0x15,
                        0xb9, 0xdb, 0x77, 0x07, 0x1d, 0x6d, 0xb5, 0x65, 0x17, 0xdf,
                        0x76, 0x6f, 0xb5, 0x43, 0xde, 0x71, 0xac, 0xf1, 0x22, 0xbf,
                        0xb2, 0xe5, 0xd9, 0x22, 0xf1, 0x67, 0x76, 0x71, 0x0c, 0xff,
                        0x99, 0x7b, 0x94, 0x9b, 0x24, 0x20, 0x80, 0xe3, 0xcc, 0x06,
                        0x4a, 0xed, 0xdf, 0xec, 0x50, 0xd5, 0x87, 0x3d, 0xa0, 0x7d,
                        0x9c, 0xe5, 0x13, 0x10, 0x98, 0x14, 0xc3, 0x90, 0x10, 0xd9,
                        0x25, 0x9a, 0x59, 0xe9, 0x37, 0x26, 0xfd, 0x87, 0xd7, 0xf4,
                        0xf9, 0x11, 0x91, 0xad, 0x5c, 0x00, 0x95, 0xf5, 0x2b, 0x37,
                        0xf7, 0x4e, 0xb4, 0x4b, 0x42, 0x7c, 0xb3, 0xad, 0xd6, 0x33,
                        0x5f, 0x0b, 0x84, 0x57, 0x7f, 0xa7, 0x07, 0x73, 0x37, 0x4b,
                        0xab, 0x2e, 0xfb, 0xfe, 0x1e, 0xcb, 0xb6, 0x4a, 0xc1, 0x21,
                        0x5f, 0xec, 0x92, 0xb7, 0xac, 0x97, 0x75, 0x20, 0xc9, 0xd8,
                        0x9e, 0x93, 0xd5, 0x12, 0x7a, 0x64, 0xb9, 0x4c, 0xed, 0x49,
                        0x87, 0x44, 0x5b, 0x4f, 0x90, 0x34, 0x3e, 0x06, 0x92, 0x57,
                        0xe3, 0x7a, 0x8f, 0x13, 0xc7, 0xf3, 0xfe, 0xf0, 0xe2, 0x59,
                        0x48, 0x15, 0xb9, 0xdb, 0x77, 0x07, 0x1d, 0x6d, 0xb5, 0x65,
                        0x17, 0xdf, 0x76, 0x6f, 0xb5, 0x43, 0xde, 0x71, 0xac, 0xf1,
                        0x22, 0xbf, 0xb2, 0xe5, 0xd9 }), false);

                Data data = new Data();
                RsaKeyParams rsaParams = new RsaKeyParams(1024);

                Name keyName = new Name("test");

                DecryptKey decryptKey = net.named_data.jndn.encrypt.algo.RsaAlgorithm.generateKey(rsaParams);
                EncryptKey encryptKey = net.named_data.jndn.encrypt.algo.RsaAlgorithm.deriveEncryptKey(decryptKey
                        .getKeyBits());

                Blob eKey = encryptKey.getKeyBits();
                Blob dKey = decryptKey.getKeyBits();

                EncryptParams encryptParams = new EncryptParams(input.type());
                net.named_data.jndn.encrypt.algo.Encryptor.encryptData(data, largeContent, keyName, eKey,
                        encryptParams);

                Assert.AssertEquals(input.testName(), new Name("/FOR").append(keyName),
                        data.getName());

                Blob largeDataContent = data.getContent();

                // largeDataContent is a sequence of the two EncryptedContent.
                EncryptedContent encryptedNonce = new EncryptedContent();
                encryptedNonce.wireDecode(largeDataContent);
                Assert.AssertEquals(input.testName(), keyName, encryptedNonce
                        .getKeyLocator().getKeyName());
                Assert.AssertEquals(input.testName(), 0, encryptedNonce.getInitialVector()
                        .size());
                Assert.AssertEquals(input.testName(), input.type(),
                        encryptedNonce.getAlgorithmType());

                // Use the size of encryptedNonce to find the start of encryptedPayload.
                ByteBuffer payloadContent = largeDataContent.buf().duplicate();
                payloadContent.position(encryptedNonce.wireEncode().size());
                EncryptedContent encryptedPayload = new EncryptedContent();
                encryptedPayload.wireDecode(payloadContent);
                Name nonceKeyName = new Name(keyName);
                nonceKeyName.append("nonce");
                Assert.AssertEquals(input.testName(), nonceKeyName, encryptedPayload
                        .getKeyLocator().getKeyName());
                Assert.AssertEquals(input.testName(), 16, encryptedPayload
                        .getInitialVector().size());
                Assert.AssertEquals(input.testName(), net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc,
                        encryptedPayload.getAlgorithmType());

                Assert.AssertTrue(input.testName(), encryptedNonce.wireEncode().size()
                        + encryptedPayload.wireEncode().size() == largeDataContent
                        .size());

                Blob blobNonce = encryptedNonce.getPayload();
                Blob nonce = net.named_data.jndn.encrypt.algo.RsaAlgorithm.decrypt(dKey, blobNonce, encryptParams);

                encryptParams.setAlgorithmType(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc);
                encryptParams.setInitialVector(encryptedPayload.getInitialVector());
                Blob bufferPayload = encryptedPayload.getPayload();
                Blob largePayload = net.named_data.jndn.encrypt.algo.AesAlgorithm.decrypt(nonce, bufferPayload,
                        encryptParams);

                Assert.AssertTrue(input.testName(), largeContent.equals(largePayload));
            }
        }
Exemplo n.º 4
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)));
        }
Exemplo n.º 5
0
        public void testContentAsymmetricEncryptSmall()
        {
            /* foreach */
            foreach (TestEncryptor.AsymmetricEncryptInput  input  in  encryptorRsaTestInputs) {
                Blob rawContent = new Blob(toBuffer(new int[] { 0x01, 0x23, 0x45,
                        0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76,
                        0x54, 0x32, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74,
                        0x73 }), false);

                Data data = new Data();
                RsaKeyParams rsaParams = new RsaKeyParams(1024);

                Name keyName = new Name("test");

                DecryptKey decryptKey = net.named_data.jndn.encrypt.algo.RsaAlgorithm.generateKey(rsaParams);
                EncryptKey encryptKey = net.named_data.jndn.encrypt.algo.RsaAlgorithm.deriveEncryptKey(decryptKey
                        .getKeyBits());

                Blob eKey = encryptKey.getKeyBits();
                Blob dKey = decryptKey.getKeyBits();

                EncryptParams encryptParams = new EncryptParams(input.type());

                net.named_data.jndn.encrypt.algo.Encryptor.encryptData(data, rawContent, keyName, eKey,
                        encryptParams);

                Assert.AssertEquals(input.testName(), new Name("/FOR").append(keyName),
                        data.getName());

                EncryptedContent extractContent = new EncryptedContent();
                extractContent.wireDecode(data.getContent());
                Assert.AssertEquals(input.testName(), keyName, extractContent
                        .getKeyLocator().getKeyName());
                Assert.AssertEquals(input.testName(), 0, extractContent.getInitialVector()
                        .size());
                Assert.AssertEquals(input.testName(), input.type(),
                        extractContent.getAlgorithmType());

                Blob recovered = extractContent.getPayload();
                Blob decrypted = net.named_data.jndn.encrypt.algo.RsaAlgorithm.decrypt(dKey, recovered,
                        encryptParams);
                Assert.AssertTrue(input.testName(), rawContent.equals(decrypted));
            }
        }
Exemplo n.º 6
0
        public void testContentSymmetricEncrypt()
        {
            /* foreach */
            foreach (TestEncryptor.SymmetricEncryptInput  input  in  encryptorAesTestInputs) {
                Data data = new Data();
                net.named_data.jndn.encrypt.algo.Encryptor.encryptData(data, input.plainText(), input.keyName(),
                        input.key(), input.encryptParams());

                Assert.AssertEquals(input.testName(),
                        new Name("/FOR").append(input.keyName()), data.getName());

                Assert.AssertTrue(input.testName(),
                        input.encryptedContent().equals(data.getContent()));

                EncryptedContent content = new EncryptedContent();
                content.wireDecode(data.getContent());
                Blob decryptedOutput = net.named_data.jndn.encrypt.algo.AesAlgorithm.decrypt(input.key(),
                        content.getPayload(), input.encryptParams());

                Assert.AssertTrue(input.testName(),
                        input.plainText().equals(decryptedOutput));
            }
        }
Exemplo n.º 7
0
            /// <summary>
            /// We received the response.
            /// </summary>
            ///
            /// <param name="interest"></param>
            /// <param name="responseData"></param>
            public virtual void onData(Interest interest, Data responseData)
            {
                // Decode responseData.getContent() and check for a success code.
                ControlResponse controlResponse = new ControlResponse();
                try {
                    controlResponse.wireDecode(responseData.getContent(),
                            net.named_data.jndn.encoding.TlvWireFormat.get());
                } catch (EncodingException ex) {
                    net.named_data.jndn.Node.logger_.log(
                            ILOG.J2CsMapping.Util.Logging.Level.INFO,
                            "Register prefix failed: Error decoding the NFD response: {0}",
                            ex);
                    try {
                        info_.onRegisterFailed_.onRegisterFailed(info_.prefix_);
                    } catch (Exception exception) {
                        net.named_data.jndn.Node.logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterFailed",
                                exception);
                    }
                    return;
                }

                // Status code 200 is "OK".
                if (controlResponse.getStatusCode() != 200) {
                    net.named_data.jndn.Node.logger_.log(
                            ILOG.J2CsMapping.Util.Logging.Level.INFO,
                            "Register prefix failed: Expected NFD status code 200, got: {0}",
                            controlResponse.getStatusCode());
                    try {
                        info_.onRegisterFailed_.onRegisterFailed(info_.prefix_);
                    } catch (Exception ex_0) {
                        net.named_data.jndn.Node.logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterFailed", ex_0);
                    }
                    return;
                }

                // Success, so we can add to the registered prefix table.
                if (info_.registeredPrefixId_ != 0) {
                    long interestFilterId = 0;
                    if (info_.onInterest_ != null) {
                        // registerPrefix was called with the "combined" form that includes the
                        // callback, so add an InterestFilterEntry.
                        interestFilterId = parent_.getNextEntryId();
                        parent_.setInterestFilter(interestFilterId,
                                new InterestFilter(info_.prefix_),
                                info_.onInterest_, info_.face_);
                    }

                    if (!parent_.registeredPrefixTable_.add(
                            info_.registeredPrefixId_, info_.prefix_,
                            interestFilterId)) {
                        // removeRegisteredPrefix was already called with the registeredPrefixId.
                        if (interestFilterId > 0)
                            // Remove the related interest filter we just added.
                            parent_.unsetInterestFilter(interestFilterId);

                        return;
                    }
                }

                net.named_data.jndn.Node.logger_.log(
                        ILOG.J2CsMapping.Util.Logging.Level.INFO,
                        "Register prefix succeeded with the NFD forwarder for prefix {0}",
                        info_.prefix_.toUri());
                if (info_.onRegisterSuccess_ != null) {
                    try {
                        info_.onRegisterSuccess_.onRegisterSuccess(info_.prefix_,
                                info_.registeredPrefixId_);
                    } catch (Exception ex_1) {
                        net.named_data.jndn.Node.logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterSuccess", ex_1);
                    }
                }
            }
Exemplo n.º 8
0
        /// <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);
        }
        static void Main(string[] args)
        {
            var data = new Data();
              data.wireDecode(new Blob(TlvData));
              Console.Out.WriteLine("Decoded Data:");
              dumpData(data);

              // Set the content again to clear the cached encoding so we encode again.
              data.setContent(data.getContent());
              var encoding = data.wireEncode();

              var reDecodedData = new Data();
              reDecodedData.wireDecode(encoding);
              Console.Out.WriteLine("");
              Console.Out.WriteLine("Re-decoded Data:");
              dumpData(reDecodedData);

              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));

              VerifyCallbacks callbacks = new VerifyCallbacks("Re-decoded Data");
              keyChain.verifyData(reDecodedData, callbacks, callbacks);

              var 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));
              keyChain.sign(freshData, certificateName);
              Console.Out.WriteLine("");
              Console.Out.WriteLine("Freshly-signed Data:");
              dumpData(freshData);

              callbacks = new VerifyCallbacks("Freshly-signed Data");
              keyChain.verifyData(freshData, callbacks, callbacks);
        }
Exemplo n.º 10
0
        public void onVerified(Data data, Interest originalInterest_0)
        {
            if (!endsWithSegmentNumber(data.getName())) {
                // We don't expect a name without a segment number.  Treat it as a bad packet.
                try {
                    onError_.onError(net.named_data.jndn.util.SegmentFetcher.ErrorCode.DATA_HAS_NO_SEGMENT,
                            "Got an unexpected packet without a segment number: "
                                    + data.getName().toUri());
                } catch (Exception ex) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", ex);
                }
            } else {
                long currentSegment;
                try {
                    currentSegment = data.getName().get(-1).toSegment();
                } catch (EncodingException ex_1) {
                    try {
                        onError_.onError(net.named_data.jndn.util.SegmentFetcher.ErrorCode.DATA_HAS_NO_SEGMENT,
                                "Error decoding the name segment number "
                                        + data.getName().get(-1).toEscapedString()
                                        + ": " + ex_1);
                    } catch (Exception exception) {
                        logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception);
                    }
                    return;
                }

                long expectedSegmentNumber = contentParts_.Count;
                if (currentSegment != expectedSegmentNumber) {
                    // Try again to get the expected segment.  This also includes the case
                    //   where the first segment is not segment 0.
                    fetchNextSegment(originalInterest_0, data.getName(),
                            expectedSegmentNumber);
                } else {
                    // Save the content and check if we are finished.
                    ILOG.J2CsMapping.Collections.Collections.Add(contentParts_,data.getContent());

                    if (data.getMetaInfo().getFinalBlockId().getValue().size() > 0) {
                        long finalSegmentNumber;
                        try {
                            finalSegmentNumber = data.getMetaInfo()
                                    .getFinalBlockId().toSegment();
                        } catch (EncodingException ex_2) {
                            try {
                                onError_.onError(net.named_data.jndn.util.SegmentFetcher.ErrorCode.DATA_HAS_NO_SEGMENT,
                                        "Error decoding the FinalBlockId segment number "
                                                + data.getMetaInfo()
                                                        .getFinalBlockId()
                                                        .toEscapedString() + ": "
                                                + ex_2);
                            } catch (Exception exception_3) {
                                logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError",
                                        exception_3);
                            }
                            return;
                        }

                        if (currentSegment == finalSegmentNumber) {
                            // We are finished.

                            // Get the total size and concatenate to get content.
                            int totalSize = 0;
                            for (int i = 0; i < contentParts_.Count; ++i)
                                totalSize += ((Blob) contentParts_[i]).size();
                            ByteBuffer content = ILOG.J2CsMapping.NIO.ByteBuffer.allocate(totalSize);
                            for (int i_4 = 0; i_4 < contentParts_.Count; ++i_4)
                                content.put(((Blob) contentParts_[i_4]).buf());
                            content.flip();

                            try {
                                onComplete_.onComplete(new Blob(content, false));
                            } catch (Exception ex_5) {
                                logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onComplete", ex_5);
                            }
                            return;
                        }
                    }

                    // Fetch the next segment.
                    fetchNextSegment(originalInterest_0, data.getName(),
                            expectedSegmentNumber + 1);
                }
            }
        }
        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>");
              }
        }
Exemplo n.º 12
0
        /// <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;
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Decrypt dKeyData.
        /// </summary>
        ///
        /// <param name="dKeyData">The D-KEY data packet.</param>
        /// <param name="onPlainText_0"></param>
        /// <param name="onError_1">This calls onError.onError(errorCode, message) for an error.</param>
        internal void decryptDKey(Data dKeyData, Consumer.OnPlainText  onPlainText_0,
				net.named_data.jndn.encrypt.EncryptError.OnError  onError_1)
        {
            // Get the encrypted content.
            Blob dataContent = dKeyData.getContent();

            // Process the nonce.
            // dataContent is a sequence of the two EncryptedContent.
            EncryptedContent encryptedNonce = new EncryptedContent();
            try {
                encryptedNonce.wireDecode(dataContent);
            } catch (EncodingException ex) {
                try {
                    onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.InvalidEncryptedFormat,
                            ex.Message);
                } catch (Exception exception) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception);
                }
                return;
            }
            Name consumerKeyName = encryptedNonce.getKeyLocator().getKeyName();

            // Get consumer decryption key.
            Blob consumerKeyBlob;
            try {
                consumerKeyBlob = getDecryptionKey(consumerKeyName);
            } catch (ConsumerDb.Error ex_2) {
                try {
                    onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.NoDecryptKey,
                            "Database error: " + ex_2.Message);
                } catch (Exception exception_3) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception_3);
                }
                return;
            }
            if (consumerKeyBlob.size() == 0) {
                try {
                    onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.NoDecryptKey,
                            "The desired consumer decryption key in not in the database");
                } catch (Exception exception_4) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception_4);
                }
                return;
            }

            // Process the D-KEY.
            // Use the size of encryptedNonce to find the start of encryptedPayload.
            ByteBuffer encryptedPayloadBuffer = dataContent.buf().duplicate();
            encryptedPayloadBuffer.position(encryptedNonce.wireEncode().size());
            Blob encryptedPayloadBlob_5 = new Blob(encryptedPayloadBuffer,
                    false);
            if (encryptedPayloadBlob_5.size() == 0) {
                try {
                    onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.InvalidEncryptedFormat,
                            "The data packet does not satisfy the D-KEY packet format");
                } catch (Exception ex_6) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", ex_6);
                }
                return;
            }

            // Decrypt the D-KEY.
            Consumer.OnPlainText  callerOnPlainText_7 = onPlainText_0;
            decrypt(encryptedNonce, consumerKeyBlob, new Consumer.Anonymous_C0 (callerOnPlainText_7, encryptedPayloadBlob_5, onError_1), onError_1);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Decrypt the data packet.
        /// </summary>
        ///
        /// <param name="data">The data packet. This does not verify the packet.</param>
        /// <param name="onPlainText_0"></param>
        /// <param name="onError_1">This calls onError.onError(errorCode, message) for an error.</param>
        internal void decryptContent(Data data, Consumer.OnPlainText  onPlainText_0,
				net.named_data.jndn.encrypt.EncryptError.OnError  onError_1)
        {
            // Get the encrypted content.
            EncryptedContent dataEncryptedContent_2 = new EncryptedContent();
            try {
                dataEncryptedContent_2.wireDecode(data.getContent());
            } catch (EncodingException ex) {
                try {
                    onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.InvalidEncryptedFormat,
                            ex.Message);
                } catch (Exception exception) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception);
                }
                return;
            }
            Name cKeyName_3 = dataEncryptedContent_2.getKeyLocator().getKeyName();

            // Check if the content key is already in the store.
            Blob cKey = (Blob) ILOG.J2CsMapping.Collections.Collections.Get(cKeyMap_,cKeyName_3);
            if (cKey != null)
                decrypt(dataEncryptedContent_2, cKey, onPlainText_0, onError_1);
            else {
                // Retrieve the C-KEY Data from the network.
                Name interestName = new Name(cKeyName_3);
                interestName.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_FOR)
                        .append(groupName_);
                Interest interest_4 = new Interest(interestName);

                // Prepare the callback functions.
                OnData onData_5 = new Consumer.Anonymous_C4 (this, cKeyName_3, onError_1, onPlainText_0,
                        dataEncryptedContent_2);

                OnTimeout onTimeout = new Consumer.Anonymous_C3 (this, onData_5, onError_1, interest_4);

                // Express the Interest.
                try {
                    face_.expressInterest(interest_4, onData_5, onTimeout);
                } catch (IOException ex_6) {
                    try {
                        onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.IOException,
                                "expressInterest error: " + ex_6.Message);
                    } catch (Exception exception_7) {
                        logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception_7);
                    }
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Decrypt cKeyData.
        /// </summary>
        ///
        /// <param name="cKeyData">The C-KEY data packet.</param>
        /// <param name="onPlainText_0"></param>
        /// <param name="onError_1">This calls onError.onError(errorCode, message) for an error.</param>
        internal void decryptCKey(Data cKeyData, Consumer.OnPlainText  onPlainText_0,
				net.named_data.jndn.encrypt.EncryptError.OnError  onError_1)
        {
            // Get the encrypted content.
            Blob cKeyContent = cKeyData.getContent();
            EncryptedContent cKeyEncryptedContent_2 = new EncryptedContent();
            try {
                cKeyEncryptedContent_2.wireDecode(cKeyContent);
            } catch (EncodingException ex) {
                try {
                    onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.InvalidEncryptedFormat,
                            ex.Message);
                } catch (Exception exception) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception);
                }
                return;
            }
            Name eKeyName = cKeyEncryptedContent_2.getKeyLocator().getKeyName();
            Name dKeyName_3 = eKeyName.getPrefix(-3);
            dKeyName_3.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_D_KEY).append(
                    eKeyName.getSubName(-2));

            // Check if the decryption key is already in the store.
            Blob dKey = (Blob) ILOG.J2CsMapping.Collections.Collections.Get(dKeyMap_,dKeyName_3);
            if (dKey != null)
                decrypt(cKeyEncryptedContent_2, dKey, onPlainText_0, onError_1);
            else {
                // Get the D-Key Data.
                Name interestName = new Name(dKeyName_3);
                interestName.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_FOR).append(
                        consumerName_);
                Interest interest_4 = new Interest(interestName);

                // Prepare the callback functions.
                OnData onData_5 = new Consumer.Anonymous_C2 (this, onError_1, onPlainText_0, dKeyName_3,
                        cKeyEncryptedContent_2);

                OnTimeout onTimeout = new Consumer.Anonymous_C1 (this, interest_4, onData_5, onError_1);

                // Express the Interest.
                try {
                    face_.expressInterest(interest_4, onData_5, onTimeout);
                } catch (IOException ex_6) {
                    try {
                        onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.IOException,
                                "expressInterest error: " + ex_6.Message);
                    } catch (Exception exception_7) {
                        logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception_7);
                    }
                }
            }
        }