当前位置: 首页>>代码示例>>C#>>正文


C# Name.append方法代码示例

本文整理汇总了C#中net.named_data.jndn.Name.append方法的典型用法代码示例。如果您正苦于以下问题:C# Name.append方法的具体用法?C# Name.append怎么用?C# Name.append使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net.named_data.jndn.Name的用法示例。


在下文中一共展示了Name.append方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        static void Main(string[] args)
        {
            try {
            var face = new Face
              (new TcpTransport(), new TcpTransport.ConnectionInfo("localhost"));

            var counter = new Counter1();

            Console.Out.WriteLine("Enter a word to echo:");
            var word = Console.In.ReadLine();

            var name = new Name("/testecho");
            name.append(word);
            Console.Out.WriteLine("Express name " + name.toUri());
            face.expressInterest(name, counter, counter);

            // The main event loop.
            while (counter.callbackCount_ < 1) {
              face.processEvents();

              // We need to sleep for a few milliseconds so we don't use 100% of the CPU.
              System.Threading.Thread.Sleep(5);
            }
              } catch (Exception e) {
            Console.Out.WriteLine("exception: " + e.Message);
              }
        }
开发者ID:named-data,项目名称:ndn-dot-net,代码行数:27,代码来源:test-echo-consumer.cs

示例2: testAppend

        public void testAppend()
        {
            // could possibly split this into different tests
            String uri = "/localhost/user/folders/files/%00%0F";
            Name name = new Name(uri);
            Name name2 = new Name("/localhost").append(new Name("/user/folders/"));
            Assert.AssertEquals("Name constructed by appending names has " + name2.size()
                    + " components instead of 3", 3, name2.size());
            Assert.AssertTrue("Name constructed with append has wrong suffix", name2
                    .get(2).getValue().equals(new Blob("folders")));
            name2 = name2.append("files");
            Assert.AssertEquals("Name constructed by appending string has " + name2.size()
                    + " components instead of 4", 4, name2.size());
            name2 = name2.appendSegment(15);
            Assert.AssertTrue(
                    "Name constructed by appending segment has wrong segment value",
                    name2.get(4).getValue()
                            .equals(new Blob(new int[] { 0x00, 0x0F })));

            Assert.AssertTrue(
                    "Name constructed with append is not equal to URI constructed name",
                    name2.equals(name));
            Assert.AssertEquals("Name constructed with append has wrong URI",
                    name.toUri(), name2.toUri());
        }
开发者ID:named-data,项目名称:ndn-dot-net,代码行数:25,代码来源:TestNameMethods.cs

示例3: testOperateAesDecryptionKey

        public void testOperateAesDecryptionKey()
        {
            // Test construction.
            ConsumerDb database = new Sqlite3ConsumerDb(System.IO.Path.GetFullPath(databaseFilePath.Name));

            // Generate key blobs.
            Blob[] encryptionKeyBlob = { null };
            Blob[] decryptionKeyBlob = { null };
            generateAesKeys(encryptionKeyBlob, decryptionKeyBlob);

            Name keyName = new Name(
                    "/alice/health/samples/activity/steps/C-KEY/20150928080000/20150928090000!");
            keyName.append(new Name("FOR/alice/health/read/activity!"));
            database.addKey(keyName, decryptionKeyBlob[0]);
            Blob resultBlob = database.getKey(keyName);

            AssertTrue(decryptionKeyBlob[0].equals(resultBlob));

            database.deleteKey(keyName);
            resultBlob = database.getKey(keyName);

            AssertEquals(0, resultBlob.size());
        }
开发者ID:named-data,项目名称:ndn-dot-net,代码行数:23,代码来源:TestGroupConsumerDb.cs

示例4: encryptData

        /// <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");
        }
开发者ID:named-data,项目名称:ndn-dot-net,代码行数:71,代码来源:Encryptor.cs

