Exemple #1
0
        private static Boolean VerifyCertificateChain(X509Certificate cert)
        {
            if (null == cert)
            {
                log.Error("cert must Not null");
                return(false);
            }
            X509Certificate rootCert = GetRootCert();

            if (null == rootCert)
            {
                log.Error("rootCert must Not null");
                return(false);
            }
            X509Certificate middleCert = GetMiddleCert();

            if (null == middleCert)
            {
                log.Error("middleCert must Not null");
                return(false);
            }

            try
            {
                X509CertStoreSelector selector = new X509CertStoreSelector();
                selector.Subject = cert.SubjectDN;

                ISet trustAnchors = new HashSet();
                trustAnchors.Add(new TrustAnchor(rootCert, null));
                PkixBuilderParameters pkixParams = new PkixBuilderParameters(
                    trustAnchors, selector);

                IList intermediateCerts = new ArrayList();
                intermediateCerts.Add(rootCert);
                intermediateCerts.Add(middleCert);
                intermediateCerts.Add(cert);

                pkixParams.IsRevocationEnabled = false;

                IX509Store intermediateCertStore = X509StoreFactory.Create(
                    "Certificate/Collection",
                    new X509CollectionStoreParameters(intermediateCerts));
                pkixParams.AddStore(intermediateCertStore);

                PkixCertPathBuilder       pathBuilder = new PkixCertPathBuilder();
                PkixCertPathBuilderResult result      = pathBuilder.Build(pkixParams);
                PkixCertPath path = result.CertPath;
                log.Info("verify certificate chain succeed.");
                return(true);
            }
            catch (PkixCertPathBuilderException e)
            {
                log.Error("verify certificate chain fail.", e);
            }
            catch (Exception e)
            {
                log.Error("verify certificate chain exception: ", e);
            }
            return(false);
        }
Exemple #2
0
        private void baseTest()
        {
//			CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
            X509CertificateParser certParser = new X509CertificateParser();
            X509CrlParser         crlParser  = new X509CrlParser();

            // initialise CertStore
            X509Certificate rootCert  = certParser.ReadCertificate(CertPathTest.rootCertBin);
            X509Certificate interCert = certParser.ReadCertificate(CertPathTest.interCertBin);
            X509Certificate finalCert = certParser.ReadCertificate(CertPathTest.finalCertBin);
            X509Crl         rootCrl   = crlParser.ReadCrl(CertPathTest.rootCrlBin);
            X509Crl         interCrl  = crlParser.ReadCrl(CertPathTest.interCrlBin);

            IList certList = new ArrayList();

            certList.Add(rootCert);
            certList.Add(interCert);
            certList.Add(finalCert);

            IList crlList = new ArrayList();

            crlList.Add(rootCrl);
            crlList.Add(interCrl);

//			CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list);
//			CertStore store = CertStore.getInstance("Collection", ccsp, "BC");
            IX509Store x509CertStore = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));
            IX509Store x509CrlStore = X509StoreFactory.Create(
                "CRL/Collection",
                new X509CollectionStoreParameters(crlList));

            // NB: Month is 1-based in .NET
            DateTime validDate = new DateTime(2008, 9, 4, 14, 49, 10).ToUniversalTime();

            //Searching for rootCert by subjectDN without CRL
            ISet trust = new HashSet();

            trust.Add(new TrustAnchor(rootCert, null));

//			CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX","BC");
            PkixCertPathBuilder   cpb = new PkixCertPathBuilder();
            X509CertStoreSelector targetConstraints = new X509CertStoreSelector();

            targetConstraints.Subject = finalCert.SubjectDN;
            PkixBuilderParameters parameters = new PkixBuilderParameters(trust, targetConstraints);

//			parameters.addCertStore(store);
            parameters.AddStore(x509CertStore);
            parameters.AddStore(x509CrlStore);
            parameters.Date = new DateTimeObject(validDate);
            PkixCertPathBuilderResult result = cpb.Build(parameters);
            PkixCertPath path = result.CertPath;

            if (path.Certificates.Count != 2)
            {
                Fail("wrong number of certs in baseTest path");
            }
        }
