Beispiel #1
0
        /// <summary>
        /// Get the certificate with name certificateName.
        /// </summary>
        ///
        /// <param name="certificateName">The name of the certificate.</param>
        /// <returns>A copy of the certificate.</returns>
        /// <exception cref="Pib.Error">if the certificate does not exist.</exception>
        /// <exception cref="PibImpl.Error">for a non-semantic (database access) error.</exception>
        public override CertificateV2 getCertificate(Name certificateName)
        {
            try {
                PreparedStatement statement = database_
                                              .prepareStatement("SELECT certificate_data FROM certificates WHERE certificate_name=?");
                statement.setBytes(1, certificateName.wireEncode()
                                   .getImmutableArray());

                try {
                    SqlDataReader result = statement.executeQuery();

                    if (result.NextResult())
                    {
                        CertificateV2 certificate = new CertificateV2();
                        try {
                            certificate.wireDecode(new Blob(result.getBytes(1)));
                        } catch (EncodingException ex) {
                            throw new PibImpl.Error(
                                      "PibSqlite3: Error decoding certificate: " + ex);
                        }
                        return(certificate);
                    }
                    else
                    {
                        throw new Pib.Error("Certificate `"
                                            + certificateName.toUri() + "` does not exit");
                    }
                } finally {
                    statement.close();
                }
            } catch (SQLException exception) {
                throw new PibImpl.Error("PibSqlite3: SQLite error: " + exception);
            }
        }
Beispiel #2
0
        public void testEmptyContent()
        {
            Data data = new Data(certificateBase_);

            data.setContent(new Blob());
            data.setSignature(generateFakeSignature());

            try {
                new CertificateV2(data);
                Assert.Fail("The CertificateV2 constructor did not throw an exception");
            } catch (CertificateV2.Error ex) {
            } catch (Exception ex_0) {
                Assert.Fail("The CertificateV2 constructor did not throw an exception");
            }

            CertificateV2 certificate = new CertificateV2(certificateBase_);

            certificate.setContent(new Blob());
            certificate.setSignature(generateFakeSignature());
            try {
                certificate.getPublicKey();
                Assert.Fail("getPublicKey did not throw an exception");
            } catch (CertificateV2.Error ex_1) {
            } catch (Exception ex_2) {
                Assert.Fail("getPublicKey did not throw an exception");
            }
        }
Beispiel #3
0
        /// <summary>
        /// Get the default certificate for the key with eyName.
        /// </summary>
        ///
        /// <param name="keyName">The name of the key.</param>
        /// <returns>A copy of the default certificate.</returns>
        /// <exception cref="Pib.Error">if the default certificate does not exist.</exception>
        /// <exception cref="PibImpl.Error">for a non-semantic (database access) error.</exception>
        public override CertificateV2 getDefaultCertificateOfKey(Name keyName)
        {
            try {
                PreparedStatement statement = database_
                                              .prepareStatement("SELECT certificate_data "
                                                                + net.named_data.jndn.security.pib.PibSqlite3Base.FROM_WHERE_getDefaultCertificateOfKey);
                statement.setBytes(1, keyName.wireEncode().getImmutableArray());

                try {
                    SqlDataReader result = statement.executeQuery();

                    if (result.NextResult())
                    {
                        CertificateV2 certificate = new CertificateV2();
                        try {
                            certificate.wireDecode(new Blob(result.getBytes(1)));
                        } catch (EncodingException ex) {
                            throw new PibImpl.Error(
                                      "PibSqlite3: Error decoding certificate: " + ex);
                        }
                        return(certificate);
                    }
                    else
                    {
                        throw new Pib.Error("No default certificate for key `"
                                            + keyName.toUri() + "`");
                    }
                } finally {
                    statement.close();
                }
            } catch (SQLException exception) {
                throw new PibImpl.Error("PibSqlite3: SQLite error: " + exception);
            }
        }
        /// <summary>
        /// Add a self-signed certificate made from the key and issuer ID.
        /// </summary>
        ///
        /// <param name="key">The key for the certificate.</param>
        /// <param name="issuerId">The issuer ID name component for the certificate name.</param>
        /// <returns>The new certificate.</returns>
        internal CertificateV2 addCertificate(PibKey key, String issuerId)
        {
            Name certificateName = new Name(key.getName());

            certificateName.append(issuerId).appendVersion(3);
            CertificateV2 certificate = new CertificateV2();

            certificate.setName(certificateName);

            // Set the MetaInfo.
            certificate.getMetaInfo().setType(net.named_data.jndn.ContentType.KEY);
            // One hour.
            certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0);

            // Set the content.
            certificate.setContent(key.getPublicKey());

            SigningInfo paras = new SigningInfo(key);
            // Validity period of 10 days.
            double now = net.named_data.jndn.util.Common.getNowMilliseconds();

            paras.setValidityPeriod(new ValidityPeriod(now, now + 10 * 24 * 3600
                                                       * 1000.0d));

            keyChain_.sign(certificate, paras);
            return(certificate);
        }
