/// <summary>
        /// Append a timestamp component and a random value component to interest's
        /// name. This ensures that the timestamp is greater than the timestamp used in
        /// the previous call. Then use keyChain to sign the interest which appends a
        /// SignatureInfo component and a component with the signature bits. If the
        /// interest lifetime is not set, this sets it.
        /// </summary>
        ///
        /// <param name="interest">The interest whose name is append with components.</param>
        /// <param name="keyChain">The KeyChain for calling sign.</param>
        /// <param name="certificateName">The certificate name of the key to use for signing.</param>
        /// <param name="wireFormat"></param>
        public void generate(Interest interest, KeyChain keyChain,
				Name certificateName, WireFormat wireFormat)
        {
            double timestamp;
             lock (lastTimestampLock_) {
                        timestamp = Math.Round(net.named_data.jndn.util.Common.getNowMilliseconds(),MidpointRounding.AwayFromZero);
                        while (timestamp <= lastTimestamp_)
                            timestamp += 1.0d;
                        // Update the timestamp now while it is locked. In the small chance that
                        //   signing fails, it just means that we have bumped the timestamp.
                        lastTimestamp_ = timestamp;
                    }

            // The timestamp is encoded as a TLV nonNegativeInteger.
            TlvEncoder encoder = new TlvEncoder(8);
            encoder.writeNonNegativeInteger((long) timestamp);
            interest.getName().append(new Blob(encoder.getOutput(), false));

            // The random value is a TLV nonNegativeInteger too, but we know it is 8 bytes,
            //   so we don't need to call the nonNegativeInteger encoder.
            ByteBuffer randomBuffer = ILOG.J2CsMapping.NIO.ByteBuffer.allocate(8);
            // Note: SecureRandom is thread safe.
            net.named_data.jndn.util.Common.getRandom().nextBytes(randomBuffer.array());
            interest.getName().append(new Blob(randomBuffer, false));

            keyChain.sign(interest, certificateName, wireFormat);

            if (interest.getInterestLifetimeMilliseconds() < 0)
                // The caller has not set the interest lifetime, so set it here.
                interest.setInterestLifetimeMilliseconds(1000.0d);
        }
Exemplo n.º 2
0
 /// <summary>
 /// Create a new Face for communication with an NDN hub at host using the
 /// default port 6363 and the default TcpTransport.
 /// </summary>
 ///
 /// <param name="host">The host of the NDN hub.</param>
 public Face(String host)
 {
     this.commandKeyChain_ = null;
     this.commandCertificateName_ = new Name();
     node_ = new Node(new TcpTransport(), new TcpTransport.ConnectionInfo(
             host, 6363));
 }
Exemplo n.º 3
0
        /// <summary>
        /// Create a group manager with the given values. The group manager namespace
        /// is /{prefix}/read/{dataType} .
        /// </summary>
        ///
        /// <param name="prefix">The prefix for the group manager namespace.</param>
        /// <param name="dataType">The data type for the group manager namespace.</param>
        /// <param name="database"></param>
        /// <param name="keySize">The group key will be an RSA key with keySize bits.</param>
        /// <param name="freshnessHours"></param>
        /// <param name="keyChain"></param>
        public GroupManager(Name prefix, Name dataType, GroupManagerDb database,
				int keySize, int freshnessHours, KeyChain keyChain)
        {
            namespace_ = new Name(prefix).append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_READ)
                    .append(dataType);
            database_ = database;
            keySize_ = keySize;
            freshnessHours_ = freshnessHours;

            keyChain_ = keyChain;
        }
Exemplo n.º 4
0
        /// <summary>
        /// Create a Consumer to use the given ConsumerDb, Face and other values.
        /// </summary>
        ///
        /// <param name="face">The face used for data packet and key fetching.</param>
        /// <param name="keyChain">The keyChain used to verify data packets.</param>
        /// <param name="groupName"></param>
        /// <param name="consumerName"></param>
        /// <param name="database">The ConsumerDb database for storing decryption keys.</param>
        public Consumer(Face face, KeyChain keyChain, Name groupName,
				Name consumerName, ConsumerDb database)
        {
            this.cKeyMap_ = new Hashtable();
                    this.dKeyMap_ = new Hashtable();
            database_ = database;
            keyChain_ = keyChain;
            face_ = face;
            groupName_ = new Name(groupName);
            consumerName_ = new Name(consumerName);
        }
        public void setUp()
        {
            Name[] localCertificateName = new Name[1];
            keyChain = net.named_data.jndn.tests.integration_tests.IntegrationTestsCommon.buildKeyChain(localCertificateName);
            certificateName = localCertificateName[0];

            faceIn = net.named_data.jndn.tests.integration_tests.IntegrationTestsCommon.buildFaceWithKeyChain("localhost",
                    keyChain, certificateName);
            faceOut = net.named_data.jndn.tests.integration_tests.IntegrationTestsCommon.buildFaceWithKeyChain("localhost",
                    keyChain, certificateName);
        }