Exemple #3
0
    public override bool Equals(object obj)
    {
        if (this == obj)
        {
            return(true);
        }
        PkixCertPath pkixCertPath = obj as PkixCertPath;

        if (pkixCertPath == null)
        {
            return(false);
        }
        IList list  = Certificates;
        IList list2 = pkixCertPath.Certificates;

        if (list.Count != list2.Count)
        {
            return(false);
        }
        IEnumerator enumerator  = list.GetEnumerator();
        IEnumerator enumerator2 = list.GetEnumerator();

        while (enumerator.MoveNext())
        {
            enumerator2.MoveNext();
            if (!object.Equals(enumerator.Current, enumerator2.Current))
            {
                return(false);
            }
        }
        return(true);
    }
    public virtual PkixCertPathValidatorResult Validate(PkixCertPath certPath, PkixParameters pkixParams)
    {
        IX509Selector targetConstraints = pkixParams.GetTargetConstraints();

        if (!(targetConstraints is X509AttrCertStoreSelector))
        {
            throw new ArgumentException("TargetConstraints must be an instance of " + typeof(X509AttrCertStoreSelector).FullName, "pkixParams");
        }
        IX509AttributeCertificate attributeCert     = ((X509AttrCertStoreSelector)targetConstraints).AttributeCert;
        PkixCertPath holderCertPath                 = Rfc3281CertPathUtilities.ProcessAttrCert1(attributeCert, pkixParams);
        PkixCertPathValidatorResult result          = Rfc3281CertPathUtilities.ProcessAttrCert2(certPath, pkixParams);
        X509Certificate             x509Certificate = (X509Certificate)certPath.Certificates[0];

        Rfc3281CertPathUtilities.ProcessAttrCert3(x509Certificate, pkixParams);
        Rfc3281CertPathUtilities.ProcessAttrCert4(x509Certificate, pkixParams);
        Rfc3281CertPathUtilities.ProcessAttrCert5(attributeCert, pkixParams);
        Rfc3281CertPathUtilities.ProcessAttrCert7(attributeCert, certPath, holderCertPath, pkixParams);
        Rfc3281CertPathUtilities.AdditionalChecks(attributeCert, pkixParams);
        DateTime validCertDateFromValidityModel;

        try
        {
            validCertDateFromValidityModel = PkixCertPathValidatorUtilities.GetValidCertDateFromValidityModel(pkixParams, null, -1);
        }
        catch (Exception cause)
        {
            throw new PkixCertPathValidatorException("Could not get validity date from attribute certificate.", cause);
        }
        Rfc3281CertPathUtilities.CheckCrls(attributeCert, pkixParams, x509Certificate, validCertDateFromValidityModel, certPath.Certificates);
        return(result);
    }
    internal static void ProcessAttrCert7(IX509AttributeCertificate attrCert, PkixCertPath certPath, PkixCertPath holderCertPath, PkixParameters pkixParams)
    {
        ISet criticalExtensionOids = attrCert.GetCriticalExtensionOids();

        if (criticalExtensionOids.Contains(X509Extensions.TargetInformation.Id))
        {
            try
            {
                TargetInformation.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(attrCert, X509Extensions.TargetInformation));
            }
            catch (Exception cause)
            {
                throw new PkixCertPathValidatorException("Target information extension could not be read.", cause);
            }
        }
        criticalExtensionOids.Remove(X509Extensions.TargetInformation.Id);
        foreach (PkixAttrCertChecker attrCertChecker in pkixParams.GetAttrCertCheckers())
        {
            attrCertChecker.Check(attrCert, certPath, holderCertPath, criticalExtensionOids);
        }
        if (!criticalExtensionOids.IsEmpty)
        {
            throw new PkixCertPathValidatorException("Attribute certificate contains unsupported critical extensions: " + criticalExtensionOids);
        }
    }