Beispiel #5
0
        public void testSetters()
        {
            CertificateV2 certificate = new CertificateV2();

            certificate.setName(new Name(
                                    "/ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B"));
            certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0d);
            certificate.setContent(new Blob(PUBLIC_KEY, false));
            certificate.setSignature(generateFakeSignature());

            Assert.AssertEquals(new Name(
                                    "/ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B"),
                                certificate.getName());
            Assert.AssertEquals(new Name("/ndn/site1/KEY/ksk-1416425377094"),
                                certificate.getKeyName());
            Assert.AssertEquals(new Name("/ndn/site1"), certificate.getIdentity());
            Assert.AssertEquals(new Name.Component("0123"), certificate.getIssuerId());
            Assert.AssertEquals(new Name.Component("ksk-1416425377094"),
                                certificate.getKeyId());
            Assert.AssertEquals(new Name("/ndn/site1/KEY/ksk-2516425377094"), net.named_data.jndn.KeyLocator
                                .getFromSignature(certificate.getSignature()).getKeyName());
            Assert.AssertEquals(net.named_data.jndn.tests.unit_tests.UnitTestsCommon.fromIsoString("20141111T050000"), certificate
                                .getValidityPeriod().getNotBefore(), 0);
            Assert.AssertEquals(net.named_data.jndn.tests.unit_tests.UnitTestsCommon.fromIsoString("20141111T060000"), certificate
                                .getValidityPeriod().getNotAfter(), 0);

            try {
                certificate.getPublicKey();
            } catch (Exception ex) {
                Assert.Fail(ex.Message);
            }
        }
 /// <summary>
 /// Save the identity's certificate to a file.
 /// </summary>
 ///
 /// <param name="identity">The PibIdentity.</param>
 /// <param name="filePath">The file path, which should be writable.</param>
 /// <returns>True if successful.</returns>
 public bool saveCertificate(PibIdentity identity, String filePath)
 {
     try {
         CertificateV2 certificate = identity.getDefaultKey()
                                     .getDefaultCertificate();
         return(saveCertificateToFile(certificate, filePath));
     } catch (Pib.Error ex) {
         return(false);
     }
 }
 /// <summary>
 /// Verify the Interest packet using the public key in the certificate, where
 /// the last two name components are the SignatureInfo and signature bytes.
 /// This does not check the type of public key or digest algorithm against the
 /// type of SignatureInfo such as Sha256WithRsaSignature.
 /// </summary>
 ///
 /// <param name="interest">The Interest packet to verify.</param>
 /// <param name="certificate">The certificate containing the public key.</param>
 /// <param name="digestAlgorithm">(optional) The digest algorithm. If omitted, use SHA256.</param>
 /// <param name="wireFormat"></param>
 /// <returns>True if verification succeeds, false if verification fails or
 /// cannot decode the Interest or public key.</returns>
 /// <exception cref="System.ArgumentException">for an invalid public key type ordigestAlgorithm.</exception>
 public static bool verifyInterestSignature(Interest interest,
                                            CertificateV2 certificate, DigestAlgorithm digestAlgorithm,
                                            WireFormat wireFormat)
 {
     try {
         return(verifyInterestSignature(interest,
                                        certificate.getPublicKey(), digestAlgorithm, wireFormat));
     } catch (CertificateV2.Error ex) {
         return(false);
     }
 }
 /// <summary>
 /// Verify the Data packet using the public key in the certificate. This does
 /// not check the type of public key or digest algorithm against the type of
 /// SignatureInfo in the Data packet such as Sha256WithRsaSignature.
 /// </summary>
 ///
 /// <param name="data">The Data packet to verify.</param>
 /// <param name="certificate">The certificate containing the public key.</param>
 /// <param name="digestAlgorithm">The digest algorithm.</param>
 /// <param name="wireFormat">A WireFormat object used to encode the Data packet.</param>
 /// <returns>True if verification succeeds, false if verification fails or for
 /// an error decoding the public key.</returns>
 /// <exception cref="System.ArgumentException">for an invalid public key type ordigestAlgorithm.</exception>
 public static bool verifyDataSignature(Data data,
                                        CertificateV2 certificate, DigestAlgorithm digestAlgorithm,
                                        WireFormat wireFormat)
 {
     try {
         return(verifyDataSignature(data, certificate.getPublicKey(),
                                    digestAlgorithm, wireFormat));
     } catch (CertificateV2.Error ex) {
         return(false);
     }
 }
Beispiel #9
0
        public void testOverwrite()
        {
            /* foreach */
            foreach (PibDataFixture2 fixture  in  pibImpls)
            {
                PibImpl pib = fixture.pib;

                // Check for id1Key1, which should not exist.
                pib.removeIdentity(fixture.id1);
                Assert.AssertEquals(false, pib.hasKey(fixture.id1Key1Name));

                // Add id1Key1.
                pib.addKey(fixture.id1, fixture.id1Key1Name, fixture.id1Key1.buf());
                Assert.AssertEquals(true, pib.hasKey(fixture.id1Key1Name));
                Blob keyBits = pib.getKeyBits(fixture.id1Key1Name);
                Assert.AssertTrue(keyBits.equals(fixture.id1Key1));

                // To check overwrite, add a key with the same name.
                pib.addKey(fixture.id1, fixture.id1Key1Name, fixture.id1Key2.buf());
                Blob keyBits2 = pib.getKeyBits(fixture.id1Key1Name);
                Assert.AssertTrue(keyBits2.equals(fixture.id1Key2));

                // Check for id1Key1Cert1, which should not exist.
                pib.removeIdentity(fixture.id1);
                Assert.AssertEquals(false,
                                    pib.hasCertificate(fixture.id1Key1Cert1.getName()));

                // Add id1Key1Cert1.
                pib.addKey(fixture.id1, fixture.id1Key1Name, fixture.id1Key1.buf());
                pib.addCertificate(fixture.id1Key1Cert1);
                Assert.AssertEquals(true,
                                    pib.hasCertificate(fixture.id1Key1Cert1.getName()));

                CertificateV2 cert = pib.getCertificate(fixture.id1Key1Cert1
                                                        .getName());
                Assert.AssertTrue(cert.wireEncode().equals(
                                      fixture.id1Key1Cert1.wireEncode()));

                // Create a fake certificate with the same name.
                CertificateV2 cert2 = fixture.id1Key2Cert1;
                cert2.setName(fixture.id1Key1Cert1.getName());
                cert2.setSignature(fixture.id1Key2Cert1.getSignature());
                pib.addCertificate(cert2);

                CertificateV2 cert3 = pib.getCertificate(fixture.id1Key1Cert1
                                                         .getName());
                Assert.AssertTrue(cert3.wireEncode().equals(cert2.wireEncode()));

                // Check that both the key and certificate are overwritten.
                Blob keyBits3 = pib.getKeyBits(fixture.id1Key1Name);
                Assert.AssertTrue(keyBits3.equals(fixture.id1Key2));
            }
        }