Exemplo n.º 6
0
        public void setUp()
        {
            // Don't show INFO log messages.
            ILOG.J2CsMapping.Util.Logging.Logger.getLogger("").setLevel(ILOG.J2CsMapping.Util.Logging.Level.WARNING);

            FileInfo policyConfigDirectory = net.named_data.jndn.tests.integration_tests.IntegrationTestsCommon
                    .getPolicyConfigDirectory();

            databaseFilePath = new FileInfo(System.IO.Path.Combine(policyConfigDirectory.FullName,"test-public-info.db"));
            databaseFilePath.delete();

            identityStorage = new BasicIdentityStorage(System.IO.Path.GetFullPath(databaseFilePath.Name));
            identityManager = new IdentityManager(identityStorage,
                    new FilePrivateKeyStorage());
            policyManager = new SelfVerifyPolicyManager(identityStorage);
            keyChain = new KeyChain(identityManager, policyManager);
        }
Exemplo n.º 7
0
            public VerifyCallbacks(KeyChain chain, ValidationRequest nextStep, int retry,
						OnDataValidationFailed onValidationFailed, Data originalData)
            {
                outer_KeyChain = chain;
                    nextStep_ = nextStep;
                    retry_ = retry;
                    onValidationFailed_ = onValidationFailed;
                    originalData_ = originalData;
            }
Exemplo n.º 8
0
 /// <summary>
 /// Create a CommandInterestSigner to use the keyChain to sign.
 /// </summary>
 ///
 /// <param name="keyChain">The KeyChain used to sign.</param>
 public CommandInterestSigner(KeyChain keyChain)
 {
     keyChain_ = keyChain;
 }
Exemplo n.º 9
0
        public void testNoVerify()
        {
            NoVerifyPolicyManager policyManager = new NoVerifyPolicyManager();
            Name identityName = new Name("TestValidator/Null")
                    .appendVersion((long) getNowSeconds());

            KeyChain keyChain = new KeyChain(identityManager_, policyManager);
            keyChain.createIdentityAndCertificate(identityName);
            Data data = new Data(new Name(identityName).append("data"));
            keyChain.signByIdentity(data, identityName);

            VerificationResult vr = doVerify(policyManager, data);

            AssertFalse("NoVerifyPolicyManager returned a ValidationRequest",
                    vr.hasFurtherSteps_);

            AssertEquals("Verification failed with NoVerifyPolicyManager", 0,
                    vr.failureCount_);
            AssertEquals("Verification success called " + vr.successCount_
                    + " times instead of 1", 1, vr.successCount_);
        }
        /// <summary>
        /// Create a Face using a the given KeyChain and certificate name.
        /// </summary>
        ///
        /// <param name="keyChain">The KeyChain. This calls keyChain.setFace with the created Face.</param>
        /// <param name="certificateName">The signing certificate name to use with keyChain.</param>
        /// <param name="hostname"></param>
        /// <returns>A Face configured with a valid signing key chain.</returns>
        /// <exception cref="System.Security.SecurityException"></exception>
        public static Face buildFaceWithKeyChain(String hostname,
				KeyChain keyChain, Name certificateName)
        {
            Face face = new Face(hostname);
            keyChain.setFace(face);
            face.setCommandSigningInfo(keyChain, certificateName);

            return face;
        }
        /// <summary>
        /// Append a timestamp component and a random value component to interest's
        /// name. This ensures that the timestamp is greater than the timestamp used in
        /// the previous call. Then use keyChain to sign the interest which appends a
        /// SignatureInfo component and a component with the signature bits. If the
        /// interest lifetime is not set, this sets it. Use the default WireFormat to
        /// encode the SignatureInfo and to encode interest name for signing.
        /// </summary>
        ///
        /// <param name="interest">The interest whose name is append with components.</param>
        /// <param name="keyChain">The KeyChain for calling sign.</param>
        /// <param name="certificateName">The certificate name of the key to use for signing.</param>
        public void generate(Interest interest, KeyChain keyChain,
				Name certificateName)
        {
            generate(interest, keyChain, certificateName,
                    net.named_data.jndn.encoding.WireFormat.getDefaultWireFormat());
        }