Exemple #6
0
        private static bool VerifyCertificateChain(X509Certificate cert)
        {
            if (cert is null)
            {
                return(false);
            }

            X509Certificate rootCert = GetRootCert();

            if (rootCert is null)
            {
                return(false);
            }

            X509Certificate middleCert = GetMiddleCert();

            if (middleCert is null)
            {
                return(false);
            }

            try
            {
                X509CertStoreSelector selector = new X509CertStoreSelector
                {
                    Subject = cert.SubjectDN
                };

                ISet trustAnchors = new HashSet
                {
                    new TrustAnchor(rootCert, null)
                };
                PkixBuilderParameters pkixParams = new PkixBuilderParameters(trustAnchors, selector);

                IList intermediateCerts = new ArrayList
                {
                    rootCert,
                    middleCert,
                    cert
                };

                pkixParams.IsRevocationEnabled = false;

                IX509Store intermediateCertStore = X509StoreFactory.Create(
                    "Certificate/Collection",
                    new X509CollectionStoreParameters(intermediateCerts));
                pkixParams.AddStore(intermediateCertStore);

                PkixCertPathBuilder       pathBuilder = new PkixCertPathBuilder();
                PkixCertPathBuilderResult result      = pathBuilder.Build(pkixParams);
                PkixCertPath path = result.CertPath;
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemple #7
0
 public PkixCertPathBuilderResult(PkixCertPath certPath, TrustAnchor trustAnchor, PkixPolicyNode policyTree, AsymmetricKeyParameter subjectPublicKey)
     : base(trustAnchor, policyTree, subjectPublicKey)
 {
     if (certPath == null)
     {
         throw new ArgumentNullException("certPath");
     }
     this.certPath = certPath;
 }
        private void VerifyDistinguishedName(PkixCertPath path)
        {
            X509Certificate leaf = (X509Certificate)path.Certificates[0];
            string          distinguishedName = leaf.SubjectDN.ToString();

            if ("C=US,ST=CA,L=Santa Clara,O=Intel Corporation,CN=Intel SGX Attestation Report Signing" != distinguishedName)
            {
                throw new CryptographicException($"Bad DN: {distinguishedName}");
            }
        }
        private PkixCertPathValidatorResult DoTest(
            string trustAnchor,
            string[] certs,
            string[] crls,
            ISet policies)
        {
            ISet trustedSet = new HashSet();

            trustedSet.Add(GetTrustAnchor(trustAnchor));

            IList           x509Certs = new ArrayList();
            IList           x509Crls  = new ArrayList();
            X509Certificate endCert   = LoadCert(certs[certs.Length - 1]);

            for (int i = 0; i != certs.Length - 1; i++)
            {
                x509Certs.Add(LoadCert(certs[i]));
            }

            x509Certs.Add(endCert);

            PkixCertPath certPath = new PkixCertPath(x509Certs);

            for (int i = 0; i != crls.Length; i++)
            {
                x509Crls.Add(LoadCrl(crls[i]));
            }

            IX509Store x509CertStore = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(x509Certs));
            IX509Store x509CrlStore = X509StoreFactory.Create(
                "CRL/Collection",
                new X509CollectionStoreParameters(x509Crls));

//			CertPathValidator validator = CertPathValidator.GetInstance("PKIX");
            PkixCertPathValidator validator  = new PkixCertPathValidator();
            PkixParameters        parameters = new PkixParameters(trustedSet);

            parameters.AddStore(x509CertStore);
            parameters.AddStore(x509CrlStore);
            parameters.IsRevocationEnabled = true;

            if (policies != null)
            {
                parameters.IsExplicitPolicyRequired = true;
                parameters.SetInitialPolicies(policies);
            }

            // Perform validation as of this date since test certs expired
            parameters.Date = new DateTimeObject(DateTime.Parse("1/1/2011"));

            return(validator.Validate(certPath, parameters));
        }
    internal static PkixCertPathValidatorResult ProcessAttrCert2(PkixCertPath certPath, PkixParameters pkixParams)
    {
        PkixCertPathValidator pkixCertPathValidator = new PkixCertPathValidator();

        try
        {
            return(pkixCertPathValidator.Validate(certPath, pkixParams));
        }
        catch (PkixCertPathValidatorException cause)
        {
            throw new PkixCertPathValidatorException("Certification path for issuer certificate of attribute certificate could not be validated.", cause);
        }
    }
        /// <summary>
        ///
        /// </summary>
        /// <param name="certificateChain"></param>
        /// <exception cref="PkixCertPathValidatorException"></exception>
        /// <exception cref="CryptographicException"></exception>
        public SigningCertificate(string certificateChain)
        {
            StringReader           stringReader = new StringReader(certificateChain);
            PemReader              pemReader    = new PemReader(stringReader);
            List <X509Certificate> certificates = new List <X509Certificate>();

            X509Certificate certificate;

            while ((certificate = (X509Certificate)pemReader.ReadObject()) != null)
            {
                certificates.Add(certificate);
            }

            path = new PkixCertPath(certificates);

            Org.BouncyCastle.Utilities.Collections.ISet trustAnchors = new Org.BouncyCastle.Utilities.Collections.HashSet(new TrustAnchor[] { new TrustAnchor(certificates.Last(), null) });
            PkixParameters pkixParameters = new PkixParameters(trustAnchors);

            pkixParameters.IsRevocationEnabled = false;
            PkixCertPathValidator certPathValidator = new PkixCertPathValidator();

            certPathValidator.Validate(path, pkixParameters);
            VerifyDistinguishedName(path);
        }
 internal static DateTime GetValidCertDateFromValidityModel(PkixParameters paramsPkix, PkixCertPath certPath, int index)
 {
     if (paramsPkix.ValidityModel != 1)
     {
         return(GetValidDate(paramsPkix));
     }
     if (index <= 0)
     {
         return(GetValidDate(paramsPkix));
     }
     if (index - 1 == 0)
     {
         DerGeneralizedTime derGeneralizedTime = null;
         try
         {
             X509Certificate x509Certificate = (X509Certificate)certPath.Certificates[index - 1];
             Asn1OctetString extensionValue  = x509Certificate.GetExtensionValue(IsisMttObjectIdentifiers.IdIsisMttATDateOfCertGen);
             derGeneralizedTime = DerGeneralizedTime.GetInstance(extensionValue);
         }
         catch (ArgumentException)
         {
             throw new Exception("Date of cert gen extension could not be read.");
         }
         if (derGeneralizedTime != null)
         {
             try
             {
                 return(derGeneralizedTime.ToDateTime());
             }
             catch (ArgumentException innerException)
             {
                 throw new Exception("Date from date of cert gen extension could not be parsed.", innerException);
             }
         }
     }
     return(((X509Certificate)certPath.Certificates[index - 1]).NotBefore);
 }
    public virtual PkixCertPathValidatorResult Validate(PkixCertPath certPath, PkixParameters paramsPkix)
    {
        if (paramsPkix.GetTrustAnchors() == null)
        {
            throw new ArgumentException("trustAnchors is null, this is not allowed for certification path validation.", "parameters");
        }
        IList certificates = certPath.Certificates;
        int   count        = certificates.Count;

        if (certificates.Count == 0)
        {
            throw new PkixCertPathValidatorException("Certification path is empty.", null, certPath, 0);
        }
        ISet        initialPolicies = paramsPkix.GetInitialPolicies();
        TrustAnchor trustAnchor;

        try
        {
            trustAnchor = PkixCertPathValidatorUtilities.FindTrustAnchor((X509Certificate)certificates[certificates.Count - 1], paramsPkix.GetTrustAnchors());
        }
        catch (Exception ex)
        {
            throw new PkixCertPathValidatorException(ex.Message, ex, certPath, certificates.Count - 1);
        }
        if (trustAnchor == null)
        {
            throw new PkixCertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1);
        }
        int num = 0;

        IList[] array = new IList[count + 1];
        for (int i = 0; i < array.Length; i++)
        {
            array[i] = Platform.CreateArrayList();
        }
        ISet set = new HashSet();

        set.Add(Rfc3280CertPathUtilities.ANY_POLICY);
        PkixPolicyNode pkixPolicyNode = new PkixPolicyNode(Platform.CreateArrayList(), 0, set, null, new HashSet(), Rfc3280CertPathUtilities.ANY_POLICY, critical: false);

        array[0].Add(pkixPolicyNode);
        PkixNameConstraintValidator nameConstraintValidator = new PkixNameConstraintValidator();
        ISet                   acceptablePolicies           = new HashSet();
        int                    explicitPolicy   = (!paramsPkix.IsExplicitPolicyRequired) ? (count + 1) : 0;
        int                    inhibitAnyPolicy = (!paramsPkix.IsAnyPolicyInhibited) ? (count + 1) : 0;
        int                    policyMapping    = (!paramsPkix.IsPolicyMappingInhibited) ? (count + 1) : 0;
        X509Certificate        x509Certificate  = trustAnchor.TrustedCert;
        X509Name               workingIssuerName;
        AsymmetricKeyParameter asymmetricKeyParameter;

        try
        {
            if (x509Certificate != null)
            {
                workingIssuerName      = x509Certificate.SubjectDN;
                asymmetricKeyParameter = x509Certificate.GetPublicKey();
            }
            else
            {
                workingIssuerName      = new X509Name(trustAnchor.CAName);
                asymmetricKeyParameter = trustAnchor.CAPublicKey;
            }
        }
        catch (ArgumentException cause)
        {
            throw new PkixCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", cause, certPath, -1);
        }
        try
        {
            PkixCertPathValidatorUtilities.GetAlgorithmIdentifier(asymmetricKeyParameter);
        }
        catch (PkixCertPathValidatorException cause2)
        {
            throw new PkixCertPathValidatorException("Algorithm identifier of public key of trust anchor could not be read.", cause2, certPath, -1);
        }
        int maxPathLength = count;
        X509CertStoreSelector targetCertConstraints = paramsPkix.GetTargetCertConstraints();

        if (targetCertConstraints != null && !targetCertConstraints.Match((X509Certificate)certificates[0]))
        {
            throw new PkixCertPathValidatorException("Target certificate in certification path does not match targetConstraints.", null, certPath, 0);
        }
        IList       certPathCheckers = paramsPkix.GetCertPathCheckers();
        IEnumerator enumerator       = certPathCheckers.GetEnumerator();

        while (enumerator.MoveNext())
        {
            ((PkixCertPathChecker)enumerator.Current).Init(forward: false);
        }
        X509Certificate x509Certificate2 = null;

        for (num = certificates.Count - 1; num >= 0; num--)
        {
            int num2 = count - num;
            x509Certificate2 = (X509Certificate)certificates[num];
            Rfc3280CertPathUtilities.ProcessCertA(certPath, paramsPkix, num, asymmetricKeyParameter, workingIssuerName, x509Certificate);
            Rfc3280CertPathUtilities.ProcessCertBC(certPath, num, nameConstraintValidator);
            pkixPolicyNode = Rfc3280CertPathUtilities.ProcessCertD(certPath, num, acceptablePolicies, pkixPolicyNode, array, inhibitAnyPolicy);
            pkixPolicyNode = Rfc3280CertPathUtilities.ProcessCertE(certPath, num, pkixPolicyNode);
            Rfc3280CertPathUtilities.ProcessCertF(certPath, num, pkixPolicyNode, explicitPolicy);
            if (num2 != count)
            {
                if (x509Certificate2 != null && x509Certificate2.Version == 1)
                {
                    throw new PkixCertPathValidatorException("Version 1 certificates can't be used as CA ones.", null, certPath, num);
                }
                Rfc3280CertPathUtilities.PrepareNextCertA(certPath, num);
                pkixPolicyNode = Rfc3280CertPathUtilities.PrepareCertB(certPath, num, array, pkixPolicyNode, policyMapping);
                Rfc3280CertPathUtilities.PrepareNextCertG(certPath, num, nameConstraintValidator);
                explicitPolicy   = Rfc3280CertPathUtilities.PrepareNextCertH1(certPath, num, explicitPolicy);
                policyMapping    = Rfc3280CertPathUtilities.PrepareNextCertH2(certPath, num, policyMapping);
                inhibitAnyPolicy = Rfc3280CertPathUtilities.PrepareNextCertH3(certPath, num, inhibitAnyPolicy);
                explicitPolicy   = Rfc3280CertPathUtilities.PrepareNextCertI1(certPath, num, explicitPolicy);
                policyMapping    = Rfc3280CertPathUtilities.PrepareNextCertI2(certPath, num, policyMapping);
                inhibitAnyPolicy = Rfc3280CertPathUtilities.PrepareNextCertJ(certPath, num, inhibitAnyPolicy);
                Rfc3280CertPathUtilities.PrepareNextCertK(certPath, num);
                maxPathLength = Rfc3280CertPathUtilities.PrepareNextCertL(certPath, num, maxPathLength);
                maxPathLength = Rfc3280CertPathUtilities.PrepareNextCertM(certPath, num, maxPathLength);
                Rfc3280CertPathUtilities.PrepareNextCertN(certPath, num);
                ISet criticalExtensionOids = x509Certificate2.GetCriticalExtensionOids();
                if (criticalExtensionOids != null)
                {
                    criticalExtensionOids = new HashSet(criticalExtensionOids);
                    criticalExtensionOids.Remove(X509Extensions.KeyUsage.Id);
                    criticalExtensionOids.Remove(X509Extensions.CertificatePolicies.Id);
                    criticalExtensionOids.Remove(X509Extensions.PolicyMappings.Id);
                    criticalExtensionOids.Remove(X509Extensions.InhibitAnyPolicy.Id);
                    criticalExtensionOids.Remove(X509Extensions.IssuingDistributionPoint.Id);
                    criticalExtensionOids.Remove(X509Extensions.DeltaCrlIndicator.Id);
                    criticalExtensionOids.Remove(X509Extensions.PolicyConstraints.Id);
                    criticalExtensionOids.Remove(X509Extensions.BasicConstraints.Id);
                    criticalExtensionOids.Remove(X509Extensions.SubjectAlternativeName.Id);
                    criticalExtensionOids.Remove(X509Extensions.NameConstraints.Id);
                }
                else
                {
                    criticalExtensionOids = new HashSet();
                }
                Rfc3280CertPathUtilities.PrepareNextCertO(certPath, num, criticalExtensionOids, certPathCheckers);
                x509Certificate   = x509Certificate2;
                workingIssuerName = x509Certificate.SubjectDN;
                try
                {
                    asymmetricKeyParameter = PkixCertPathValidatorUtilities.GetNextWorkingKey(certPath.Certificates, num);
                }
                catch (PkixCertPathValidatorException cause3)
                {
                    throw new PkixCertPathValidatorException("Next working key could not be retrieved.", cause3, certPath, num);
                }
                PkixCertPathValidatorUtilities.GetAlgorithmIdentifier(asymmetricKeyParameter);
            }
        }
        explicitPolicy = Rfc3280CertPathUtilities.WrapupCertA(explicitPolicy, x509Certificate2);
        explicitPolicy = Rfc3280CertPathUtilities.WrapupCertB(certPath, num + 1, explicitPolicy);
        ISet criticalExtensionOids2 = x509Certificate2.GetCriticalExtensionOids();

        if (criticalExtensionOids2 != null)
        {
            criticalExtensionOids2 = new HashSet(criticalExtensionOids2);
            criticalExtensionOids2.Remove(X509Extensions.KeyUsage.Id);
            criticalExtensionOids2.Remove(X509Extensions.CertificatePolicies.Id);
            criticalExtensionOids2.Remove(X509Extensions.PolicyMappings.Id);
            criticalExtensionOids2.Remove(X509Extensions.InhibitAnyPolicy.Id);
            criticalExtensionOids2.Remove(X509Extensions.IssuingDistributionPoint.Id);
            criticalExtensionOids2.Remove(X509Extensions.DeltaCrlIndicator.Id);
            criticalExtensionOids2.Remove(X509Extensions.PolicyConstraints.Id);
            criticalExtensionOids2.Remove(X509Extensions.BasicConstraints.Id);
            criticalExtensionOids2.Remove(X509Extensions.SubjectAlternativeName.Id);
            criticalExtensionOids2.Remove(X509Extensions.NameConstraints.Id);
            criticalExtensionOids2.Remove(X509Extensions.CrlDistributionPoints.Id);
        }
        else
        {
            criticalExtensionOids2 = new HashSet();
        }
        Rfc3280CertPathUtilities.WrapupCertF(certPath, num + 1, certPathCheckers, criticalExtensionOids2);
        PkixPolicyNode pkixPolicyNode2 = Rfc3280CertPathUtilities.WrapupCertG(certPath, paramsPkix, initialPolicies, num + 1, array, pkixPolicyNode, acceptablePolicies);

        if (explicitPolicy > 0 || pkixPolicyNode2 != null)
        {
            return(new PkixCertPathValidatorResult(trustAnchor, pkixPolicyNode2, x509Certificate2.GetPublicKey()));
        }
        throw new PkixCertPathValidatorException("Path processing failed on policy.", null, certPath, num);
    }