示例5: prepareUnsignedIdentityCertificate

        /// <summary>
        /// Prepare an unsigned identity certificate.
        /// </summary>
        ///
        /// <param name="keyName">The key name, e.g., `/{identity_name}/ksk-123456`.</param>
        /// <param name="publicKey">The public key to sign.</param>
        /// <param name="signingIdentity">The signing identity.</param>
        /// <param name="notBefore">See IdentityCertificate.</param>
        /// <param name="notAfter">See IdentityCertificate.</param>
        /// <param name="subjectDescription">on the keyName.</param>
        /// <param name="certPrefix">signingIdentity and the subject identity. If the signingIdentity is a prefix of the subject identity, `KEY` will be inserted after the signingIdentity, otherwise `KEY` is inserted after subject identity (i.e., before `ksk-...`).</param>
        /// <returns>The unsigned IdentityCertificate, or null if the inputs are invalid.</returns>
        public IdentityCertificate prepareUnsignedIdentityCertificate(
				Name keyName, PublicKey publicKey, Name signingIdentity,
				double notBefore, double notAfter, IList subjectDescription,
				Name certPrefix)
        {
            if (keyName.size() < 1)
                return null;

            String tempKeyIdPrefix = keyName.get(-1).toEscapedString();
            if (tempKeyIdPrefix.Length < 4)
                return null;
            String keyIdPrefix = tempKeyIdPrefix.Substring(0,(4)-(0));
            if (!keyIdPrefix.equals("ksk-") && !keyIdPrefix.equals("dsk-"))
                return null;

            IdentityCertificate certificate = new IdentityCertificate();
            Name certName = new Name();

            if (certPrefix == null) {
                // No certificate prefix hint, so infer the prefix.
                if (signingIdentity.match(keyName))
                    certName.append(signingIdentity).append("KEY")
                            .append(keyName.getSubName(signingIdentity.size()))
                            .append("ID-CERT")
                            .appendVersion((long) net.named_data.jndn.util.Common.getNowMilliseconds());
                else
                    certName.append(keyName.getPrefix(-1)).append("KEY")
                            .append(keyName.get(-1)).append("ID-CERT")
                            .appendVersion((long) net.named_data.jndn.util.Common.getNowMilliseconds());
            } else {
                // A cert prefix hint is supplied, so determine the cert name.
                if (certPrefix.match(keyName) && !certPrefix.equals(keyName))
                    certName.append(certPrefix).append("KEY")
                            .append(keyName.getSubName(certPrefix.size()))
                            .append("ID-CERT")
                            .appendVersion((long) net.named_data.jndn.util.Common.getNowMilliseconds());
                else
                    return null;
            }

            certificate.setName(certName);
            certificate.setNotBefore(notBefore);
            certificate.setNotAfter(notAfter);
            certificate.setPublicKeyInfo(publicKey);

            if (subjectDescription == null || (subjectDescription.Count==0))
                certificate
                        .addSubjectDescription(new CertificateSubjectDescription(
                                "2.5.4.41", keyName.getPrefix(-1).toUri()));
            else {
                for (int i = 0; i < subjectDescription.Count; ++i)
                    certificate
                            .addSubjectDescription((CertificateSubjectDescription) subjectDescription[i]);
            }

            try {
                certificate.encode();
            } catch (DerEncodingException ex) {
                throw new SecurityException("DerEncodingException: " + ex);
            } catch (DerDecodingException ex_0) {
                throw new SecurityException("DerDecodingException: " + ex_0);
            }

            return certificate;
        }
开发者ID:named-data,项目名称:ndn-dot-net,代码行数:77,代码来源:IdentityManager.cs