Beispiel #10
0
        /// <summary>
        /// Authorize a member identified by memberCertificate to decrypt data under
        /// the policy.
        /// </summary>
        ///
        /// <param name="memberCertificate"></param>
        /// <returns>The published KDK Data packet.</returns>
        public Data addMember(CertificateV2 memberCertificate)
        {
            Name kdkName = new Name(nacKey_.getIdentityName());

            kdkName.append(net.named_data.jndn.encrypt.EncryptorV2.NAME_COMPONENT_KDK)
            .append(nacKey_.getName().get(-1))
            // key-id
            .append(net.named_data.jndn.encrypt.EncryptorV2.NAME_COMPONENT_ENCRYPTED_BY)
            .append(memberCertificate.getKeyName());

            int secretLength = 32;

            byte[] secret = new byte[secretLength];
            net.named_data.jndn.util.Common.getRandom().nextBytes(secret);
            // To be compatible with OpenSSL which uses a null-terminated string,
            // replace each 0 with 1. And to be compatible with the Java security
            // library which interprets the secret as a char array converted to UTF8,
            // limit each byte to the ASCII range 1 to 127.
            for (int i = 0; i < secretLength; ++i)
            {
                if (secret[i] == 0)
                {
                    secret[i] = 1;
                }

                secret[i] &= 0x7f;
            }

            SafeBag kdkSafeBag = keyChain_.exportSafeBag(
                nacKey_.getDefaultCertificate(), ILOG.J2CsMapping.NIO.ByteBuffer.wrap(secret));

            PublicKey memberKey = new PublicKey(memberCertificate.getPublicKey());

            EncryptedContent encryptedContent = new EncryptedContent();

            encryptedContent.setPayload(kdkSafeBag.wireEncode());
            encryptedContent.setPayloadKey(memberKey.encrypt(secret,
                                                             net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep));

            Data kdkData = new Data(kdkName);

            kdkData.setContent(encryptedContent.wireEncodeV2());
            // FreshnessPeriod can serve as a soft access control for revoking access.
            kdkData.getMetaInfo().setFreshnessPeriod(
                DEFAULT_KDK_FRESHNESS_PERIOD_MS);
            keyChain_.sign(kdkData, new SigningInfo(identity_));

            storage_.insert(kdkData);

            return(kdkData);
        }
Beispiel #11
0
        public void setUp()
        {
            CertificateV2 certificateBase = new CertificateV2();

            certificateBase.wireDecode(new Blob(CERT, false));
            // Check no throw.
            CertificateV2 temp1 = new CertificateV2(certificateBase);

            certificateBase_ = new Data(certificateBase);
            certificateBase_.setSignature(generateFakeSignature());

            // Check no throw.
            CertificateV2 temp2 = new CertificateV2(certificateBase_);
        }
            public void processInterest(Interest interest, OnData onData,
                                        OnTimeout onTimeout, OnNetworkNack onNetworkNack)
            {
                CertificateV2 certificate = outer_ValidatorFixture.cache_.find(interest);

                if (certificate != null)
                {
                    onData.onData(interest, certificate);
                }
                else
                {
                    onTimeout.onTimeout(interest);
                }
            }
        /// <summary>
        /// Add certificate into the container. If the certificate already exists,
        /// this replaces it.
        /// </summary>
        ///
        /// <param name="certificate">The certificate to add. This copies the object.</param>
        /// <exception cref="System.ArgumentException">if the name of the certificate does notmatch the key name.</exception>
        public void add(CertificateV2 certificate)
        {
            if (!keyName_.equals(certificate.getKeyName()))
            {
                throw new ArgumentException("The certificate name `"
                                            + certificate.getKeyName().toUri()
                                            + "` does not match the key name");
            }

            Name certificateName = new Name(certificate.getName());

            ILOG.J2CsMapping.Collections.Collections.Add(certificateNames_, certificateName);
            // Copy the certificate.
            ILOG.J2CsMapping.Collections.Collections.Put(certificates_, certificateName, new CertificateV2(certificate));
            pibImpl_.addCertificate(certificate);
        }
Beispiel #14
0
        public void testSelfSignedCertValidity()
        {
            CertificateV2 certificate = fixture_
                                        .addIdentity(
                new Name(
                    "/Security/V2/TestKeyChain/SelfSignedCertValidity"))
                                        .getDefaultKey().getDefaultCertificate();

            Assert.AssertTrue(certificate.isValid());
            // Check 10 years from now.
            Assert.AssertTrue(certificate.isValid(net.named_data.jndn.util.Common.getNowMilliseconds() + 10 * 365
                                                  * 24 * 3600 * 1000.0d));
            // Check that notAfter is later than 10 years from now.
            Assert.AssertTrue(certificate.getValidityPeriod().getNotAfter() > net.named_data.jndn.util.Common
                              .getNowMilliseconds() + 10 * 365 * 24 * 3600 * 1000.0d);
        }
Beispiel #15
0
        public void testOverwrite()
        {
            PibMemory pibImpl = new PibMemory();

            try {
                new PibKeyImpl(fixture.id1Key1Name, pibImpl);
                Assert.Fail("Did not throw the expected exception");
            } catch (Pib.Error ex) {
            } catch (Exception ex_0) {
                Assert.Fail("Did not throw the expected exception");
            }

            new PibKeyImpl(fixture.id1Key1Name, fixture.id1Key1.buf(), pibImpl);
            PibKeyImpl key1 = new PibKeyImpl(fixture.id1Key1Name, pibImpl);

            // Overwriting the key should work.
            new PibKeyImpl(fixture.id1Key1Name, fixture.id1Key2.buf(), pibImpl);
            PibKeyImpl key2 = new PibKeyImpl(fixture.id1Key1Name, pibImpl);

            // key1 should have cached the original public key.
            Assert.AssertTrue(!key1.getPublicKey().equals(key2.getPublicKey()));
            Assert.AssertTrue(key2.getPublicKey().equals(fixture.id1Key2));

            key1.addCertificate(fixture.id1Key1Cert1);
            // Use the wire encoding to check equivalence.
            Assert.AssertTrue(key1.getCertificate(fixture.id1Key1Cert1.getName())
                              .wireEncode().equals(fixture.id1Key1Cert1.wireEncode()));

            CertificateV2 otherCert = new CertificateV2(fixture.id1Key1Cert1);

            ((Sha256WithRsaSignature)otherCert.getSignature()).getValidityPeriod()
            .setPeriod(net.named_data.jndn.util.Common.getNowMilliseconds(),
                       net.named_data.jndn.util.Common.getNowMilliseconds() + 1000);
            // Don't bother resigning so we don't have to load a private key.

            Assert.AssertTrue(fixture.id1Key1Cert1.getName().equals(otherCert.getName()));
            Assert.AssertTrue(otherCert.getContent().equals(
                                  fixture.id1Key1Cert1.getContent()));
            Assert.AssertFalse(otherCert.wireEncode().equals(
                                   fixture.id1Key1Cert1.wireEncode()));

            key1.addCertificate(otherCert);

            Assert.AssertTrue(key1.getCertificate(fixture.id1Key1Cert1.getName())
                              .wireEncode().equals(otherCert.wireEncode()));
        }