Exemple #14
0
        private void v0Test()
        {
            // create certificates and CRLs
            IAsymmetricCipherKeyPair rootPair  = TestUtilities.GenerateRsaKeyPair();
            IAsymmetricCipherKeyPair interPair = TestUtilities.GenerateRsaKeyPair();
            IAsymmetricCipherKeyPair endPair   = TestUtilities.GenerateRsaKeyPair();

            X509Certificate rootCert  = TestUtilities.GenerateRootCert(rootPair);
            X509Certificate interCert = TestUtilities.GenerateIntermediateCert(interPair.Public, rootPair.Private, rootCert);
            X509Certificate endCert   = TestUtilities.GenerateEndEntityCert(endPair.Public, interPair.Private, interCert);

            IBigInteger revokedSerialNumber = BigInteger.Two;
            X509Crl     rootCRL             = TestUtilities.CreateCrl(rootCert, rootPair.Private, revokedSerialNumber);
            X509Crl     interCRL            = TestUtilities.CreateCrl(interCert, interPair.Private, revokedSerialNumber);

            // create CertStore to support path building
            IList certList = new ArrayList();

            certList.Add(rootCert);
            certList.Add(interCert);
            certList.Add(endCert);

            IList crlList = new ArrayList();

            crlList.Add(rootCRL);
            crlList.Add(interCRL);

//			CollectionCertStoreParameters parameters = new CollectionCertStoreParameters(list);
//			CertStore                     store = CertStore.getInstance("Collection", parameters);
            IX509Store x509CertStore = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));
            IX509Store x509CrlStore = X509StoreFactory.Create(
                "CRL/Collection",
                new X509CollectionStoreParameters(crlList));

            ISet trust = new HashSet();

            trust.Add(new TrustAnchor(rootCert, null));

            // build the path