示例6: createIdentityCertificate

        /// <summary>
        /// Create an identity certificate for a public key supplied by the caller.
        /// </summary>
        ///
        /// <param name="certificatePrefix">The name of public key to be signed.</param>
        /// <param name="publicKey">The public key to be signed.</param>
        /// <param name="signerCertificateName">The name of signing certificate.</param>
        /// <param name="notBefore">The notBefore value in the validity field of the generated certificate.</param>
        /// <param name="notAfter">The notAfter vallue in validity field of the generated certificate.</param>
        /// <returns>The generated identity certificate.</returns>
        public IdentityCertificate createIdentityCertificate(
				Name certificatePrefix, PublicKey publicKey,
				Name signerCertificateName, double notBefore, double notAfter)
        {
            IdentityCertificate certificate = new IdentityCertificate();
            Name keyName = getKeyNameFromCertificatePrefix(certificatePrefix);

            Name certificateName = new Name(certificatePrefix);
            certificateName.append("ID-CERT").appendVersion(
                    (long) net.named_data.jndn.util.Common.getNowMilliseconds());

            certificate.setName(certificateName);
            certificate.setNotBefore(notBefore);
            certificate.setNotAfter(notAfter);
            certificate.setPublicKeyInfo(publicKey);
            certificate.addSubjectDescription(new CertificateSubjectDescription(
                    "2.5.4.41", keyName.toUri()));
            try {
                certificate.encode();
            } catch (DerEncodingException ex) {
                throw new SecurityException("DerDecodingException: " + ex);
            } catch (DerDecodingException ex_0) {
                throw new SecurityException("DerEncodingException: " + ex_0);
            }

            Sha256WithRsaSignature sha256Sig = new Sha256WithRsaSignature();

            KeyLocator keyLocator = new KeyLocator();
            keyLocator.setType(net.named_data.jndn.KeyLocatorType.KEYNAME);
            keyLocator.setKeyName(signerCertificateName);

            sha256Sig.setKeyLocator(keyLocator);

            certificate.setSignature(sha256Sig);

            SignedBlob unsignedData = certificate.wireEncode();

            IdentityCertificate signerCertificate;
            try {
                signerCertificate = getCertificate(signerCertificateName);
            } catch (DerDecodingException ex_1) {
                throw new SecurityException("DerDecodingException: " + ex_1);
            }
            Name signerkeyName = signerCertificate.getPublicKeyName();

            Blob sigBits = privateKeyStorage_.sign(unsignedData.signedBuf(),
                    signerkeyName);

            sha256Sig.setSignature(sigBits);

            return certificate;
        }
开发者ID:named-data,项目名称:ndn-dot-net,代码行数:62,代码来源:IdentityManager.cs

示例7: getKeyNameFromCertificatePrefix

        private static Name getKeyNameFromCertificatePrefix(Name certificatePrefix)
        {
            Name result = new Name();

            String keyString = "KEY";
            int i = 0;
            for (; i < certificatePrefix.size(); i++) {
                if (certificatePrefix.get(i).toEscapedString().equals(keyString))
                    break;
            }

            if (i >= certificatePrefix.size())
                throw new SecurityException(
                        "Identity Certificate Prefix does not have a KEY component");

            result.append(certificatePrefix.getSubName(0, i));
            result.append(certificatePrefix.getSubName(i + 1,
                    certificatePrefix.size() - i - 1));

            return result;
        }
开发者ID:named-data,项目名称:ndn-dot-net,代码行数:21,代码来源:IdentityManager.cs

示例8: decryptContent

        /// <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);
                    }
                }
            }
        }
开发者ID:named-data,项目名称:ndn-dot-net,代码行数:55,代码来源:Consumer.cs