Exemplo n.º 12
0
        /// <summary>
        /// Append a timestamp component and a random value component to interest's
        /// name. Then use the keyChain and certificateName to sign the interest. If
        /// the interest lifetime is not set, this sets it.
        /// </summary>
        ///
        /// <param name="interest">The interest whose name is append with components.</param>
        /// <param name="keyChain">The KeyChain object for signing interests.</param>
        /// <param name="certificateName">The certificate name for signing interests.</param>
        /// <param name="wireFormat"></param>
        /// <exception cref="System.Security.SecurityException">If cannot find the private key for thecertificateName.</exception>
        internal void makeCommandInterest(Interest interest, KeyChain keyChain,
				Name certificateName, WireFormat wireFormat)
        {
            commandInterestGenerator_.generate(interest, keyChain, certificateName,
                    wireFormat);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Register prefix with the connected NDN hub and call onInterest when a
        /// matching interest is received. To register a prefix with NFD, you must
        /// first call setCommandSigningInfo.
        /// </summary>
        ///
        /// <param name="registeredPrefixId"></param>
        /// <param name="prefix">A Name for the prefix to register. This copies the Name.</param>
        /// <param name="onInterest">onInterest.onInterest(prefix, interest, face, interestFilterId, filter). If onInterest is null, it is ignored and you must call setInterestFilter.</param>
        /// <param name="onRegisterFailed">prefix.</param>
        /// <param name="onRegisterSuccess">receives a success message from the forwarder. If onRegisterSuccess is null, this does not use it.</param>
        /// <param name="flags"></param>
        /// <param name="wireFormat">A WireFormat object used to encode the message.</param>
        /// <param name="commandKeyChain">The KeyChain object for signing interests.</param>
        /// <param name="commandCertificateName">The certificate name for signing interests.</param>
        /// <param name="face"></param>
        /// <exception cref="IOException">For I/O error in sending the registration request.</exception>
        /// <exception cref="System.Security.SecurityException">If signing a command interest for NFD and cannotfind the private key for the certificateName.</exception>
        public void registerPrefix(long registeredPrefixId, Name prefix,
				OnInterestCallback onInterest, OnRegisterFailed onRegisterFailed,
				OnRegisterSuccess onRegisterSuccess, ForwardingFlags flags,
				WireFormat wireFormat, KeyChain commandKeyChain,
				Name commandCertificateName, Face face)
        {
            nfdRegisterPrefix(registeredPrefixId, new Name(prefix), onInterest,
                    onRegisterFailed, onRegisterSuccess, flags, commandKeyChain,
                    commandCertificateName, wireFormat, face);
        }
Exemplo n.º 14
0
        public void setUp()
        {
            policyConfigDirectory = net.named_data.jndn.tests.integration_tests.IntegrationTestsCommon
                    .getPolicyConfigDirectory();

            identityStorage = new MemoryIdentityStorage();
            privateKeyStorage = new MemoryPrivateKeyStorage();
            // Not using keychain for verification so we don't need to set the
            //   policy manager.
            keyChain = new KeyChain(new IdentityManager(identityStorage,
                    privateKeyStorage));
            identityName = new Name("/SecurityTestSecRule/Basic/Longer");

            Name keyName = new Name(identityName).append("ksk-2439872");
            defaultCertName = certNameFromKeyName(keyName);
            identityStorage.addKey(keyName, net.named_data.jndn.security.KeyType.RSA, new Blob(
                    DEFAULT_RSA_PUBLIC_KEY_DER, false));
            privateKeyStorage.setKeyPairForKeyName(keyName, net.named_data.jndn.security.KeyType.RSA,
                    DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER);

            keyName = new Name("/SecurityTestSecRule/Basic/ksk-0923489");
            identityStorage.addKey(keyName, net.named_data.jndn.security.KeyType.RSA, new Blob(
                    DEFAULT_RSA_PUBLIC_KEY_DER, false));
            privateKeyStorage.setKeyPairForKeyName(keyName, net.named_data.jndn.security.KeyType.RSA,
                    DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER);

            shortCertName = certNameFromKeyName(keyName, -2);

            net.named_data.jndn.security.policy.ConfigPolicyManager.setFriendAccess(this);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Initiate segment fetching. For more details, see the documentation for
        /// the class.
        /// </summary>
        ///
        /// <param name="face">This calls face.expressInterest to fetch more segments.</param>
        /// <param name="baseInterest">This interest may include a custom InterestLifetime and selectors that will propagate to all subsequent Interests. The only exception is that the initial Interest will be forced to include selectors "ChildSelector=1" and "MustBeFresh=true" which will be turned off in subsequent Interests.</param>
        /// <param name="validatorKeyChain">fetching and call onError with SEGMENT_VERIFICATION_FAILED. This does not make a copy of the KeyChain; the object must remain valid while fetching. If validatorKeyChain is null, this does not validate the data packet.</param>
        /// <param name="onComplete">content of all the segments. 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="onError">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>
        public static void fetch(Face face, Interest baseInterest,
				KeyChain validatorKeyChain, SegmentFetcher.OnComplete  onComplete, SegmentFetcher.OnError  onError)
        {
            new SegmentFetcher(face, validatorKeyChain, DontVerifySegment,
                    onComplete, onError).fetchFirstSegment(baseInterest);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Create a new SegmentFetcher to use the Face. See the static fetch method
        /// for details. If validatorKeyChain is not null, use it and ignore
        /// verifySegment. After creating the SegmentFetcher, call fetchFirstSegment.
        /// </summary>
        ///
        /// <param name="face">This calls face.expressInterest to fetch more segments.</param>
        /// <param name="validatorKeyChain"></param>
        /// <param name="verifySegment">and call onError.onError with ErrorCode.SEGMENT_VERIFICATION_FAILED.</param>
        /// <param name="onComplete">content of all the segments.</param>
        /// <param name="onError"></param>
        private SegmentFetcher(Face face, KeyChain validatorKeyChain,
				SegmentFetcher.VerifySegment  verifySegment, SegmentFetcher.OnComplete  onComplete, SegmentFetcher.OnError  onError)
        {
            this.contentParts_ = new ArrayList();
            face_ = face;
            validatorKeyChain_ = validatorKeyChain;
            verifySegment_ = verifySegment;
            onComplete_ = onComplete;
            onError_ = onError;
        }
        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.º 18
0
        public void testSelfVerification()
        {
            SelfVerifyPolicyManager policyManager = new SelfVerifyPolicyManager(
                    identityStorage_);
            KeyChain keyChain = new KeyChain(identityManager_, policyManager);

            Name identityName = new Name("TestValidator/RsaSignatureVerification");
            keyChain.createIdentityAndCertificate(identityName);

            Data data = new Data(new Name("/TestData/1"));
            keyChain.signByIdentity(data, identityName);

            VerificationResult vr = doVerify(policyManager, data);

            AssertFalse("SelfVerifyPolicyManager returned a ValidationRequest",
                    vr.hasFurtherSteps_);
            AssertEquals("Verification of identity-signed data failed", 0,
                    vr.failureCount_);
            AssertEquals("Verification success called " + vr.successCount_
                    + " times instead of 1", 1, vr.successCount_);

            Data data2 = new Data(new Name("/TestData/2"));

            vr = doVerify(policyManager, data2);

            AssertFalse("SelfVerifyPolicyManager returned a ValidationRequest",
                    vr.hasFurtherSteps_);
            AssertEquals("Verification of unsigned data succeeded", 0,
                    vr.successCount_);
            AssertEquals("Verification failure callback called " + vr.failureCount_
                    + " times instead of 1", 1, vr.failureCount_);
        }
Exemplo n.º 19
0
            public VerifyCallbacksForVerifyInterest(KeyChain chain, ValidationRequest nextStep,
						int retry, OnInterestValidationFailed onValidationFailed,
						Interest originalInterest)
            {
                outer_KeyChain = chain;
                    nextStep_ = nextStep;
                    retry_ = retry;
                    onValidationFailed_ = onValidationFailed;
                    originalInterest_ = originalInterest;
            }
Exemplo n.º 20
0
        public void setUp()
        {
            MemoryIdentityStorage identityStorage = new MemoryIdentityStorage();
            MemoryPrivateKeyStorage privateKeyStorage = new MemoryPrivateKeyStorage();
            keyChain = new KeyChain(new IdentityManager(identityStorage,
                    privateKeyStorage),
                    new SelfVerifyPolicyManager(identityStorage));

            // Initialize the storage.
            Name keyName = new Name("/testname/DSK-123");
            certificateName = keyName.getSubName(0, keyName.size() - 1)
                    .append("KEY").append(keyName.get(-1)).append("ID-CERT")
                    .append("0");
            try {
                identityStorage.addKey(keyName, net.named_data.jndn.security.KeyType.RSA, new Blob(
                        DEFAULT_RSA_PUBLIC_KEY_DER, false));
                privateKeyStorage.setKeyPairForKeyName(keyName, net.named_data.jndn.security.KeyType.RSA,
                        DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER);
            } catch (SecurityException ex) {
                // We don't expect this to happen.
                ILOG.J2CsMapping.Util.Logging.Logger.getLogger(typeof(TestLink).FullName).log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null,
                        ex);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Do the work of registerPrefix to register with NFD.
        /// </summary>
        ///
        /// <param name="registeredPrefixId">registeredPrefixTable_ (assuming it has already been done).</param>
        /// <param name="prefix"></param>
        /// <param name="onInterest"></param>
        /// <param name="onRegisterFailed"></param>
        /// <param name="onRegisterSuccess"></param>
        /// <param name="flags"></param>
        /// <param name="commandKeyChain"></param>
        /// <param name="commandCertificateName"></param>
        /// <param name="wireFormat_0"></param>
        /// <param name="face_1"></param>
        /// <exception cref="System.Security.SecurityException">If cannot find the private key for thecertificateName.</exception>
        private void nfdRegisterPrefix(long registeredPrefixId, Name prefix,
				OnInterestCallback onInterest, OnRegisterFailed onRegisterFailed,
				OnRegisterSuccess onRegisterSuccess, ForwardingFlags flags,
				KeyChain commandKeyChain, Name commandCertificateName,
				WireFormat wireFormat_0, Face face_1)
        {
            if (commandKeyChain == null)
                throw new Exception(
                        "registerPrefix: The command KeyChain has not been set. You must call setCommandSigningInfo.");
            if (commandCertificateName.size() == 0)
                throw new Exception(
                        "registerPrefix: The command certificate name has not been set. You must call setCommandSigningInfo.");

            ControlParameters controlParameters = new ControlParameters();
            controlParameters.setName(prefix);
            controlParameters.setForwardingFlags(flags);

            Interest commandInterest = new Interest();

            // Determine whether to use remote prefix registration.
            bool faceIsLocal;
            try {
                faceIsLocal = isLocal();
            } catch (IOException ex) {
                logger_.log(
                        ILOG.J2CsMapping.Util.Logging.Level.INFO,
                        "Register prefix failed: Error attempting to determine if the face is local: {0}",
                        ex);
                try {
                    onRegisterFailed.onRegisterFailed(prefix);
                } catch (Exception exception) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterFailed",
                            exception);
                }
                return;
            }

            if (faceIsLocal) {
                commandInterest.setName(new Name("/localhost/nfd/rib/register"));
                // The interest is answered by the local host, so set a short timeout.
                commandInterest.setInterestLifetimeMilliseconds(2000.0d);
            } else {
                commandInterest.setName(new Name("/localhop/nfd/rib/register"));
                // The host is remote, so set a longer timeout.
                commandInterest.setInterestLifetimeMilliseconds(4000.0d);
            }

            // NFD only accepts TlvWireFormat packets.
            commandInterest.getName().append(
                    controlParameters.wireEncode(net.named_data.jndn.encoding.TlvWireFormat.get()));
            makeCommandInterest(commandInterest, commandKeyChain,
                    commandCertificateName, net.named_data.jndn.encoding.TlvWireFormat.get());

            // Send the registration interest.
            Node.RegisterResponse  response = new Node.RegisterResponse (
                    new RegisterResponse.Info(prefix, onRegisterFailed,
                            onRegisterSuccess, registeredPrefixId, onInterest, face_1),
                    this);
            try {
                expressInterest(getNextEntryId(), commandInterest, response,
                        response, null, wireFormat_0, face_1);
            } catch (IOException ex_2) {
                // Can't send the interest. Call onRegisterFailed.
                logger_.log(
                        ILOG.J2CsMapping.Util.Logging.Level.INFO,
                        "Register prefix failed: Error sending the register prefix interest to the forwarder: {0}",
                        ex_2);
                try {
                    onRegisterFailed.onRegisterFailed(prefix);
                } catch (Exception exception_3) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterFailed",
                            exception_3);
                }
            }
        }