//			CertPathBuilder  builder = CertPathBuilder.getInstance("PKIX", "BC");
            PkixCertPathBuilder   builder         = new PkixCertPathBuilder();
            X509CertStoreSelector pathConstraints = new X509CertStoreSelector();

            pathConstraints.Subject = endCert.SubjectDN;

            PkixBuilderParameters buildParams = new PkixBuilderParameters(trust, pathConstraints);

//			buildParams.addCertStore(store);
            buildParams.AddStore(x509CertStore);
            buildParams.AddStore(x509CrlStore);

            buildParams.Date = new DateTimeObject(DateTime.UtcNow);

            PkixCertPathBuilderResult result = builder.Build(buildParams);
            PkixCertPath path = result.CertPath;

            if (path.Certificates.Count != 2)
            {
                Fail("wrong number of certs in v0Test path");
            }
        }
    private PkixCertPathBuilderResult Build(IX509AttributeCertificate attrCert, X509Certificate tbvCert, PkixBuilderParameters pkixParams, IList tbvPath)
    {
        if (tbvPath.Contains(tbvCert))
        {
            return(null);
        }
        if (pkixParams.GetExcludedCerts().Contains(tbvCert))
        {
            return(null);
        }
        if (pkixParams.MaxPathLength != -1 && tbvPath.Count - 1 > pkixParams.MaxPathLength)
        {
            return(null);
        }
        tbvPath.Add(tbvCert);
        PkixCertPathBuilderResult pkixCertPathBuilderResult = null;
        PkixAttrCertPathValidator pkixAttrCertPathValidator = new PkixAttrCertPathValidator();

        try
        {
            if (PkixCertPathValidatorUtilities.FindTrustAnchor(tbvCert, pkixParams.GetTrustAnchors()) != null)
            {
                PkixCertPath certPath = new PkixCertPath(tbvPath);
                PkixCertPathValidatorResult pkixCertPathValidatorResult;
                try
                {
                    pkixCertPathValidatorResult = pkixAttrCertPathValidator.Validate(certPath, pkixParams);
                }
                catch (Exception innerException)
                {
                    throw new Exception("Certification path could not be validated.", innerException);
                }
                return(new PkixCertPathBuilderResult(certPath, pkixCertPathValidatorResult.TrustAnchor, pkixCertPathValidatorResult.PolicyTree, pkixCertPathValidatorResult.SubjectPublicKey));
            }
            try
            {
                PkixCertPathValidatorUtilities.AddAdditionalStoresFromAltNames(tbvCert, pkixParams);
            }
            catch (CertificateParsingException innerException2)
            {
                throw new Exception("No additional X.509 stores can be added from certificate locations.", innerException2);
            }
            ISet set = new HashSet();
            try
            {
                set.AddAll(PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams));
            }
            catch (Exception innerException3)
            {
                throw new Exception("Cannot find issuer certificate for certificate in certification path.", innerException3);
            }
            if (set.IsEmpty)
            {
                throw new Exception("No issuer certificate for certificate in certification path found.");
            }
            foreach (X509Certificate item in set)
            {
                if (!PkixCertPathValidatorUtilities.IsSelfIssued(item))
                {
                    pkixCertPathBuilderResult = Build(attrCert, item, pkixParams, tbvPath);
                    if (pkixCertPathBuilderResult != null)
                    {
                        break;
                    }
                }
            }
        }
        catch (Exception innerException4)
        {
            certPathException = new Exception("No valid certification path could be build.", innerException4);
        }
        if (pkixCertPathBuilderResult == null)
        {
            tbvPath.Remove(tbvCert);
        }
        return(pkixCertPathBuilderResult);
    }
        public override void PerformTest()
        {
            X509CertificateParser certParser = new X509CertificateParser();
            X509CrlParser         crlParser  = new X509CrlParser();

            // initialise CertStore
            X509Certificate rootCert  = certParser.ReadCertificate(CertPathTest.rootCertBin);
            X509Certificate interCert = certParser.ReadCertificate(CertPathTest.interCertBin);
            X509Certificate finalCert = certParser.ReadCertificate(CertPathTest.finalCertBin);
            X509Crl         rootCrl   = crlParser.ReadCrl(CertPathTest.rootCrlBin);
            X509Crl         interCrl  = crlParser.ReadCrl(CertPathTest.interCrlBin);

            IList x509Certs = new ArrayList();

            x509Certs.Add(rootCert);
            x509Certs.Add(interCert);
            x509Certs.Add(finalCert);

            IList x509Crls = new ArrayList();

            x509Crls.Add(rootCrl);
            x509Crls.Add(interCrl);

//			CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list);
//			CertStore store = CertStore.GetInstance("Collection", ccsp);
//			X509CollectionStoreParameters ccsp = new X509CollectionStoreParameters(list);
            IX509Store x509CertStore = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(x509Certs));
            IX509Store x509CrlStore = X509StoreFactory.Create(
                "CRL/Collection",
                new X509CollectionStoreParameters(x509Crls));

            // NB: Month is 1-based in .NET
            //DateTime validDate = new DateTime(2008,9,4,14,49,10).ToUniversalTime();
            DateTime validDate = new DateTime(2008, 9, 4, 5, 49, 10);

            //validating path
            IList certchain = new ArrayList();

            certchain.Add(finalCert);
            certchain.Add(interCert);