示例9: testImplicitSha256Digest

        public void testImplicitSha256Digest()
        {
            Name name = new Name();

            ByteBuffer digest = toBuffer(new int[] { 0x28, 0xba, 0xd4, 0xb5, 0x27,
                    0x5b, 0xd3, 0x92, 0xdb, 0xb6, 0x70, 0xc7, 0x5c, 0xf0, 0xb6,
                    0x6f, 0x13, 0xf7, 0x94, 0x2b, 0x21, 0xe8, 0x0f, 0x55, 0xc0,
                    0xe8, 0x6b, 0x37, 0x47, 0x53, 0xa5, 0x48, 0x00, 0x00 });

            digest.limit(32);
            name.appendImplicitSha256Digest(new Blob(digest, true));
            name.appendImplicitSha256Digest(new Blob(digest, true)
                    .getImmutableArray());
            Assert.AssertEquals(name.get(0), name.get(1));

            digest.limit(34);
            bool gotError = true;
            try {
                name.appendImplicitSha256Digest(new Blob(digest, true));
                gotError = false;
            } catch (Exception ex) {
            }
            if (!gotError)
                Assert.Fail("Expected error in appendImplicitSha256Digest");

            digest.limit(30);
            gotError = true;
            try {
                name.appendImplicitSha256Digest(new Blob(digest, true));
                gotError = false;
            } catch (Exception ex_0) {
            }
            if (!gotError)
                Assert.Fail("Expected error in appendImplicitSha256Digest");

            // Add name.get(2) as a generic component.
            digest.limit(32);
            name.append(new Blob(digest, true));
            Assert.AssertTrue(name.get(0).compare(name.get(2)) < 0);
            Assert.AssertTrue(name.get(0).getValue().equals(name.get(2).getValue()));

            // Add name.get(3) as a generic component whose first byte is greater.
            digest.position(1);
            digest.limit(33);
            name.append(new Blob(digest, true));
            Assert.AssertTrue(name.get(0).compare(name.get(3)) < 0);

            Assert.AssertEquals(
                    "sha256digest="
                            + "28bad4b5275bd392dbb670c75cf0b66f13f7942b21e80f55c0e86b374753a548",
                    name.get(0).toEscapedString());

            Assert.AssertEquals(true, name.get(0).isImplicitSha256Digest());
            Assert.AssertEquals(false, name.get(2).isImplicitSha256Digest());

            gotError = true;
            try {
                new Name("/hello/sha256digest=hmm");
                gotError = false;
            } catch (Exception ex_1) {
            }
            if (!gotError)
                Assert.Fail("Expected error in new Name from URI");

            // Check canonical URI encoding (lower case).
            Name name2 = new Name(
                    "/hello/sha256digest="
                            + "28bad4b5275bd392dbb670c75cf0b66f13f7942b21e80f55c0e86b374753a548");
            Assert.AssertEquals(name.get(0), name2.get(1));

            // Check that it will accept a hex value in upper case too.
            name2 = new Name(
                    "/hello/sha256digest="
                            + "28BAD4B5275BD392DBB670C75CF0B66F13F7942B21E80F55C0E86B374753A548");
            Assert.AssertEquals(name.get(0), name2.get(1));

            // This is not valid sha256digest component. It should be treated as generic.
            name2 = new Name(
                    "/hello/SHA256DIGEST="
                            + "28BAD4B5275BD392DBB670C75CF0B66F13F7942B21E80F55C0E86B374753A548");
            Assert.AssertFalse(name.get(0).equals(name2.get(1)));
            Assert.AssertTrue(name2.get(1).isGeneric());
        }
开发者ID:named-data,项目名称:ndn-dot-net,代码行数:83,代码来源:TestNameMethods.cs

示例10: createDKeyData

        /// <summary>
        /// Create a D-KEY Data packet with an EncryptedContent for the given private
        /// key, encrypted with the certificate 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="keyName"></param>
        /// <param name="privateKeyBlob">A Blob of the encoded private key.</param>
        /// <param name="certificateKey"></param>
        /// <returns>The Data packet.</returns>
        /// <exception cref="System.Security.SecurityException">for an error using the security KeyChain.</exception>
        private Data createDKeyData(String startTimeStamp, String endTimeStamp,
				Name keyName, Blob privateKeyBlob, Blob certificateKey)
        {
            Name name = new Name(namespace_);
            name.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_D_KEY);
            name.append(startTimeStamp).append(endTimeStamp);
            Data data = new Data(name);
            data.getMetaInfo().setFreshnessPeriod(
                    freshnessHours_ * MILLISECONDS_IN_HOUR);
            EncryptParams encryptParams = new EncryptParams(
                    net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep);
            try {
                net.named_data.jndn.encrypt.algo.Encryptor.encryptData(data, privateKeyBlob, keyName,
                        certificateKey, encryptParams);
            } catch (Exception ex) {
                // Consolidate errors such as InvalidKeyException.
                throw new SecurityException(
                        "createDKeyData: Error in encryptData: " + ex.Message);
            }

            keyChain_.sign(data);
            return data;
        }