Beispiel #16
0
        public void testValidityPeriodChecking()
        {
            CertificateV2 certificate = new CertificateV2();

            certificate.setName(new Name(
                                    "/ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B"));
            certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0d);
            certificate.setContent(new Blob(PUBLIC_KEY, false));
            certificate.setSignature(generateFakeSignature());

            Assert.AssertEquals(true,
                                certificate.isValid(net.named_data.jndn.tests.unit_tests.UnitTestsCommon.fromIsoString("20141111T050000")));
            Assert.AssertEquals(true,
                                certificate.isValid(net.named_data.jndn.tests.unit_tests.UnitTestsCommon.fromIsoString("20141111T060000")));
            Assert.AssertEquals(false,
                                certificate.isValid(net.named_data.jndn.tests.unit_tests.UnitTestsCommon.fromIsoString("20141111T045959")));
            Assert.AssertEquals(false,
                                certificate.isValid(net.named_data.jndn.tests.unit_tests.UnitTestsCommon.fromIsoString("20141111T060001")));
        }
        public void testFindByInterest()
        {
            anchorContainer.insert("group1", certificatePath1.FullName,
                                   400.0d);
            Interest interest = new Interest(identity1.getName());

            Assert.AssertTrue(anchorContainer.find(interest) != null);
            Interest interest1 = new Interest(identity1.getName().getPrefix(-1));

            Assert.AssertTrue(anchorContainer.find(interest1) != null);
            Interest interest2 = new Interest(
                new Name(identity1.getName()).appendVersion(1));

            Assert.AssertTrue(anchorContainer.find(interest2) == null);

            CertificateV2 certificate3 = fixture.addCertificate(
                identity1.getDefaultKey(), "3");
            CertificateV2 certificate4 = fixture.addCertificate(
                identity1.getDefaultKey(), "4");
            CertificateV2 certificate5 = fixture.addCertificate(
                identity1.getDefaultKey(), "5");

            CertificateV2 certificate3Copy = new CertificateV2(certificate3);

            anchorContainer.insert("group2", certificate3Copy);
            anchorContainer.insert("group3", certificate4);
            anchorContainer.insert("group4", certificate5);

            Interest      interest3        = new Interest(certificate3.getKeyName());
            CertificateV2 foundCertificate = anchorContainer.find(interest3);

            Assert.AssertTrue(foundCertificate != null);
            Assert.AssertTrue(interest3.getName().isPrefixOf(foundCertificate.getName()));
            Assert.AssertTrue(certificate3.getName().equals(foundCertificate.getName()));

            interest3.getExclude().appendComponent(
                certificate3.getName().get(net.named_data.jndn.security.v2.CertificateV2.ISSUER_ID_OFFSET));
            foundCertificate = anchorContainer.find(interest3);
            Assert.AssertTrue(foundCertificate != null);
            Assert.AssertTrue(interest3.getName().isPrefixOf(foundCertificate.getName()));
            Assert.AssertTrue(!foundCertificate.getName().equals(certificate3.getName()));
        }
Beispiel #18
0
        internal void makeCertificate(PibKey key, PibKey signer)
        {
            // Copy the default certificate.
            CertificateV2 request = new CertificateV2(key.getDefaultCertificate());

            request.setName(new Name(key.getName()).append("looper").appendVersion(
                                1));

            // Set SigningInfo.
            SigningInfo             // Set SigningInfo.
                paras = new SigningInfo(signer);
            // Validity period from 100 days before to 100 days after now.
            double now = net.named_data.jndn.util.Common.getNowMilliseconds();

            paras.setValidityPeriod(new ValidityPeriod(now - 100 * 24 * 3600
                                                       * 1000.0d, now + 100 * 24 * 3600 * 1000.0d));
            fixture_.keyChain_.sign(request, paras);
            fixture_.keyChain_.addCertificate(key, request);

            fixture_.cache_.insert(request);
        }
Beispiel #19
0
        /// <summary>
        /// Add the certificate. If a certificate with the same name (without implicit
        /// digest) already exists, then overwrite the certificate. If the key or
        /// identity does not exist, they will be created. If no default certificate
        /// for the key has been set, then set the added certificate as the default for
        /// the key. If no default key was set for the identity, it will be set as the
        /// default key for the identity. If no default identity was selected, the
        /// certificate's identity becomes the default.
        /// </summary>
        ///
        /// <param name="certificate">The certificate to add. This copies the object.</param>
        public override void addCertificate(CertificateV2 certificate)
        {
            Name certificateNameCopy = new Name(certificate.getName());
            // getKeyName already makes a new Name.
            Name keyNameCopy = certificate.getKeyName();
            Name identity    = certificate.getIdentity();

            addKey(identity, keyNameCopy, certificate.getContent().buf());

            try {
                ILOG.J2CsMapping.Collections.Collections.Put(certificates_, certificateNameCopy, new CertificateV2(
                                                                 certificate));
            } catch (CertificateV2.Error ex) {
                // We don't expect an error in the copy constructor.
                throw new PibImpl.Error(ex.Message);
            }
            if (!defaultCertificateNames_.Contains(keyNameCopy))
            {
                ILOG.J2CsMapping.Collections.Collections.Put(defaultCertificateNames_, keyNameCopy, certificateNameCopy);
            }
        }
        /// <summary>
        /// Get the certificate with certificateName from the container.
        /// </summary>
        ///
        /// <param name="certificateName">The name of the certificate.</param>
        /// <returns>A copy of the certificate.</returns>
        /// <exception cref="System.ArgumentException">if certificateName does not match the keyname</exception>
        /// <exception cref="Pib.Error">if the certificate does not exist.</exception>
        public CertificateV2 get(Name certificateName)
        {
            CertificateV2 cachedCertificate = ILOG.J2CsMapping.Collections.Collections.Get(certificates_, certificateName);

            if (cachedCertificate != null)
            {
                try {
                    // Make a copy.
                    // TODO: Copy is expensive. Can we just tell the caller not to modify it?
                    return(new CertificateV2(cachedCertificate));
                } catch (CertificateV2.Error ex) {
                    // We don't expect this for the copy constructor.
                    throw new Pib.Error("Error copying certificate: " + ex);
                }
            }

            // Get from the PIB and cache.
            if (!net.named_data.jndn.security.v2.CertificateV2.isValidName(certificateName) ||
                !net.named_data.jndn.security.v2.CertificateV2.extractKeyNameFromCertName(certificateName)
                .equals(keyName_))
            {
                throw new ArgumentException("Certificate name `"
                                            + certificateName.toUri()
                                            + "` is invalid or does not match key name");
            }

            CertificateV2 certificate = pibImpl_.getCertificate(certificateName);

            // Copy the certificate Name.
            ILOG.J2CsMapping.Collections.Collections.Put(certificates_, new Name(certificateName), certificate);
            try {
                // Make a copy.
                // TODO: Copy is expensive. Can we just tell the caller not to modify it?
                return(new CertificateV2(certificate));
            } catch (CertificateV2.Error ex_0) {
                // We don't expect this for the copy constructor.
                throw new Pib.Error("Error copying certificate: " + ex_0);
            }
        }
