示例#1
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");
        }
示例#2
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;
        }
示例#3
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)));
        }
示例#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)));
        }
示例#5
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));
 }
            public void onInterest(Name prefix, Interest interest, Face face,
						long interestFilterId, InterestFilter filter)
            {
                ++interestCallbackCount[0];
                    Data data = new Data(interest.getName());
                    data.setContent(new Blob("SUCCESS"));

                    try {
                        outer_TestFaceCallRegisterMethods.keyChain.sign(data, outer_TestFaceCallRegisterMethods.certificateName);
                    } catch (SecurityException ex) {
                        net.named_data.jndn.tests.integration_tests.TestFaceCallRegisterMethods.logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex);
                    }
                    try {
                        face.putData(data);
                    } catch (IOException ex_0) {
                        net.named_data.jndn.tests.integration_tests.TestFaceCallRegisterMethods.logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex_0);
                    }
            }
        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");
        }
        /**
         * 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;
        }
示例#9
0
        /// <summary>
        /// Create an E-KEY Data packet for the given public key.
        /// </summary>
        ///
        /// <param name="startTimeStamp">The start time stamp string to put in the name.</param>
        /// <param name="endTimeStamp">The end time stamp string to put in the name.</param>
        /// <param name="publicKeyBlob">A Blob of the public key DER.</param>
        /// <returns>The Data packet.</returns>
        /// <exception cref="System.Security.SecurityException">for an error using the security KeyChain.</exception>
        private Data createEKeyData(String startTimeStamp, String endTimeStamp,
				Blob publicKeyBlob)
        {
            Name name = new Name(namespace_);
            name.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_E_KEY).append(startTimeStamp)
                    .append(endTimeStamp);

            Data data = new Data(name);
            data.getMetaInfo().setFreshnessPeriod(
                    freshnessHours_ * MILLISECONDS_IN_HOUR);
            data.setContent(publicKeyBlob);
            keyChain_.sign(data);
            return data;
        }
示例#10
0
        /// <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);
        }
        public void testExtension()
        {
            // Now add an extension.
            String name = "/hello/kitty";
            int trustClass = 0;
            int trustLevel = 300;

            net.named_data.jndn.encoding.der.DerNode.DerSequence  extValueRoot = new net.named_data.jndn.encoding.der.DerNode.DerSequence ();
            net.named_data.jndn.encoding.der.DerNode.DerOctetString  extValueName = new net.named_data.jndn.encoding.der.DerNode.DerOctetString (new Blob(name).buf());
            net.named_data.jndn.encoding.der.DerNode.DerInteger  extValueTrustClass = new net.named_data.jndn.encoding.der.DerNode.DerInteger (trustClass);
            net.named_data.jndn.encoding.der.DerNode.DerInteger  extValueTrustLevel = new net.named_data.jndn.encoding.der.DerNode.DerInteger (trustLevel);

            extValueRoot.addChild(extValueName);
            extValueRoot.addChild(extValueTrustClass);
            extValueRoot.addChild(extValueTrustLevel);

            Blob extValueData = extValueRoot.encode();

            String oidString = "1.3.6.1.5.32.1";
            bool isCritical = true;
            CertificateExtension certExtension = new CertificateExtension(
                    oidString, isCritical, extValueData);
            toyCert.encode();
            Certificate cert = new Certificate(toyCert);
            cert.addExtension(certExtension);

            cert.encode();
            Blob certData = cert.getContent();
            Data plainData = new Data();
            plainData.setContent(certData);
            // The constructor Certificate(Data) calls decode().
            Certificate decodedCert = new Certificate(plainData);
            Assert.AssertEquals("Wrong number of certificate extensions after decoding",
                    1, decodedCert.getExtensionList().Count);

            CertificateExtension decodedExtension = (CertificateExtension) decodedCert
                            .getExtensionList()[0];
            Assert.AssertEquals("Certificate extension has the wrong OID after decoding",
                    oidString, "" + decodedExtension.getOid());
            Assert.AssertEquals(
                    "Certificate extension has the wrong isCritical value after decoding",
                    isCritical, decodedExtension.getIsCritical());

            // Decode and check the extension value.
            DerNode parsedExtValue = net.named_data.jndn.encoding.der.DerNode.parse(decodedExtension.getValue()
                    .buf());
            IList decodedExtValueRoot = parsedExtValue.getChildren();
            Assert.AssertEquals(
                    "Wrong number of certificate extension value items after decoding",
                    3, decodedExtValueRoot.Count);

            net.named_data.jndn.encoding.der.DerNode.DerOctetString  decodedName = (net.named_data.jndn.encoding.der.DerNode.DerOctetString ) decodedExtValueRoot[0];
            net.named_data.jndn.encoding.der.DerNode.DerInteger  decodedTrustClass = (net.named_data.jndn.encoding.der.DerNode.DerInteger ) decodedExtValueRoot[1];
            net.named_data.jndn.encoding.der.DerNode.DerInteger  decodedTrustLevel = (net.named_data.jndn.encoding.der.DerNode.DerInteger ) decodedExtValueRoot[2];
            Assert.AssertEquals("Wrong extension value name after decoding", name, ""
                    + decodedName.toVal());
            Assert.AssertEquals("Wrong extension value trust class after decoding",
                    trustClass, (int) (Int32) decodedTrustClass.toVal());
            Assert.AssertEquals("Wrong extension value trust level after decoding",
                    trustLevel, (int) (Int32) decodedTrustLevel.toVal());
        }
        public void testEncodeDecode()
        {
            toyCert.encode();
            Blob cert_data = toyCert.getContent();
            Data plainData = new Data();
            plainData.setName(toyCert.getName());
            plainData.setContent(cert_data);
            // The constructor Certificate(Data) calls decode().
            Certificate decoded_cert = new Certificate(plainData);

            Assert.AssertEquals("Certificate representation changed after encoding", ""
                    + toyCert, "" + decoded_cert);
        }
        public void testDecode()
        {
            Data data = new Data(new Name("/tmp"));
            data.setContent(new Blob(REAL_CERT, false));
            // The constructor Certificate(Data) calls decode().
            Certificate realCert = new Certificate(data);

            Assert.AssertEquals("Certificate representation changed after decoding",
                    REAL_CERT_STRING, "" + realCert);
        }
        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);
        }
            public void onInterest(Name prefix, Interest interest, Face face, long interestFilterId,
        InterestFilter filter)
            {
                ++responseCount_;

                // Make and sign a Data packet.
                var data = new Data(interest.getName());
                var content = "Echo " + interest.getName().toUri();
                data.setContent(new Blob(content));

                try {
                  keyChain_.sign(data, certificateName_);      }
                catch (SecurityException exception) {
                  // Don't expect this to happen.
                  throw new SecurityException
                  ("SecurityException in sign: " + exception);
                }

                Console.Out.WriteLine("Sent content " + content);
                try {
                  face.putData(data);
                } catch (Exception ex) {
                  Console.Out.WriteLine("Echo: Exception in sending data " + ex);
                }
            }