Exemplo n.º 22
0
        public CredentialStorage()
        {
            this.identityStorage_ = new MemoryIdentityStorage();
            this.privateKeyStorage_ = new MemoryPrivateKeyStorage();
            this.keyChain_ = new KeyChain(new IdentityManager(
                    identityStorage_, privateKeyStorage_), new SelfVerifyPolicyManager(
                    identityStorage_));
            Name keyName = new Name("/testname/DSK-123");
            defaultCertName_ = keyName.getSubName(0, keyName.size() - 1)
                    .append("KEY").append(keyName.get(-1)).append("ID-CERT")
                    .append("0");

            Name ecdsaKeyName = new Name("/testEcdsa/DSK-123");
            ecdsaCertName_ = ecdsaKeyName.getSubName(0, ecdsaKeyName.size() - 1)
                    .append("KEY").append(ecdsaKeyName.get(-1)).append("ID-CERT")
                    .append("0");

            try {
                identityStorage_.addKey(keyName, net.named_data.jndn.security.KeyType.RSA, new Blob(
                        DEFAULT_RSA_PUBLIC_KEY_DER, false));
                privateKeyStorage_.setKeyPairForKeyName(keyName, net.named_data.jndn.security.KeyType.RSA,
                        DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER);

            #if false // Skip ECDSA for now.
                identityStorage_.addKey(ecdsaKeyName, net.named_data.jndn.security.KeyType.ECDSA, new Blob(
                        DEFAULT_EC_PUBLIC_KEY_DER, false));
                privateKeyStorage_.setKeyPairForKeyName(ecdsaKeyName,
                        net.named_data.jndn.security.KeyType.ECDSA, DEFAULT_EC_PUBLIC_KEY_DER,
                        DEFAULT_EC_PRIVATE_KEY_DER);
            #endif
            } catch (SecurityException ex) {
                // Don't expect this to happen;
                System.Console.Out.WriteLine("Exception setting test keys: " + ex);
                identityStorage_ = null;
                privateKeyStorage_ = null;
            }
        }