//			CertPath cp = CertificateFactory.GetInstance("X.509").GenerateCertPath(certchain);
            PkixCertPath cp    = new PkixCertPath(certchain);
            ISet         trust = new HashSet();

            trust.Add(new TrustAnchor(rootCert, null));

//			CertPathValidator cpv = CertPathValidator.GetInstance("PKIX");
            PkixCertPathValidator cpv   = new PkixCertPathValidator();
            PkixParameters        param = new PkixParameters(trust);

            param.AddStore(x509CertStore);
            param.AddStore(x509CrlStore);
            param.Date = new DateTimeObject(validDate);
            MyChecker checker = new MyChecker();

            param.AddCertPathChecker(checker);

            PkixCertPathValidatorResult result      = (PkixCertPathValidatorResult)cpv.Validate(cp, param);
            PkixPolicyNode         policyTree       = result.PolicyTree;
            AsymmetricKeyParameter subjectPublicKey = result.SubjectPublicKey;

            if (checker.GetCount() != 2)
            {
                Fail("checker not evaluated for each certificate");
            }

            if (!subjectPublicKey.Equals(finalCert.GetPublicKey()))
            {
                Fail("wrong public key returned");
            }

            IsTrue(result.TrustAnchor.TrustedCert.Equals(rootCert));

            // try a path with trust anchor included.
            certchain.Clear();
            certchain.Add(finalCert);
            certchain.Add(interCert);
            certchain.Add(rootCert);

            cp = new PkixCertPath(certchain);

            cpv   = new PkixCertPathValidator();
            param = new PkixParameters(trust);
            param.AddStore(x509CertStore);
            param.AddStore(x509CrlStore);
            param.Date = new DateTimeObject(validDate);
            checker    = new MyChecker();
            param.AddCertPathChecker(checker);

            result = (PkixCertPathValidatorResult)cpv.Validate(cp, param);

            IsTrue(result.TrustAnchor.TrustedCert.Equals(rootCert));

            //
            // invalid path containing a valid one test
            //
            try
            {
                // initialise CertStore
                rootCert  = certParser.ReadCertificate(AC_RAIZ_ICPBRASIL);
                interCert = certParser.ReadCertificate(AC_PR);
                finalCert = certParser.ReadCertificate(schefer);

                x509Certs = new ArrayList();
                x509Certs.Add(rootCert);
                x509Certs.Add(interCert);
                x509Certs.Add(finalCert);

//				ccsp = new CollectionCertStoreParameters(list);
//				store = CertStore.GetInstance("Collection", ccsp);
//				ccsp = new X509CollectionStoreParameters(list);
                x509CertStore = X509StoreFactory.Create(
                    "Certificate/Collection",
                    new X509CollectionStoreParameters(x509Certs));

                // NB: Month is 1-based in .NET
                //validDate = new DateTime(2004,3,21,2,21,10).ToUniversalTime();
                validDate = new DateTime(2004, 3, 20, 19, 21, 10);

                //validating path
                certchain = new ArrayList();
                certchain.Add(finalCert);
                certchain.Add(interCert);

//				cp = CertificateFactory.GetInstance("X.509").GenerateCertPath(certchain);
                cp    = new PkixCertPath(certchain);
                trust = new HashSet();
                trust.Add(new TrustAnchor(rootCert, null));

//				cpv = CertPathValidator.GetInstance("PKIX");
                cpv   = new PkixCertPathValidator();
                param = new PkixParameters(trust);
                param.AddStore(x509CertStore);
                param.IsRevocationEnabled = false;
                param.Date = new DateTimeObject(validDate);

                result           = (PkixCertPathValidatorResult)cpv.Validate(cp, param);
                policyTree       = result.PolicyTree;
                subjectPublicKey = result.SubjectPublicKey;

                Fail("Invalid path validated");
            }
            catch (Exception e)
            {
                if (e is PkixCertPathValidatorException &&
                    e.Message.StartsWith("Could not validate certificate signature."))
                {
                    return;
                }
                Fail("unexpected exception", e);
            }
        }
 public abstract void Check(IX509AttributeCertificate attrCert, PkixCertPath certPath, PkixCertPath holderCertPath, ICollection unresolvedCritExts);