开发者ID:named-data,项目名称:ndn-dot-net,代码行数:35,代码来源:GroupManager.cs

示例11: encryptContentKey

        /// <summary>
        /// Get the content key from the database_ and encrypt it for the timeSlot
        /// using encryptionKey.
        /// </summary>
        ///
        /// <param name="encryptionKey">The encryption key value.</param>
        /// <param name="eKeyName">The key name for the EncryptedContent.</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>
        /// <returns>True if encryption succeeds, otherwise false.</returns>
        private bool encryptContentKey(Blob encryptionKey, Name eKeyName,
				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 keyName = new Name(namespace_);
            keyName.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_C_KEY);
            keyName.append(net.named_data.jndn.encrypt.Schedule.toIsoString(getRoundedTimeSlot(timeSlot_0)));

            Blob contentKey = database_.getContentKey(timeSlot_0);

            Data cKeyData = new Data();
            cKeyData.setName(keyName);
            EncryptParams paras = new EncryptParams(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep);
            try {
                net.named_data.jndn.encrypt.algo.Encryptor.encryptData(cKeyData, contentKey, eKeyName,
                        encryptionKey, paras);
            } catch (Exception ex) {
                try {
                    onError_2.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.EncryptionFailure, ex.Message);
                } catch (Exception exception) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception);
                }
                return false;
            }

            keyChain_.sign(cKeyData);
            ILOG.J2CsMapping.Collections.Collections.Add(keyRequest.encryptedKeys,cKeyData);
            updateKeyRequest(keyRequest, timeCount, onEncryptedKeys_1);
            return true;
        }
开发者ID:named-data,项目名称:ndn-dot-net,代码行数:42,代码来源:Producer.cs

示例12: construct

        private void construct(Name prefix, Name dataType)
        {
            Name fixedPrefix = new Name(prefix);
            Name fixedDataType = new Name(dataType);

            // Fill ekeyInfo_ with all permutations of dataType, including the 'E-KEY'
            // component of the name. This will be used in createContentKey to send
            // interests without reconstructing names every time.
            fixedPrefix.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_READ);
            while (fixedDataType.size() > 0) {
                Name nodeName = new Name(fixedPrefix);
                nodeName.append(fixedDataType);
                nodeName.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_E_KEY);

                ILOG.J2CsMapping.Collections.Collections.Put(eKeyInfo_,nodeName,new Producer.KeyInfo ());
                fixedDataType = fixedDataType.getPrefix(-1);
            }
            fixedPrefix.append(dataType);
            namespace_ = new Name(prefix);
            namespace_.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_SAMPLE);
            namespace_.append(dataType);
        }
开发者ID:named-data,项目名称:ndn-dot-net,代码行数:22,代码来源:Producer.cs

示例13: produce

        /// <summary>
        /// Encrypt the given content with the content key that covers timeSlot, and
        /// update the data packet with the encrypted content and an appropriate data
        /// name.
        /// </summary>
        ///
        /// <param name="data">An empty Data object which is updated.</param>
        /// <param name="timeSlot_0">The time slot as milliseconds since Jan 1, 1970 UTC.</param>
        /// <param name="content">The content to encrypt.</param>
        /// <param name="onError_1">better error handling the callback should catch and properly handle any exceptions.</param>
        public void produce(Data data, double timeSlot_0, Blob content,
				net.named_data.jndn.encrypt.EncryptError.OnError  onError_1)
        {
            // Get a content key.
            Name contentKeyName = createContentKey(timeSlot_0, null, onError_1);
            Blob contentKey = database_.getContentKey(timeSlot_0);

            // Produce data.
            Name dataName = new Name(namespace_);
            dataName.append(net.named_data.jndn.encrypt.Schedule.toIsoString(timeSlot_0));

            data.setName(dataName);
            EncryptParams paras = new EncryptParams(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc,
                    16);
            net.named_data.jndn.encrypt.algo.Encryptor
                    .encryptData(data, content, contentKeyName, contentKey, paras);
            keyChain_.sign(data);
        }