Beispiel #21
0
            public void processInterest(Interest interest, OnData onData,
                                        OnTimeout onTimeout, OnNetworkNack onNetworkNack)
            {
                try {
                    // Create another key for the same identity and sign it properly.
                    PibKey parentKey = outer_TestValidator.fixture_.keyChain_
                                       .createKey(outer_TestValidator.fixture_.subIdentity_);
                    PibKey requestedKey = outer_TestValidator.fixture_.subIdentity_.getKey(interest
                                                                                           .getName());

                    // Copy the Name.
                    Name certificateName = new Name(requestedKey.getName());
                    certificateName.append("looper").appendVersion(1);
                    CertificateV2 certificate = new CertificateV2();
                    certificate.setName(certificateName);

                    // Set the MetaInfo.
                    certificate.getMetaInfo().setType(net.named_data.jndn.ContentType.KEY);
                    // Set the freshness period to one hour.
                    certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0d);

                    // Set the content.
                    certificate.setContent(requestedKey.getPublicKey());

                    // Set SigningInfo.
                    SigningInfo                             // Set SigningInfo.
                        paras = new SigningInfo(parentKey);
                    // Validity period from 10 days before to 10 days after now.
                    double now = net.named_data.jndn.util.Common.getNowMilliseconds();
                    paras.setValidityPeriod(new ValidityPeriod(now - 10 * 24
                                                               * 3600 * 1000.0d, now + 10 * 24 * 3600 * 1000.0d));

                    outer_TestValidator.fixture_.keyChain_.sign(certificate, paras);
                    onData.onData(interest, certificate);
                } catch (Exception ex) {
                    Assert.Fail("Error in InfiniteCertificateChain: " + ex);
                }
            }
        public void setUp()
        {
            anchorContainer = new TrustAnchorContainer();
            fixture         = new IdentityManagementFixture();

            // Create a directory and prepares two certificates.
            certificateDirectoryPath = new FileInfo(System.IO.Path.Combine(net.named_data.jndn.tests.integration_tests.IntegrationTestsCommon.getPolicyConfigDirectory().FullName, "test-cert-dir"));
            System.IO.Directory.CreateDirectory(certificateDirectoryPath.FullName);

            certificatePath1 = new FileInfo(System.IO.Path.Combine(certificateDirectoryPath.FullName, "trust-anchor-1.cert"));
            certificatePath2 = new FileInfo(System.IO.Path.Combine(certificateDirectoryPath.FullName, "trust-anchor-2.cert"));

            identity1    = fixture.addIdentity(new Name("/TestAnchorContainer/First"));
            certificate1 = identity1.getDefaultKey().getDefaultCertificate();
            fixture.saveCertificateToFile(certificate1,
                                          certificatePath1.FullName);

            identity2 = fixture
                        .addIdentity(new Name("/TestAnchorContainer/Second"));
            certificate2 = identity2.getDefaultKey().getDefaultCertificate();
            fixture.saveCertificateToFile(certificate2,
                                          certificatePath2.FullName);
        }
Beispiel #23
0
        public void testConstructor()
        {
            CertificateV2 certificate = new CertificateV2();

            certificate.wireDecode(new Blob(CERT, false));

            Assert.AssertEquals(new Name(
                                    "/ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B"),
                                certificate.getName());
            Assert.AssertEquals(new Name("/ndn/site1/KEY/ksk-1416425377094"),
                                certificate.getKeyName());
            Assert.AssertEquals(new Name("/ndn/site1"), certificate.getIdentity());
            Assert.AssertEquals(new Name.Component("0123"), certificate.getIssuerId());
            Assert.AssertEquals(new Name.Component("ksk-1416425377094"),
                                certificate.getKeyId());
            Assert.AssertEquals(new Name("/ndn/site1/KEY/ksk-2516425377094"), net.named_data.jndn.KeyLocator
                                .getFromSignature(certificate.getSignature()).getKeyName());
            Assert.AssertEquals(net.named_data.jndn.tests.unit_tests.UnitTestsCommon.fromIsoString("20150814T223739"), certificate
                                .getValidityPeriod().getNotBefore(), 0);
            Assert.AssertEquals(net.named_data.jndn.tests.unit_tests.UnitTestsCommon.fromIsoString("20150818T223738"), certificate
                                .getValidityPeriod().getNotAfter(), 0);

            try {
                certificate.getPublicKey();
            } catch (Exception ex) {
                Assert.Fail(ex.Message);
            }

            Data data = new Data();

            data.wireDecode(new Blob(CERT, false));
            CertificateV2 certificate2 = new CertificateV2(data);

            Assert.AssertEquals(certificate.getName(), certificate2.getName());
            Assert.AssertTrue(certificate.getPublicKey().equals(
                                  certificate2.getPublicKey()));
        }