Exemple #18
0
        public override void PerformTest()
        {
            X509CertificateParser cf = new X509CertificateParser();

            X509Certificate rootCert  = cf.ReadCertificate(rootCertBin);
            X509Certificate interCert = cf.ReadCertificate(interCertBin);
            X509Certificate finalCert = cf.ReadCertificate(finalCertBin);

            //Testing CertPath generation from List
            IList list = new ArrayList();

            list.Add(interCert);
//			CertPath certPath1 = cf.generateCertPath(list);
            PkixCertPath certPath1 = new PkixCertPath(list);

            //Testing CertPath encoding as PkiPath
            byte[] encoded = certPath1.GetEncoded("PkiPath");

            //Testing CertPath generation from InputStream
            MemoryStream inStream = new MemoryStream(encoded, false);
//			CertPath certPath2 = cf.generateCertPath(inStream, "PkiPath");
            PkixCertPath certPath2 = new PkixCertPath(inStream, "PkiPath");

            //Comparing both CertPathes
            if (!certPath2.Equals(certPath1))
            {
                Fail("CertPath differ after encoding and decoding.");
            }

            encoded = certPath1.GetEncoded("PKCS7");

            //Testing CertPath generation from InputStream
            inStream = new MemoryStream(encoded, false);
//			certPath2 = cf.generateCertPath(inStream, "PKCS7");
            certPath2 = new PkixCertPath(inStream, "PKCS7");

            //Comparing both CertPathes
            if (!certPath2.Equals(certPath1))
            {
                Fail("CertPath differ after encoding and decoding.");
            }

            encoded = certPath1.GetEncoded("PEM");

            //Testing CertPath generation from InputStream
            inStream = new MemoryStream(encoded, false);
//			certPath2 = cf.generateCertPath(inStream, "PEM");
            certPath2 = new PkixCertPath(inStream, "PEM");

            //Comparing both CertPathes
            if (!certPath2.Equals(certPath1))
            {
                Fail("CertPath differ after encoding and decoding.");
            }

            //
            // empty list test
            //
            list = new ArrayList();

//			CertPath certPath = CertificateFactory.GetInstance("X.509","BC").generateCertPath(list);
            PkixCertPath certPath = new PkixCertPath(list);

            if (certPath.Certificates.Count != 0)
            {
                Fail("list wrong size.");
            }

            //
            // exception tests
            //
            doTestExceptions();
        }