开发者ID:named-data,项目名称:ndn-dot-net,代码行数:28,代码来源:Producer.cs

示例14: createContentKey

        /// <summary>
        /// Create the content key corresponding to the timeSlot. This first checks if
        /// the content key exists. For an existing content key, this returns the
        /// content key name directly. If the key does not exist, this creates one and
        /// encrypts it using the corresponding E-KEYs. The encrypted content keys are
        /// passed to the onEncryptedKeys callback.
        /// </summary>
        ///
        /// <param name="timeSlot_0">The time slot as milliseconds since Jan 1, 1970 UTC.</param>
        /// <param name="onEncryptedKeys_1">content key Data packets. If onEncryptedKeys is null, this does not use it. 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_2">better error handling the callback should catch and properly handle any exceptions.</param>
        /// <returns>The content key name.</returns>
        public Name createContentKey(double timeSlot_0,
				Producer.OnEncryptedKeys  onEncryptedKeys_1, net.named_data.jndn.encrypt.EncryptError.OnError  onError_2)
        {
            double hourSlot = getRoundedTimeSlot(timeSlot_0);

            // Create the content key name.
            Name contentKeyName = new Name(namespace_);
            contentKeyName.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_C_KEY);
            contentKeyName.append(net.named_data.jndn.encrypt.Schedule.toIsoString(hourSlot));

            Blob contentKeyBits;

            // Check if we have created the content key before.
            if (database_.hasContentKey(timeSlot_0))
                // We have created the content key. Return its name directly.
                return contentKeyName;

            // We haven't created the content key. Create one and add it into the database.
            AesKeyParams aesParams = new AesKeyParams(128);
            contentKeyBits = net.named_data.jndn.encrypt.algo.AesAlgorithm.generateKey(aesParams).getKeyBits();
            database_.addContentKey(timeSlot_0, contentKeyBits);

            // Now we need to retrieve the E-KEYs for content key encryption.
            double timeCount = Math.Round(timeSlot_0,MidpointRounding.AwayFromZero);
            ILOG.J2CsMapping.Collections.Collections.Put(keyRequests_,timeCount,new Producer.KeyRequest (eKeyInfo_.Count));
            Producer.KeyRequest  keyRequest = (Producer.KeyRequest ) ILOG.J2CsMapping.Collections.Collections.Get(keyRequests_,timeCount);

            // Check if the current E-KEYs can cover the content key.
            Exclude timeRange = new Exclude();
            excludeAfter(timeRange,
                    new Name.Component(net.named_data.jndn.encrypt.Schedule.toIsoString(timeSlot_0)));
            new ILOG.J2CsMapping.Collections.IteratorAdapter(eKeyInfo_.GetEnumerator());
            for (IIterator i = new ILOG.J2CsMapping.Collections.IteratorAdapter(eKeyInfo_.GetEnumerator()); i.HasNext();) {
                // For each current E-KEY.
                DictionaryEntry entry = (DictionaryEntry) i.Next();
                Producer.KeyInfo  keyInfo = (Producer.KeyInfo ) ((DictionaryEntry) entry).Value;
                if (timeSlot_0 < keyInfo.beginTimeSlot
                        || timeSlot_0 >= keyInfo.endTimeSlot) {
                    // The current E-KEY cannot cover the content key, so retrieve one.
                    ILOG.J2CsMapping.Collections.Collections.Put(keyRequest.repeatAttempts,((DictionaryEntry) entry).Key,0);
                    sendKeyInterest(
                            new Interest((Name) ((DictionaryEntry) entry).Key).setExclude(
                                    timeRange).setChildSelector(1), timeSlot_0,
                            onEncryptedKeys_1, onError_2);
                } else {
                    // The current E-KEY can cover the content key.
                    // Encrypt the content key directly.
                    Name eKeyName = new Name((Name) ((DictionaryEntry) entry).Key);
                    eKeyName.append(net.named_data.jndn.encrypt.Schedule.toIsoString(keyInfo.beginTimeSlot));
                    eKeyName.append(net.named_data.jndn.encrypt.Schedule.toIsoString(keyInfo.endTimeSlot));
                    encryptContentKey(keyInfo.keyBits, eKeyName, timeSlot_0,
                            onEncryptedKeys_1, onError_2);
                }
            }

            return contentKeyName;
        }