Beispiel #24
0
        /// <summary>
        /// Get the default certificate for the key with eyName.
        /// </summary>
        ///
        /// <param name="keyName">The name of the key.</param>
        /// <returns>A copy of the default certificate.</returns>
        /// <exception cref="Pib.Error">if the default certificate does not exist.</exception>
        public override CertificateV2 getDefaultCertificateOfKey(Name keyName)
        {
            Name certificateName = ILOG.J2CsMapping.Collections.Collections.Get(defaultCertificateNames_, keyName);

            if (certificateName == null)
            {
                throw new Pib.Error("No default certificate for key `"
                                    + keyName.toUri() + "`");
            }

            CertificateV2 certificate = ILOG.J2CsMapping.Collections.Collections.Get(certificates_, certificateName);

            if (certificate == null)
            {
                // We don't expect this since we just checked defaultCertificateNames_.
                throw new Pib.Error("certificate not found");
            }
            try {
                return(new CertificateV2(certificate));
            } catch (CertificateV2.Error ex) {
                // We don't expect an error in the copy constructor.
                throw new PibImpl.Error(ex.Message);
            }
        }
Beispiel #25
0
        public void testPrintCertificateInfo()
        {
            String expectedCertificateInfo = "Certificate name:\n"
                                             + "  /ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B\n"
                                             + "Validity:\n"
                                             + "  NotBefore: 20150814T223739\n"
                                             + "  NotAfter: 20150818T223738\n"
                                             + "Public key bits:\n"
                                             + "MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQCeBj5HhbI0N6qFR6wDJIO1nKgF\n"
                                             + "OiQe64kBu+mbssMirGjj8GwCzmimxNCnBpCcqhsIHYtDmjNnRG0hoxuImpdeWcQV\n"
                                             + "C9ksvVEHYYKtwbjXv5vPfSTCY/OXF+v+YiW6W02Kwnq9Q4qPuPLxxWow01CMyJrf\n"
                                             + "7+0153pi6nZ8uwgmxwIBEQ==\n" + "Signature Information:\n"
                                             + "  Signature Type: SignatureSha256WithRsa\n"
                                             + "  Key Locator: Name=/ndn/site1/KEY/ksk-2516425377094\n";

            CertificateV2 certificate = new CertificateV2();

            certificate.wireDecode(new Blob(CERT, false));

            StringBuilder actual = new StringBuilder();

            certificate.printCertificate(actual);
            Assert.AssertEquals(expectedCertificateInfo, actual.toString());
        }
        /// <summary>
        /// Issue a certificate for subIdentityName signed by issuer. If the identity
        /// does not exist, it is created. A new key is generated as the default key
        /// for the identity. A default certificate for the key is signed by the
        /// issuer using its default certificate.
        /// </summary>
        ///
        /// <param name="subIdentityName">The name to issue the certificate for.</param>
        /// <param name="issuer">The identity of the signer.</param>
        /// <param name="params"></param>
        /// <returns>The sub identity.</returns>
        internal PibIdentity addSubCertificate(Name subIdentityName, PibIdentity issuer,
                                               KeyParams paras)
        {
            PibIdentity subIdentity = addIdentity(subIdentityName, paras);

            CertificateV2 request = subIdentity.getDefaultKey()
                                    .getDefaultCertificate();

            request.setName(request.getKeyName().append("parent").appendVersion(1));

            SigningInfo certificateParams = new SigningInfo(issuer);
            // Validity period of 20 years.
            double now = net.named_data.jndn.util.Common.getNowMilliseconds();

            certificateParams.setValidityPeriod(new ValidityPeriod(now, now + 20
                                                                   * 365 * 24 * 3600 * 1000.0d));

            // Skip the AdditionalDescription.

            keyChain_.sign(request, certificateParams);
            keyChain_.setDefaultCertificate(subIdentity.getDefaultKey(), request);

            return(subIdentity);
        }