Exemplo n.º 23
0
 /// <summary>
 /// Create a new Face for communication with an NDN hub with the given
 /// Transport object and connectionInfo.
 /// </summary>
 ///
 /// <param name="transport">A Transport object used for communication.</param>
 /// <param name="connectionInfo"></param>
 public Face(Transport transport, Transport.ConnectionInfo connectionInfo)
 {
     this.commandKeyChain_ = null;
     this.commandCertificateName_ = new Name();
     node_ = new Node(transport, connectionInfo);
 }
Exemplo n.º 24
0
        /// <summary>
        /// Create a Producer to use the given ProducerDb, Face and other values.
        /// A producer can produce data with a naming convention:
        /// /{prefix}/SAMPLE/{dataType}/[timestamp]
        /// The produced data packet is encrypted with a content key,
        /// which is stored in the ProducerDb database.
        /// A producer also needs to produce data containing a content key
        /// encrypted with E-KEYs. A producer can retrieve E-KEYs through the face,
        /// and will re-try for at most repeatAttemps times when E-KEY retrieval fails.
        /// </summary>
        ///
        /// <param name="prefix">The producer name prefix. This makes a copy of the Name.</param>
        /// <param name="dataType"></param>
        /// <param name="face">The face used to retrieve keys.</param>
        /// <param name="keyChain">The keyChain used to sign data packets.</param>
        /// <param name="database">The ProducerDb database for storing keys.</param>
        /// <param name="repeatAttempts">The maximum retry for retrieving keys.</param>
        public Producer(Name prefix, Name dataType, Face face, KeyChain keyChain,
				ProducerDb database, int repeatAttempts)
        {
            this.eKeyInfo_ = new Hashtable();
                    this.keyRequests_ = new Hashtable();
            face_ = face;
            keyChain_ = keyChain;
            database_ = database;
            maxRepeatAttempts_ = repeatAttempts;

            construct(prefix, dataType);
        }