开发者ID:named-data,项目名称:ndn-dot-net,代码行数:69,代码来源:Producer.cs

示例15: testRegisterPrefixResponse

        public void testRegisterPrefixResponse()
        {
            Name prefixName = new Name("/test");

            int[] interestCallbackCount_0 = new int[] { 0 };
            int[] failedCallbackCount_1 = new int[] { 0 };
            faceIn.registerPrefix(prefixName, new TestFaceCallRegisterMethods.Anonymous_C3 (this, interestCallbackCount_0), new TestFaceCallRegisterMethods.Anonymous_C2 (failedCallbackCount_1));

            // Give the "server" time to register the interest.
            double timeout = 1000;
            double startTime = getNowMilliseconds();
            while (getNowMilliseconds() - startTime < timeout) {
                try {
                    faceIn.processEvents();
                } catch (IOException ex) {
                    logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex);
                    break;
                } catch (EncodingException ex_2) {
                    logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex_2);
                    break;
                }

                try {
                    // We need to sleep for a few milliseconds so we don't use 100% of the CPU.
                    ILOG.J2CsMapping.Threading.ThreadWrapper.sleep(10);
                } catch (ThreadInterruptedException ex_3) {
                    logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex_3);
                    break;
                }
            }

            // Now express an interest on this new face, and see if onInterest is called.
            // Add the timestamp so it is unique and we don't get a cached response.
            int[] dataCallbackCount_4 = new int[] { 0 };
            int[] timeoutCallbackCount_5 = new int[] { 0 };
            Data[] receivedData_6 = new Data[1];
            Name interestName = prefixName.append("hello" + getNowMilliseconds());
            faceOut.expressInterest(interestName, new TestFaceCallRegisterMethods.Anonymous_C1 (receivedData_6, dataCallbackCount_4), new TestFaceCallRegisterMethods.Anonymous_C0 (timeoutCallbackCount_5));

            // Process events for the in and out faces.
            timeout = 10000;
            startTime = getNowMilliseconds();
            while (getNowMilliseconds() - startTime < timeout) {
                try {
                    faceIn.processEvents();
                    faceOut.processEvents();
                } catch (IOException ex_7) {
                    logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex_7);
                    break;
                } catch (EncodingException ex_8) {
                    logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex_8);
                    break;
                }

                bool done = true;
                if (interestCallbackCount_0[0] == 0 && failedCallbackCount_1[0] == 0)
                    // Still processing faceIn.
                    done = false;
                if (dataCallbackCount_4[0] == 0 && timeoutCallbackCount_5[0] == 0)
                    // Still processing face_out.
                    done = false;

                if (done)
                    break;

                try {
                    // We need to sleep for a few milliseconds so we don't use 100% of the CPU.
                    ILOG.J2CsMapping.Threading.ThreadWrapper.sleep(10);
                } catch (ThreadInterruptedException ex_9) {
                    logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex_9);
                    break;
                }
            }

            AssertEquals("Failed to register prefix at all", 0,
                    failedCallbackCount_1[0]);
            AssertEquals("Expected 1 onInterest callback", 1,
                    interestCallbackCount_0[0]);
            AssertEquals("Expected 1 onData callback", 1, dataCallbackCount_4[0]);

            // Check the message content.
            Blob expectedBlob = new Blob("SUCCESS");
            AssertTrue(
                    "Data received on the face does not match the expected format",
                    expectedBlob.equals(receivedData_6[0].getContent()));
        }
开发者ID:named-data,项目名称:ndn-dot-net,代码行数:86,代码来源:TestFaceCallRegisterMethods.cs


注:本文中的net.named_data.jndn.Name.append方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。