Beispiel #27
0
        public void testManagement()
        {
            Name identityName  = new Name("/test/id");
            Name identity2Name = new Name("/test/id2");

            Assert.AssertEquals(0, fixture_.keyChain_.getPib().getIdentities_().size());
            try {
                fixture_.keyChain_.getPib().getDefaultIdentity();
                Assert.Fail("Did not throw the expected exception");
            } catch (Pib.Error ex) {
            } catch (Exception ex_0) {
                Assert.Fail("Did not throw the expected exception");
            }

            // Create an identity.
            PibIdentity id = fixture_.keyChain_.createIdentityV2(identityName);

            Assert.AssertTrue(id != null);
            Assert.AssertTrue(fixture_.keyChain_.getPib().getIdentities_()
                              .getIdentities_().Contains(identityName));

            // The first added identity becomes the default identity.
            try {
                fixture_.keyChain_.getPib().getDefaultIdentity();
            } catch (Exception ex_1) {
                Assert.Fail("Unexpected exception: " + ex_1.Message);
            }

            // The default key of the added identity must exist.
            PibKey key = null;

            try {
                key = id.getDefaultKey();
            } catch (Exception ex_2) {
                Assert.Fail("Unexpected exception: " + ex_2.Message);
            }

            // The default certificate of the default key must exist.
            try {
                key.getDefaultCertificate();
            } catch (Exception ex_3) {
                Assert.Fail("Unexpected exception: " + ex_3.Message);
            }

            // Delete the key.
            Name key1Name = key.getName();

            try {
                id.getKey(key1Name);
            } catch (Exception ex_4) {
                Assert.Fail("Unexpected exception: " + ex_4.Message);
            }

            Assert.AssertEquals(1, id.getKeys_().size());
            fixture_.keyChain_.deleteKey(id, key);

            /* TODO: Implement key validity.
             *  // The key instance should not be valid anymore.
             *  assertTrue(!key);
             */

            try {
                id.getKey(key1Name);
                Assert.Fail("Did not throw the expected exception");
            } catch (Pib.Error ex_5) {
            } catch (Exception ex_6) {
                Assert.Fail("Did not throw the expected exception");
            }

            Assert.AssertEquals(0, id.getKeys_().size());

            // Create another key.
            fixture_.keyChain_.createKey(id);
            // The added key becomes the default key.
            try {
                id.getDefaultKey();
            } catch (Exception ex_7) {
                Assert.Fail("Unexpected exception: " + ex_7.Message);
            }

            PibKey key2 = id.getDefaultKey();

            Assert.AssertTrue(key2 != null);
            Assert.AssertTrue(!key2.getName().equals(key1Name));
            Assert.AssertEquals(1, id.getKeys_().size());
            try {
                key2.getDefaultCertificate();
            } catch (Exception ex_8) {
                Assert.Fail("Unexpected exception: " + ex_8.Message);
            }

            // Create a third key.
            PibKey key3 = fixture_.keyChain_.createKey(id);

            Assert.AssertTrue(!key3.getName().equals(key2.getName()));
            // The added key will not be the default key, because the default key already exists.
            Assert.AssertTrue(id.getDefaultKey().getName().equals(key2.getName()));
            Assert.AssertEquals(2, id.getKeys_().size());
            try {
                key3.getDefaultCertificate();
            } catch (Exception ex_9) {
                Assert.Fail("Unexpected exception: " + ex_9.Message);
            }

            // Delete the certificate.
            Assert.AssertEquals(1, key3.getCertificates_().size());
            CertificateV2 key3Cert1 = (CertificateV2)ILOG.J2CsMapping.Collections.Collections.ToArray(key3.getCertificates_()
                                                                                                      .getCertificates_().Values)[0];
            Name key3CertName = key3Cert1.getName();

            fixture_.keyChain_.deleteCertificate(key3, key3CertName);
            Assert.AssertEquals(0, key3.getCertificates_().size());
            try {
                key3.getDefaultCertificate();
                Assert.Fail("Did not throw the expected exception");
            } catch (Pib.Error ex_10) {
            } catch (Exception ex_11) {
                Assert.Fail("Did not throw the expected exception");
            }

            // Add a certificate.
            fixture_.keyChain_.addCertificate(key3, key3Cert1);
            Assert.AssertEquals(1, key3.getCertificates_().size());
            try {
                key3.getDefaultCertificate();
            } catch (Exception ex_12) {
                Assert.Fail("Unexpected exception: " + ex_12.Message);
            }

            // Overwriting the certificate should work.
            fixture_.keyChain_.addCertificate(key3, key3Cert1);
            Assert.AssertEquals(1, key3.getCertificates_().size());
            // Add another certificate.
            CertificateV2 key3Cert2     = new CertificateV2(key3Cert1);
            Name          key3Cert2Name = new Name(key3.getName());

            key3Cert2Name.append("Self");
            key3Cert2Name.appendVersion(1);
            key3Cert2.setName(key3Cert2Name);
            fixture_.keyChain_.addCertificate(key3, key3Cert2);
            Assert.AssertEquals(2, key3.getCertificates_().size());

            // Set the default certificate.
            Assert.AssertTrue(key3.getDefaultCertificate().getName().equals(key3CertName));
            fixture_.keyChain_.setDefaultCertificate(key3, key3Cert2);
            Assert.AssertTrue(key3.getDefaultCertificate().getName().equals(key3Cert2Name));

            // Set the default key.
            Assert.AssertTrue(id.getDefaultKey().getName().equals(key2.getName()));
            fixture_.keyChain_.setDefaultKey(id, key3);
            Assert.AssertTrue(id.getDefaultKey().getName().equals(key3.getName()));

            // Set the default identity.
            PibIdentity id2 = fixture_.keyChain_.createIdentityV2(identity2Name);

            Assert.AssertTrue(fixture_.keyChain_.getPib().getDefaultIdentity().getName()
                              .equals(id.getName()));
            fixture_.keyChain_.setDefaultIdentity(id2);
            Assert.AssertTrue(fixture_.keyChain_.getPib().getDefaultIdentity().getName()
                              .equals(id2.getName()));

            // Delete an identity.
            fixture_.keyChain_.deleteIdentity(id);

            /* TODO: Implement identity validity.
             *  // The identity instance should not be valid any more.
             *  BOOST_CHECK(!id);
             */
            try {
                fixture_.keyChain_.getPib().getIdentity(identityName);
                Assert.Fail("Did not throw the expected exception");
            } catch (Pib.Error ex_13) {
            } catch (Exception ex_14) {
                Assert.Fail("Did not throw the expected exception");
            }

            Assert.AssertTrue(!fixture_.keyChain_.getPib().getIdentities_()
                              .getIdentities_().Contains(identityName));
        }