Exemplo n.º 25
0
 /// <summary>
 /// Set the KeyChain and certificate name used to sign command interests
 /// (e.g. for registerPrefix).
 /// </summary>
 ///
 /// <param name="keyChain">object and pass it in. You can create a default KeyChain for your system with the default KeyChain constructor.</param>
 /// <param name="certificateName">with keyChain.getDefaultCertificateName() .</param>
 public void setCommandSigningInfo(KeyChain keyChain, Name certificateName)
 {
     commandKeyChain_ = keyChain;
     commandCertificateName_ = new Name(certificateName);
 }
        /// <summary>
        /// Create a KeyChain with the a default name and key pair.
        /// </summary>
        ///
        /// <param name="certificateName">Set certificateName[0] to the signing certificateName.</param>
        /// <returns>The KeyChain.</returns>
        /// <exception cref="System.Security.SecurityException"></exception>
        public static KeyChain buildKeyChain(Name[] certificateName)
        {
            MemoryIdentityStorage identityStorage = new MemoryIdentityStorage();
            MemoryPrivateKeyStorage privateKeyStorage = new MemoryPrivateKeyStorage();
            KeyChain keyChain = new KeyChain(new IdentityManager(identityStorage,
                    privateKeyStorage),
                    new SelfVerifyPolicyManager(identityStorage));

            // initialize the storage with
            Name keyName = new Name("/testname/DSK-123");
            certificateName[0] = keyName.getSubName(0, keyName.size() - 1)
                    .append("KEY").append(keyName.get(-1)).append("ID-CERT")
                    .append("0");
            identityStorage.addKey(keyName, net.named_data.jndn.security.KeyType.RSA, new Blob(
                    DEFAULT_RSA_PUBLIC_KEY_DER, false));
            privateKeyStorage.setKeyPairForKeyName(keyName, net.named_data.jndn.security.KeyType.RSA,
                    DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER);

            return keyChain;
        }