Exemple #19
0
        private void doTestExceptions()
        {
            byte[] enc = { (byte)0, (byte)2, (byte)3, (byte)4, (byte)5 };
//			MyCertPath mc = new MyCertPath(enc);
            MemoryStream os = new MemoryStream();
            MemoryStream ins;

            byte[] arr;

            // TODO Support serialization of cert paths?
//			ObjectOutputStream oos = new ObjectOutputStream(os);
//			oos.WriteObject(mc);
//			oos.Flush();
//			oos.Close();

            try
            {
//				CertificateFactory cFac = CertificateFactory.GetInstance("X.509");
                arr = os.ToArray();
                ins = new MemoryStream(arr, false);
//				cFac.generateCertPath(ins);
                new PkixCertPath(ins);
            }
            catch (CertificateException)
            {
                // ignore okay
            }

//			CertificateFactory cf = CertificateFactory.GetInstance("X.509");
            X509CertificateParser cf = new X509CertificateParser();
            IList certCol            = new ArrayList();

            certCol.Add(cf.ReadCertificate(certA));
            certCol.Add(cf.ReadCertificate(certB));
            certCol.Add(cf.ReadCertificate(certC));
            certCol.Add(cf.ReadCertificate(certD));

//			CertPathBuilder pathBuilder = CertPathBuilder.GetInstance("PKIX");
            PkixCertPathBuilder   pathBuilder = new PkixCertPathBuilder();
            X509CertStoreSelector select      = new X509CertStoreSelector();

            select.Subject = ((X509Certificate)certCol[0]).SubjectDN;

            ISet trustanchors = new HashSet();

            trustanchors.Add(new TrustAnchor(cf.ReadCertificate(rootCertBin), null));

//			CertStore certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certCol));
            IX509Store x509CertStore = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certCol));

            PkixBuilderParameters parameters = new PkixBuilderParameters(trustanchors, select);

            parameters.AddStore(x509CertStore);

            try
            {
                PkixCertPathBuilderResult result = pathBuilder.Build(parameters);
                PkixCertPath path = result.CertPath;
                Fail("found cert path in circular set");
            }
            catch (PkixCertPathBuilderException)
            {
                // expected
            }
        }