Beispiel #28
0
 /// <summary>
 /// Add the certificate. If a certificate with the same name (without implicit
 /// digest) already exists, then overwrite the certificate. If the key or
 /// identity does not exist, they will be created. If no default certificate
 /// for the key has been set, then set the added certificate as the default for
 /// the key. If no default key was set for the identity, it will be set as
 /// default key for the identity. If no default identity was selected, the
 /// certificate's identity becomes the default.
 /// </summary>
 ///
 /// <param name="certificate">The certificate to add. This copies the object.</param>
 /// <exception cref="PibImpl.Error">for a non-semantic (database access) error.</exception>
 public abstract void addCertificate(CertificateV2 certificate);
        public void testRefresh10s()
        {
            StringBuilder encodedData = new StringBuilder();
            TextReader    dataFile    = new FileReader(new FileInfo(System.IO.Path.Combine(policyConfigDirectory_.FullName, "testData")).FullName);

            // Use "try/finally instead of "try-with-resources" or "using"
            // which are not supported before Java 7.
            try {
                String line;
                while ((line = dataFile.readLine()) != null)
                {
                    encodedData.append(line);
                }
            } finally {
                dataFile.close();
            }

            byte[] decodedData = net.named_data.jndn.util.Common.base64Decode(encodedData.toString());
            Data   data        = new Data();

            data.wireDecode(new Blob(decodedData, false));

            // This test is needed, since the KeyChain will express interests in unknown
            // certificates.
            VerificationResult vr = doVerify(policyManager_, data);

            Assert.AssertTrue(
                "ConfigPolicyManager did not create ValidationRequest for unknown certificate",
                vr.hasFurtherSteps_);
            Assert.AssertEquals(
                "ConfigPolicyManager called success callback with pending ValidationRequest",
                0, vr.successCount_);
            Assert.AssertEquals(
                "ConfigPolicyManager called failure callback with pending ValidationRequest",
                0, vr.failureCount_);

            // Now save the cert data to our anchor directory, and wait.
            // We have to sign it with the current identity or the policy manager will
            // create an interest for the signing certificate.
            CertificateV2 cert = new CertificateV2();

            byte[] certData = net.named_data.jndn.util.Common.base64Decode(CERT_DUMP);
            cert.wireDecode(new Blob(certData, false));
            SigningInfo signingInfo = new SigningInfo();

            signingInfo.setSigningIdentity(identityName_);
            // Make sure the validity period is current for two years.
            double now = net.named_data.jndn.util.Common.getNowMilliseconds();

            signingInfo.setValidityPeriod(new ValidityPeriod(now, now + 2 * 365
                                                             * 24 * 3600 * 1000.0d));

            keyChain_.sign(cert, signingInfo);
            Blob   signedCertBlob = cert.wireEncode();
            String encodedCert    = net.named_data.jndn.util.Common.base64Encode(signedCertBlob
                                                                                 .getImmutableArray());
            var certFile = (new StreamWriter(
                                testCertFile_.FullName));

            try {
                certFile.Write(encodedCert, 0, encodedCert.Substring(0, encodedCert.Length));
                certFile.flush();
            } finally {
                certFile.close();
            }

            // Still too early for refresh to pick it up.
            vr = doVerify(policyManager_, data);

            Assert.AssertTrue("ConfigPolicyManager refresh occured sooner than specified",
                              vr.hasFurtherSteps_);
            Assert.AssertEquals(
                "ConfigPolicyManager called success callback with pending ValidationRequest",
                0, vr.successCount_);
            Assert.AssertEquals(
                "ConfigPolicyManager called failure callback with pending ValidationRequest",
                0, vr.failureCount_);

            ILOG.J2CsMapping.Threading.ThreadWrapper.sleep(6000);

            // Now we should find it.
            vr = doVerify(policyManager_, data);

            Assert.AssertFalse("ConfigPolicyManager did not refresh certificate store",
                               vr.hasFurtherSteps_);
            Assert.AssertEquals("Verification success called " + vr.successCount_
                                + " times instead of 1", 1, vr.successCount_);
            Assert.AssertEquals("ConfigPolicyManager did not verify valid signed data", 0,
                                vr.failureCount_);
        }
        public void testBasic()
        {
            PibMemory pibImpl = new PibMemory();

            // Start with an empty container.
            PibCertificateContainer container = new PibCertificateContainer(
                fixture.id1Key1Name, pibImpl);

            Assert.AssertEquals(0, container.size());
            Assert.AssertEquals(0, container.getCertificates_().Count);

            // Add a certificate.
            container.add(fixture.id1Key1Cert1);
            Assert.AssertEquals(1, container.size());
            Assert.AssertEquals(1, container.getCertificates_().Count);
            Assert.AssertTrue(container.getCertificates_().Contains(
                                  fixture.id1Key1Cert1.getName()));

            // Add the same certificate again.
            container.add(fixture.id1Key1Cert1);
            Assert.AssertEquals(1, container.size());
            Assert.AssertEquals(1, container.getCertificates_().Count);
            Assert.AssertTrue(container.getCertificates_().Contains(
                                  fixture.id1Key1Cert1.getName()));

            // Add another certificate.
            container.add(fixture.id1Key1Cert2);
            Assert.AssertEquals(2, container.size());
            Assert.AssertEquals(2, container.getCertificates_().Count);
            Assert.AssertTrue(container.getCertificates_().Contains(
                                  fixture.id1Key1Cert1.getName()));
            Assert.AssertTrue(container.getCertificates_().Contains(
                                  fixture.id1Key1Cert2.getName()));

            // Get the certificates.
            try {
                container.get(fixture.id1Key1Cert1.getName());
            } catch (Exception ex) {
                Assert.Fail("Unexpected exception: " + ex.Message);
            }
            try {
                container.get(fixture.id1Key1Cert2.getName());
            } catch (Exception ex_0) {
                Assert.Fail("Unexpected exception: " + ex_0.Message);
            }
            Name id1Key1Cert3Name = new Name(fixture.id1Key1Name);

            id1Key1Cert3Name.append("issuer").appendVersion(3);
            try {
                container.get(id1Key1Cert3Name);
                Assert.Fail("Did not throw the expected exception");
            } catch (Pib.Error ex_1) {
            } catch (Exception ex_2) {
                Assert.Fail("Did not throw the expected exception");
            }

            // Check the certificates.
            CertificateV2 cert1 = container.get(fixture.id1Key1Cert1.getName());
            CertificateV2 cert2 = container.get(fixture.id1Key1Cert2.getName());

            // Use the wire encoding to check equivalence.
            Assert.AssertTrue(cert1.wireEncode().equals(fixture.id1Key1Cert1.wireEncode()));
            Assert.AssertTrue(cert2.wireEncode().equals(fixture.id1Key1Cert2.wireEncode()));

            // Create another container with the same PibImpl. The cache should be empty.
            PibCertificateContainer container2 = new PibCertificateContainer(
                fixture.id1Key1Name, pibImpl);

            Assert.AssertEquals(2, container2.size());
            Assert.AssertEquals(0, container2.getCertificates_().Count);

            // Get a certificate. The cache should be filled.
            try {
                container2.get(fixture.id1Key1Cert1.getName());
            } catch (Exception ex_3) {
                Assert.Fail("Unexpected exception: " + ex_3.Message);
            }
            Assert.AssertEquals(2, container2.size());
            Assert.AssertEquals(1, container2.getCertificates_().Count);

            try {
                container2.get(fixture.id1Key1Cert2.getName());
            } catch (Exception ex_4) {
                Assert.Fail("Unexpected exception: " + ex_4.Message);
            }
            Assert.AssertEquals(2, container2.size());
            Assert.AssertEquals(2, container2.getCertificates_().Count);

            // Remove a certificate.
            container2.remove(fixture.id1Key1Cert1.getName());
            Assert.AssertEquals(1, container2.size());
            Assert.AssertEquals(1, container2.getCertificates_().Count);
            Assert.AssertTrue(!container2.getCertificates_().Contains(
                                  fixture.id1Key1Cert1.getName()));
            Assert.AssertTrue(container2.getCertificates_().Contains(
                                  fixture.id1Key1Cert2.getName()));

            // Remove another certificate.
            container2.remove(fixture.id1Key1Cert2.getName());
            Assert.AssertEquals(0, container2.size());
            Assert.AssertEquals(0, container2.getCertificates_().Count);
            Assert.AssertTrue(!container2.getCertificates_().Contains(
                                  fixture.id1Key1Cert2.getName()));
        }