Exemplo n.º 27
0
        public void setUp()
        {
            // Don't show INFO log messages.
            ILOG.J2CsMapping.Util.Logging.Logger.getLogger("").setLevel(ILOG.J2CsMapping.Util.Logging.Level.WARNING);

            policyConfigDirectory_ = net.named_data.jndn.tests.integration_tests.IntegrationTestsCommon
                    .getPolicyConfigDirectory();

            testCertFile_ = new FileInfo(System.IO.Path.Combine(new FileInfo(System.IO.Path.Combine(policyConfigDirectory_.FullName,"certs")).FullName,"test.cert"));

            identityStorage_ = new MemoryIdentityStorage();
            privateKeyStorage_ = new MemoryPrivateKeyStorage();
            identityManager_ = new IdentityManager(identityStorage_,
                    privateKeyStorage_);
            policyManager_ = new ConfigPolicyManager(System.IO.Path.GetFullPath(new FileInfo(System.IO.Path.Combine(policyConfigDirectory_.FullName,"simple_rules.conf")).Name));

            identityName_ = new Name("/TestConfigPolicyManager/temp");
            // To match the anchor cert.
            Name keyName = new Name(identityName_).append("ksk-1416010123");
            identityStorage_.addKey(keyName, net.named_data.jndn.security.KeyType.RSA, new Blob(
                    DEFAULT_RSA_PUBLIC_KEY_DER, false));
            privateKeyStorage_.setKeyPairForKeyName(keyName, net.named_data.jndn.security.KeyType.RSA,
                    DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER);

            IdentityCertificate cert = identityManager_.selfSign(keyName);
            identityStorage_.setDefaultKeyNameForIdentity(keyName);
            identityManager_.addCertificateAsDefault(cert);

            face_ = new Face("localhost");
            keyChain_ = new KeyChain(identityManager_, policyManager_);
            keyName_ = keyName;

            net.named_data.jndn.security.policy.ConfigPolicyManager.setFriendAccess(this);
        }
        /**
         * Loop to decode a data packet nIterations times.
         * @param nIterations The number of iterations.
         * @param useCrypto If true, verify the signature.  If false, don't verify.
         * @param keyType KeyType.RSA or EC, used if useCrypto is true.
         * @param encoding The wire encoding to decode.
         * @return The number of seconds for all iterations.
         * @throws EncodingException
         */
        private static double benchmarkDecodeDataSeconds(int nIterations, bool useCrypto, KeyType keyType, Blob encoding)
        {
            // Initialize the KeyChain storage in case useCrypto is true.
              MemoryIdentityStorage identityStorage = new MemoryIdentityStorage();
              KeyChain keyChain = new KeyChain
            (new IdentityManager(identityStorage, new MemoryPrivateKeyStorage()),
              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");
              identityStorage.addKey(keyName, KeyType.RSA, new Blob(DEFAULT_RSA_PUBLIC_KEY_DER));
              VerifyCallbacks callbacks = new VerifyCallbacks();

              double start = getNowSeconds();
              for (int i = 0; i < nIterations; ++i) {
            Data data = new Data();
            data.wireDecode(encoding.buf());

            if (useCrypto)
              keyChain.verifyData(data, callbacks, callbacks);
              }
              double finish = getNowSeconds();

              return finish - start;
        }
        /**
         * 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;
        }
        static void Main(string[] args)
        {
            var interest = new Interest();
              interest.wireDecode(new Blob(TlvInterest));
              Console.Out.WriteLine("Interest:");
              dumpInterest(interest);

              // Set the name again to clear the cached encoding so we encode again.
              interest.setName(interest.getName());
              var encoding = interest.wireEncode();
              Console.Out.WriteLine("");
              Console.Out.WriteLine("Re-encoded interest " + encoding.toHex());

              var reDecodedInterest = new Interest();
              reDecodedInterest.wireDecode(encoding);
              Console.Out.WriteLine("");
              Console.Out.WriteLine("Re-decoded Interest:");
              dumpInterest(reDecodedInterest);

              var freshInterest = new Interest(new Name("/ndn/abc"));
              freshInterest.setMinSuffixComponents(4);
              freshInterest.setMaxSuffixComponents(6);
              freshInterest.setInterestLifetimeMilliseconds(30000);
              freshInterest.setChildSelector(1);
              freshInterest.setMustBeFresh(true);
              freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST);
              freshInterest.getKeyLocator().setKeyData
            (new Blob(new byte[] {
              0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
              0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }));
              freshInterest.getExclude().appendComponent(new Name("abc").get(0)).appendAny();

              var identityStorage = new MemoryIdentityStorage();
              var privateKeyStorage = new MemoryPrivateKeyStorage();
              var keyChain = new KeyChain
            (new IdentityManager(identityStorage, privateKeyStorage),
              new SelfVerifyPolicyManager(identityStorage));

              // Initialize the storage.
              var keyName = new Name("/testname/DSK-123");
              var certificateName = keyName.getSubName(0, keyName.size() - 1).append
            ("KEY").append(keyName.get(-1)).append("ID-CERT").append("0");
              identityStorage.addKey(keyName, KeyType.RSA, new Blob(DEFAULT_RSA_PUBLIC_KEY_DER));
              privateKeyStorage.setKeyPairForKeyName
            (keyName, KeyType.RSA, new ByteBuffer(DEFAULT_RSA_PUBLIC_KEY_DER),
             new ByteBuffer(DEFAULT_RSA_PRIVATE_KEY_DER));

              // Make a Face just so that we can sign the interest.
              var face = new Face("localhost");
              face.setCommandSigningInfo(keyChain, certificateName);
              face.makeCommandInterest(freshInterest);

              Interest reDecodedFreshInterest = new Interest();
              reDecodedFreshInterest.wireDecode(freshInterest.wireEncode());
              Console.Out.WriteLine("");
              Console.Out.WriteLine("Re-decoded fresh Interest:");
              dumpInterest(reDecodedFreshInterest);

              VerifyCallbacks callbacks = new VerifyCallbacks("Freshly-signed Interest");
              keyChain.verifyInterest(reDecodedFreshInterest, callbacks, callbacks);
        }
 public Echo(KeyChain keyChain, Name certificateName)
 {
     keyChain_ = keyChain;
     certificateName_ = certificateName;
 }