private X509CertPairStoreSelector(
			X509CertPairStoreSelector o)
		{
			this.certPair = o.CertPair;
			this.forwardSelector = o.ForwardSelector;
			this.reverseSelector = o.ReverseSelector;
		}
        private static X509Certificate GetCertificate(SignerInformation signer, IX509Store cmsCertificates)
        {
            X509Certificate cert = null;

            // Create a selector with the information necessary to
            // find the signer certificate
            X509CertStoreSelector sel = new X509CertStoreSelector();
            sel.Issuer = signer.SignerID.Issuer;
            sel.SerialNumber = signer.SignerID.SerialNumber;

            // Try find a match
            IList certificatesFound = new ArrayList( cmsCertificates.GetMatches(sel) );

            if (certificatesFound.Count > 0) // Match found
            {
                // Load certificate from CMS

                Console.WriteLine("Loading signer's certificate from CMS...");

                cert = (X509Certificate)certificatesFound[0];
            }
            else
            {
                // Load certificate from file

                Console.WriteLine("Loading signer's certificate from file...");

                ReadCertificate("..\\..\\example.cer");
            }
            return cert;
        }
		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();
            DateTime validDate = new DateTime(2008, 9, 4, 5, 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");
			}
		}
Example #4
0
 public X509CertStoreSelector(X509CertStoreSelector o)
 {
     authorityKeyIdentifier = o.AuthorityKeyIdentifier;
     basicConstraints       = o.BasicConstraints;
     certificate            = o.Certificate;
     certificateValid       = o.CertificateValid;
     extendedKeyUsage       = o.ExtendedKeyUsage;
     issuer                = o.Issuer;
     keyUsage              = o.KeyUsage;
     policy                = o.Policy;
     privateKeyValid       = o.PrivateKeyValid;
     serialNumber          = o.SerialNumber;
     subject               = o.Subject;
     subjectKeyIdentifier  = o.SubjectKeyIdentifier;
     subjectPublicKey      = o.SubjectPublicKey;
     subjectPublicKeyAlgID = o.SubjectPublicKeyAlgID;
 }
 public X509CertStoreSelector(X509CertStoreSelector o)
 {
     this.authorityKeyIdentifier = o.AuthorityKeyIdentifier;
     this.basicConstraints       = o.BasicConstraints;
     this.certificate            = o.Certificate;
     this.certificateValid       = o.CertificateValid;
     this.extendedKeyUsage       = o.ExtendedKeyUsage;
     this.issuer                = o.Issuer;
     this.keyUsage              = o.KeyUsage;
     this.policy                = o.Policy;
     this.privateKeyValid       = o.PrivateKeyValid;
     this.serialNumber          = o.SerialNumber;
     this.subject               = o.Subject;
     this.subjectKeyIdentifier  = o.SubjectKeyIdentifier;
     this.subjectPublicKey      = o.SubjectPublicKey;
     this.subjectPublicKeyAlgID = o.SubjectPublicKeyAlgID;
 }
		public X509CertStoreSelector(
			X509CertStoreSelector o)
		{
			this.authorityKeyIdentifier = o.AuthorityKeyIdentifier;
			this.basicConstraints = o.BasicConstraints;
			this.certificate = o.Certificate;
			this.certificateValid = o.CertificateValid;
			this.extendedKeyUsage = o.ExtendedKeyUsage;
			this.issuer = o.Issuer;
			this.keyUsage = o.KeyUsage;
			this.policy = o.Policy;
			this.privateKeyValid = o.PrivateKeyValid;
			this.serialNumber = o.SerialNumber;
			this.subject = o.Subject;
			this.subjectKeyIdentifier = o.SubjectKeyIdentifier;
			this.subjectPublicKey = o.SubjectPublicKey;
			this.subjectPublicKeyAlgID = o.SubjectPublicKeyAlgID;
		}
Example #7
0
		private void certPairTest()
		{
			X509CertificateParser certParser = new X509CertificateParser();

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

			// Testing CollectionCertStore generation from List
			X509CertificatePair pair1 = new X509CertificatePair(rootCert, interCert);

			IList certList = new ArrayList();
			certList.Add(pair1);
			certList.Add(new X509CertificatePair(interCert, finalCert));

			IX509Store certStore = X509StoreFactory.Create(
				"CertificatePair/Collection",
				new X509CollectionStoreParameters(certList));

			X509CertPairStoreSelector selector = new X509CertPairStoreSelector();
			X509CertStoreSelector fwSelector = new X509CertStoreSelector();

			fwSelector.SerialNumber = rootCert.SerialNumber;
			fwSelector.Subject = rootCert.IssuerDN;

			selector.ForwardSelector = fwSelector;

			IList col = new ArrayList(certStore.GetMatches(selector));

			if (col.Count != 1 || !col.Contains(pair1))
			{
				Fail("failed pair1 test");
			}

			col = new ArrayList(certStore.GetMatches(null));

			if (col.Count != 2)
			{
				Fail("failed null test");
			}
		}
 private static X509CertStoreSelector CloneSelector(
     X509CertStoreSelector s)
 {
     return(s == null ? null : (X509CertStoreSelector)s.Clone());
 }
Example #9
0
		public override void PerformTest()
		{
			X509CertificateParser certParser = new X509CertificateParser();
			X509CrlParser crlParser = new X509CrlParser();

			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);

			// Testing CollectionCertStore generation from List
			IList certList = new ArrayList();
			certList.Add(rootCert);
			certList.Add(interCert);
			certList.Add(finalCert);

			IX509Store certStore = X509StoreFactory.Create(
				"Certificate/Collection",
				new X509CollectionStoreParameters(certList));

			// set default to be the same as for SUN X500 name
			X509Name.DefaultReverse = true;

			// Searching for rootCert by subjectDN

			X509CertStoreSelector targetConstraints = new X509CertStoreSelector();
			targetConstraints.Subject = PrincipalUtilities.GetSubjectX509Principal(rootCert);
			IList certs = new ArrayList(certStore.GetMatches(targetConstraints));
			if (certs.Count != 1 || !certs.Contains(rootCert))
			{
				Fail("rootCert not found by subjectDN");
			}

			// Searching for rootCert by subjectDN encoded as byte
			targetConstraints = new X509CertStoreSelector();
			targetConstraints.Subject = PrincipalUtilities.GetSubjectX509Principal(rootCert);
			certs = new ArrayList(certStore.GetMatches(targetConstraints));
			if (certs.Count != 1 || !certs.Contains(rootCert))
			{
				Fail("rootCert not found by encoded subjectDN");
			}

			X509Name.DefaultReverse = false;

			// Searching for rootCert by public key encoded as byte
			targetConstraints = new X509CertStoreSelector();
			targetConstraints.SubjectPublicKey =
				SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(rootCert.GetPublicKey());
			certs = new ArrayList(certStore.GetMatches(targetConstraints));
			if (certs.Count != 1 || !certs.Contains(rootCert))
			{
				Fail("rootCert not found by encoded public key");
			}

			// Searching for interCert by issuerDN
			targetConstraints = new X509CertStoreSelector();
			targetConstraints.Issuer = PrincipalUtilities.GetSubjectX509Principal(rootCert);
			certs = new ArrayList(certStore.GetMatches(targetConstraints));
			if (certs.Count != 2)
			{
				Fail("did not found 2 certs");
			}
			if (!certs.Contains(rootCert))
			{
				Fail("rootCert not found");
			}
			if (!certs.Contains(interCert))
			{
				Fail("interCert not found");
			}

			// Searching for rootCrl by issuerDN
			IList crlList = new ArrayList();
			crlList.Add(rootCrl);
			crlList.Add(interCrl);
			IX509Store store = X509StoreFactory.Create(
				"CRL/Collection",
				new X509CollectionStoreParameters(crlList));

			X509CrlStoreSelector targetConstraintsCRL = new X509CrlStoreSelector();

			ArrayList issuers = new ArrayList();
			issuers.Add(rootCrl.IssuerDN);
			targetConstraintsCRL.Issuers = issuers;

			IList crls = new ArrayList(store.GetMatches(targetConstraintsCRL));
			if (crls.Count != 1 || !crls.Contains(rootCrl))
			{
				Fail("rootCrl not found");
			}

			crls = new ArrayList(certStore.GetMatches(targetConstraintsCRL));
			if (crls.Count != 0)
			{
				Fail("error using wrong selector (CRL)");
			}
			certs = new ArrayList(store.GetMatches(targetConstraints));
			if (certs.Count != 0)
			{
				Fail("error using wrong selector (certs)");
			}
			// Searching for attribute certificates
			X509V2AttributeCertificate attrCert = new X509V2AttributeCertificate(AttrCertTest.attrCert);
			IX509AttributeCertificate attrCert2 = new X509V2AttributeCertificate(AttrCertTest.certWithBaseCertificateID);

			IList attrList = new ArrayList();
			attrList.Add(attrCert);
			attrList.Add(attrCert2);
			store = X509StoreFactory.Create(
				"AttributeCertificate/Collection",
				new X509CollectionStoreParameters(attrList));

			X509AttrCertStoreSelector attrSelector = new X509AttrCertStoreSelector();
			attrSelector.Holder = attrCert.Holder;
			if (!attrSelector.Holder.Equals(attrCert.Holder))
			{
				Fail("holder get not correct");
			}
			IList attrs = new ArrayList(store.GetMatches(attrSelector));
			if (attrs.Count != 1 || !attrs.Contains(attrCert))
			{
				Fail("attrCert not found on holder");
			}
			attrSelector.Holder = attrCert2.Holder;
			if (attrSelector.Holder.Equals(attrCert.Holder))
			{
				Fail("holder get not correct");
			}
			attrs = new ArrayList(store.GetMatches(attrSelector));
			if (attrs.Count != 1 || !attrs.Contains(attrCert2))
			{
				Fail("attrCert2 not found on holder");
			}
			attrSelector = new X509AttrCertStoreSelector();
			attrSelector.Issuer = attrCert.Issuer;
			if (!attrSelector.Issuer.Equals(attrCert.Issuer))
			{
				Fail("issuer get not correct");
			}
			attrs = new ArrayList(store.GetMatches(attrSelector));
			if (attrs.Count != 1 || !attrs.Contains(attrCert))
			{
				Fail("attrCert not found on issuer");
			}
			attrSelector.Issuer = attrCert2.Issuer;
			if (attrSelector.Issuer.Equals(attrCert.Issuer))
			{
				Fail("issuer get not correct");
			}
			attrs = new ArrayList(store.GetMatches(attrSelector));
			if (attrs.Count != 1 || !attrs.Contains(attrCert2))
			{
				Fail("attrCert2 not found on issuer");
			}
			attrSelector = new X509AttrCertStoreSelector();
			attrSelector.AttributeCert = attrCert;
			if (!attrSelector.AttributeCert.Equals(attrCert))
			{
				Fail("attrCert get not correct");
			}
			attrs = new ArrayList(store.GetMatches(attrSelector));
			if (attrs.Count != 1 || !attrs.Contains(attrCert))
			{
				Fail("attrCert not found on attrCert");
			}
			attrSelector = new X509AttrCertStoreSelector();
			attrSelector.SerialNumber = attrCert.SerialNumber;
			if (!attrSelector.SerialNumber.Equals(attrCert.SerialNumber))
			{
				Fail("serial number get not correct");
			}
			attrs = new ArrayList(store.GetMatches(attrSelector));
			if (attrs.Count != 1 || !attrs.Contains(attrCert))
			{
				Fail("attrCert not found on serial number");
			}
			attrSelector = (X509AttrCertStoreSelector)attrSelector.Clone();
			if (!attrSelector.SerialNumber.Equals(attrCert.SerialNumber))
			{
				Fail("serial number get not correct");
			}
			attrs = new ArrayList(store.GetMatches(attrSelector));
			if (attrs.Count != 1 || !attrs.Contains(attrCert))
			{
				Fail("attrCert not found on serial number");
			}

			attrSelector = new X509AttrCertStoreSelector();
			attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotBefore);
			if (attrSelector.AttributeCertificateValid.Value != attrCert.NotBefore)
			{
				Fail("valid get not correct");
			}
			attrs = new ArrayList(store.GetMatches(attrSelector));
			if (attrs.Count != 1 || !attrs.Contains(attrCert))
			{
				Fail("attrCert not found on valid");
			}
			attrSelector = new X509AttrCertStoreSelector();
			attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotBefore.AddMilliseconds(-100));
			attrs = new ArrayList(store.GetMatches(attrSelector));
			if (attrs.Count != 0)
			{
				Fail("attrCert found on before");
			}
			attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotAfter.AddMilliseconds(100));
			attrs = new ArrayList(store.GetMatches(attrSelector));
			if (attrs.Count != 0)
			{
				Fail("attrCert found on after");
			}
			attrSelector.SerialNumber = BigInteger.ValueOf(10000);
			attrs = new ArrayList(store.GetMatches(attrSelector));
			if (attrs.Count != 0)
			{
				Fail("attrCert found on wrong serial number");
			}

			attrSelector.AttributeCert = null;
			attrSelector.AttributeCertificateValid = null;
			attrSelector.Holder = null;
			attrSelector.Issuer = null;
			attrSelector.SerialNumber = null;
			if (attrSelector.AttributeCert != null)
			{
				Fail("null attrCert");
			}
			if (attrSelector.AttributeCertificateValid != null)
			{
				Fail("null attrCertValid");
			}
			if (attrSelector.Holder != null)
			{
				Fail("null attrCert holder");
			}
			if (attrSelector.Issuer != null)
			{
				Fail("null attrCert issuer");
			}
			if (attrSelector.SerialNumber != null)
			{
				Fail("null attrCert serial");
			}

			attrs = new ArrayList(certStore.GetMatches(attrSelector));
			if (attrs.Count != 0)
			{
				Fail("error using wrong selector (attrs)");
			}

			certPairTest();
		}
Example #10
0
        //jbonilla - Por algún motivo, no devuleve el certificado root.
        public static X509Certificate[] BuildCertificateChainBC(X509Certificate checkCert, ICollection<X509Certificate> keystore)
        {
            PkixCertPathBuilder builder = new PkixCertPathBuilder();

            // Separate root from itermediate
            List<X509Certificate> intermediateCerts = new List<X509Certificate>();
            HashSet rootCerts = new HashSet();

            foreach (X509Certificate cert in keystore)
            {
                // Separate root and subordinate certificates
                if (IsSelfSigned(cert))
                    rootCerts.Add(new TrustAnchor(cert, null));
                else
                    intermediateCerts.Add(cert);
            }

            // Create chain for this certificate
            X509CertStoreSelector holder = new X509CertStoreSelector();
            holder.Certificate = checkCert;

            // WITHOUT THIS LINE BUILDER CANNOT BEGIN BUILDING THE CHAIN
            intermediateCerts.Add(holder.Certificate);

            PkixBuilderParameters builderParams = new PkixBuilderParameters(rootCerts, holder);
            builderParams.IsRevocationEnabled = false;

            X509CollectionStoreParameters intermediateStoreParameters =
                new X509CollectionStoreParameters(intermediateCerts);

            builderParams.AddStore(X509StoreFactory.Create(
                "Certificate/Collection", intermediateStoreParameters));

            PkixCertPathBuilderResult result = builder.Build(builderParams);            

            List<X509Certificate> chain = new List<X509Certificate>();

            foreach(X509Certificate cert in result.CertPath.Certificates)
            {
                chain.Add(cert);
            }           

            return chain.ToArray();
        }
        PkixCertPath BuildCertPath(HashSet anchors, IX509Store certificates, IX509Store crls, X509Certificate certificate, DateTime? signingTime)
        {
            var intermediate = new X509CertificateStore ();
            foreach (X509Certificate cert in certificates.GetMatches (null))
                intermediate.Add (cert);

            var selector = new X509CertStoreSelector ();
            selector.Certificate = certificate;

            var parameters = new PkixBuilderParameters (anchors, selector);
            parameters.AddStore (GetIntermediateCertificates ());
            parameters.AddStore (intermediate);

            var localCrls = GetCertificateRevocationLists ();
            parameters.AddStore (localCrls);
            parameters.AddStore (crls);

            // Note: we disable revocation unless we actually have non-empty revocation lists
            parameters.IsRevocationEnabled = localCrls.GetMatches (null).Count > 0;
            parameters.ValidityModel = PkixParameters.ChainValidityModel;

            if (signingTime.HasValue)
                parameters.Date = new DateTimeObject (signingTime.Value);

            var result = new PkixCertPathBuilder ().Build (parameters);

            return result.CertPath;
        }
		private static X509CertStoreSelector CloneSelector(
			X509CertStoreSelector s)
		{
			return s == null ? null : (X509CertStoreSelector) s.Clone();
		}
		/// <summary>
		/// Search the given Set of TrustAnchor's for one that is the
		/// issuer of the given X509 certificate.
		/// </summary>
		/// <param name="cert">the X509 certificate</param>
		/// <param name="trustAnchors">a Set of TrustAnchor's</param>
		/// <returns>the <code>TrustAnchor</code> object if found or
		/// <code>null</code> if not.
		/// </returns>
		/// @exception
		internal static TrustAnchor FindTrustAnchor(
			X509Certificate	cert,
			ISet			trustAnchors)
		{
			IEnumerator iter = trustAnchors.GetEnumerator();
			TrustAnchor trust = null;
			AsymmetricKeyParameter trustPublicKey = null;
			Exception invalidKeyEx = null;

			X509CertStoreSelector certSelectX509 = new X509CertStoreSelector();

			try
			{
				certSelectX509.Subject = GetIssuerPrincipal(cert);
			}
			catch (IOException ex)
			{
				throw new Exception("Cannot set subject search criteria for trust anchor.", ex);
			}

			while (iter.MoveNext() && trust == null)
			{
				trust = (TrustAnchor) iter.Current;
				if (trust.TrustedCert != null)
				{
					if (certSelectX509.Match(trust.TrustedCert))
					{
						trustPublicKey = trust.TrustedCert.GetPublicKey();
					}
					else
					{
						trust = null;
					}
				}
				else if (trust.CAName != null && trust.CAPublicKey != null)
				{
					try
					{
						X509Name certIssuer = GetIssuerPrincipal(cert);
						X509Name caName = new X509Name(trust.CAName);

						if (certIssuer.Equivalent(caName, true))
						{
							trustPublicKey = trust.CAPublicKey;
						}
						else
						{
							trust = null;
						}
					}
					catch (InvalidParameterException)
					{
						trust = null;
					}
				}
				else
				{
					trust = null;
				}

				if (trustPublicKey != null)
				{
					try
					{
						cert.Verify(trustPublicKey);
					}
					catch (Exception ex)
					{
						invalidKeyEx = ex;
						trust = null;
					}
				}
			}

			if (trust == null && invalidKeyEx != null)
			{
				throw new Exception("TrustAnchor found but certificate validation failed.", invalidKeyEx);
			}

			return trust;
		}
		/**
		* Searches for a holder public key certificate and verifies its
		* certification path.
		* 
		* @param attrCert the attribute certificate.
		* @param pkixParams The PKIX parameters.
		* @return The certificate path of the holder certificate.
		* @throws Exception if
		*             <ul>
		*             <li>no public key certificate can be found although holder
		*             information is given by an entity name or a base certificate
		*             ID</li>
		*             <li>support classes cannot be created</li>
		*             <li>no certification path for the public key certificate can
		*             be built</li>
		*             </ul>
		*/
		internal static PkixCertPath ProcessAttrCert1(
			IX509AttributeCertificate	attrCert,
			PkixParameters				pkixParams)
		{
			PkixCertPathBuilderResult result = null;
			// find holder PKCs
			ISet holderPKCs = new HashSet();
			if (attrCert.Holder.GetIssuer() != null)
			{
				X509CertStoreSelector selector = new X509CertStoreSelector();
				selector.SerialNumber = attrCert.Holder.SerialNumber;
				X509Name[] principals = attrCert.Holder.GetIssuer();
				for (int i = 0; i < principals.Length; i++)
				{
					try
					{
//						if (principals[i] is X500Principal)
						{
							selector.Issuer = principals[i];
						}
						holderPKCs.AddAll(PkixCertPathValidatorUtilities
							.FindCertificates(selector, pkixParams.GetStores()));
					}
					catch (Exception e)
					{
						throw new PkixCertPathValidatorException(
							"Public key certificate for attribute certificate cannot be searched.",
							e);
					}
				}
				if (holderPKCs.IsEmpty)
				{
					throw new PkixCertPathValidatorException(
						"Public key certificate specified in base certificate ID for attribute certificate cannot be found.");
				}
			}
			if (attrCert.Holder.GetEntityNames() != null)
			{
				X509CertStoreSelector selector = new X509CertStoreSelector();
				X509Name[] principals = attrCert.Holder.GetEntityNames();
				for (int i = 0; i < principals.Length; i++)
				{
					try
					{
//						if (principals[i] is X500Principal)
						{
							selector.Issuer = principals[i];
						}
						holderPKCs.AddAll(PkixCertPathValidatorUtilities
							.FindCertificates(selector, pkixParams.GetStores()));
					}
					catch (Exception e)
					{
						throw new PkixCertPathValidatorException(
							"Public key certificate for attribute certificate cannot be searched.",
							e);
					}
				}
				if (holderPKCs.IsEmpty)
				{
					throw new PkixCertPathValidatorException(
						"Public key certificate specified in entity name for attribute certificate cannot be found.");
				}
			}

			// verify cert paths for PKCs
			PkixBuilderParameters parameters = (PkixBuilderParameters)
				PkixBuilderParameters.GetInstance(pkixParams);

			PkixCertPathValidatorException lastException = null;
			foreach (X509Certificate cert in holderPKCs)
			{
				X509CertStoreSelector selector = new X509CertStoreSelector();
				selector.Certificate = cert;
				parameters.SetTargetConstraints(selector);

				PkixCertPathBuilder builder = new PkixCertPathBuilder();

				try
				{
					result = builder.Build(PkixBuilderParameters.GetInstance(parameters));
				}
				catch (PkixCertPathBuilderException e)
				{
					lastException = new PkixCertPathValidatorException(
						"Certification path for public key certificate of attribute certificate could not be build.",
						e);
				}
			}
			if (lastException != null)
			{
				throw lastException;
			}
			return result.CertPath;
		}
Example #15
0
 private X509CertPairStoreSelector(X509CertPairStoreSelector o)
 {
     this.certPair        = o.CertPair;
     this.forwardSelector = o.ForwardSelector;
     this.reverseSelector = o.ReverseSelector;
 }
		/**
		* Build and validate a CertPath using the given parameter.
		*
		* @param params PKIXBuilderParameters object containing all information to
		*            build the CertPath
		*/
		public virtual PkixCertPathBuilderResult Build(
			PkixBuilderParameters pkixParams)
		{
			// search target certificates

			IX509Selector certSelect = pkixParams.GetTargetConstraints();
			if (!(certSelect is X509AttrCertStoreSelector))
			{
				throw new PkixCertPathBuilderException(
					"TargetConstraints must be an instance of "
					+ typeof(X509AttrCertStoreSelector).FullName
					+ " for "
					+ typeof(PkixAttrCertPathBuilder).FullName + " class.");
			}

			ICollection targets;
			try
			{
				targets = PkixCertPathValidatorUtilities.FindCertificates(
					(X509AttrCertStoreSelector)certSelect, pkixParams.GetStores());
			}
			catch (Exception e)
			{
				throw new PkixCertPathBuilderException("Error finding target attribute certificate.", e);
			}

			if (targets.Count == 0)
			{
				throw new PkixCertPathBuilderException(
					"No attribute certificate found matching targetContraints.");
			}

			PkixCertPathBuilderResult result = null;

			// check all potential target certificates
			foreach (IX509AttributeCertificate cert in targets)
			{
				X509CertStoreSelector selector = new X509CertStoreSelector();
				X509Name[] principals = cert.Issuer.GetPrincipals();
				ISet issuers = new HashSet();
				for (int i = 0; i < principals.Length; i++)
				{
					try
					{
						selector.Subject = principals[i];

						issuers.AddAll(PkixCertPathValidatorUtilities.FindCertificates(selector, pkixParams.GetStores()));
					}
					catch (Exception e)
					{
						throw new PkixCertPathBuilderException(
							"Public key certificate for attribute certificate cannot be searched.",
							e);
					}
				}

				if (issuers.IsEmpty)
					throw new PkixCertPathBuilderException("Public key certificate for attribute certificate cannot be found.");

                IList certPathList = Platform.CreateArrayList();

				foreach (X509Certificate issuer in issuers)
				{
					result = Build(cert, issuer, pkixParams, certPathList);

					if (result != null)
						break;
				}

				if (result != null)
					break;
			}

			if (result == null && certPathException != null)
			{
				throw new PkixCertPathBuilderException(
					"Possible certificate chain could not be validated.",
					certPathException);
			}

			if (result == null && certPathException == null)
			{
				throw new PkixCertPathBuilderException(
					"Unable to find certificate chain.");
			}

			return result;
		}
        public virtual bool Match(object obj)
        {
            X509Certificate x509Certificate = obj as X509Certificate;

            if (x509Certificate == null)
            {
                return(false);
            }
            if (!X509CertStoreSelector.MatchExtension(this.authorityKeyIdentifier, x509Certificate, X509Extensions.AuthorityKeyIdentifier))
            {
                return(false);
            }
            if (this.basicConstraints != -1)
            {
                int num = x509Certificate.GetBasicConstraints();
                if (this.basicConstraints == -2)
                {
                    if (num != -1)
                    {
                        return(false);
                    }
                }
                else if (num < this.basicConstraints)
                {
                    return(false);
                }
            }
            if (this.certificate != null && !this.certificate.Equals(x509Certificate))
            {
                return(false);
            }
            if (this.certificateValid != null && !x509Certificate.IsValid(this.certificateValid.Value))
            {
                return(false);
            }
            if (this.extendedKeyUsage != null)
            {
                IList list = x509Certificate.GetExtendedKeyUsage();
                if (list != null)
                {
                    foreach (DerObjectIdentifier derObjectIdentifier in this.extendedKeyUsage)
                    {
                        if (!list.Contains(derObjectIdentifier.Id))
                        {
                            return(false);
                        }
                    }
                }
            }
            if (this.issuer != null && !this.issuer.Equivalent(x509Certificate.IssuerDN, true))
            {
                return(false);
            }
            if (this.keyUsage != null)
            {
                bool[] array = x509Certificate.GetKeyUsage();
                if (array != null)
                {
                    for (int i = 0; i < 9; i++)
                    {
                        if (this.keyUsage[i] && !array[i])
                        {
                            return(false);
                        }
                    }
                }
            }
            if (this.policy != null)
            {
                Asn1OctetString extensionValue = x509Certificate.GetExtensionValue(X509Extensions.CertificatePolicies);
                if (extensionValue == null)
                {
                    return(false);
                }
                Asn1Sequence instance = Asn1Sequence.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
                if (this.policy.Count < 1 && instance.Count < 1)
                {
                    return(false);
                }
                bool flag = false;
                foreach (PolicyInformation policyInformation in instance)
                {
                    if (this.policy.Contains(policyInformation.PolicyIdentifier))
                    {
                        flag = true;
                        break;
                    }
                }
                if (!flag)
                {
                    return(false);
                }
            }
            if (this.privateKeyValid != null)
            {
                Asn1OctetString extensionValue2 = x509Certificate.GetExtensionValue(X509Extensions.PrivateKeyUsagePeriod);
                if (extensionValue2 == null)
                {
                    return(false);
                }
                PrivateKeyUsagePeriod instance2 = PrivateKeyUsagePeriod.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2));
                DateTime value  = this.privateKeyValid.Value;
                DateTime value2 = instance2.NotAfter.ToDateTime();
                DateTime value3 = instance2.NotBefore.ToDateTime();
                if (value.CompareTo(value2) > 0 || value.CompareTo(value3) < 0)
                {
                    return(false);
                }
            }
            return((this.serialNumber == null || this.serialNumber.Equals(x509Certificate.SerialNumber)) && (this.subject == null || this.subject.Equivalent(x509Certificate.SubjectDN, true)) && X509CertStoreSelector.MatchExtension(this.subjectKeyIdentifier, x509Certificate, X509Extensions.SubjectKeyIdentifier) && (this.subjectPublicKey == null || this.subjectPublicKey.Equals(X509CertStoreSelector.GetSubjectPublicKey(x509Certificate))) && (this.subjectPublicKeyAlgID == null || this.subjectPublicKeyAlgID.Equals(X509CertStoreSelector.GetSubjectPublicKey(x509Certificate).AlgorithmID)));
        }
Example #18
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
			}
		}
		/// <summary>
		/// Gets the trusted anchors.
		/// </summary>
		/// <remarks>
		/// A trusted anchor is a trusted root-level X.509 certificate,
		/// generally issued by a Certificate Authority (CA).
		/// </remarks>
		/// <returns>The trusted anchors.</returns>
		protected override Org.BouncyCastle.Utilities.Collections.HashSet GetTrustedAnchors ()
		{
			var anchors = new Org.BouncyCastle.Utilities.Collections.HashSet ();
			var selector = new X509CertStoreSelector ();
			var keyUsage = new bool[9];

			keyUsage[(int) X509KeyUsageBits.KeyCertSign] = true;
			selector.KeyUsage = keyUsage;

			foreach (var record in dbase.Find (selector, true, X509CertificateRecordFields.Certificate)) {
				anchors.Add (new TrustAnchor (record.Certificate, null));
			}

			return anchors;
		}
        static IEnumerable<Org.BouncyCastle.X509.X509Certificate> BuildCertificateChainBC(byte[] primary, IEnumerable<byte[]> additional)
        {
            X509CertificateParser parser = new X509CertificateParser();
            PkixCertPathBuilder builder = new PkixCertPathBuilder();

            // Separate root from itermediate
            var intermediateCerts = new List<Org.BouncyCastle.X509.X509Certificate>();
            HashSet rootCerts = new HashSet();

            foreach (byte[] cert in additional)
            {
                var x509Cert = parser.ReadCertificate(cert);

                // Separate root and subordinate certificates
                if (x509Cert.IssuerDN.Equivalent(x509Cert.SubjectDN))
                    rootCerts.Add(new TrustAnchor(x509Cert, null));
                else
                    intermediateCerts.Add(x509Cert);
            }

            // Create chain for this certificate
            X509CertStoreSelector holder = new X509CertStoreSelector();
            holder.Certificate = parser.ReadCertificate(primary);

            // WITHOUT THIS LINE BUILDER CANNOT BEGIN BUILDING THE CHAIN
            intermediateCerts.Add(holder.Certificate);

            PkixBuilderParameters builderParams = new PkixBuilderParameters(rootCerts, holder);
            builderParams.IsRevocationEnabled = false;

            X509CollectionStoreParameters intermediateStoreParameters =
                new X509CollectionStoreParameters(intermediateCerts);

            builderParams.AddStore(X509StoreFactory.Create(
                "Certificate/Collection", intermediateStoreParameters));

            PkixCertPathBuilderResult result = builder.Build(builderParams);

            return result.CertPath.Certificates.Cast<Org.BouncyCastle.X509.X509Certificate>();
        }
		private void Test(string _name, string[] _data, ISet _ipolset,
			bool _explicit, bool _accept, bool _debug)
		{
			testCount++;
			bool _pass = true;

			try
			{
//				CertPathBuilder _cpb = CertPathBuilder.GetInstance("PKIX");
				PkixCertPathBuilder _cpb = new PkixCertPathBuilder();

				X509Certificate _ee = DecodeCertificate(_data[_data.Length - 1]);
				X509CertStoreSelector _select = new X509CertStoreSelector();
				_select.Subject = _ee.SubjectDN;

				IX509Store certStore, crlStore;
				MakeCertStore(_data, out certStore, out crlStore);

				PkixBuilderParameters _param = new PkixBuilderParameters(
					trustedSet, _select);
				_param.IsExplicitPolicyRequired = _explicit;
				_param.AddStore(certStore);
				_param.AddStore(crlStore);
				_param.IsRevocationEnabled = true;

				if (_ipolset != null)
				{
					_param.SetInitialPolicies(_ipolset);
				}

				PkixCertPathBuilderResult _result = _cpb.Build(_param);

				if (!_accept)
				{
					_pass = false;
					testFail.Add(_name);
				}
			}
			catch (Exception)
			{
				if (_accept)
				{
					_pass = false;
					testFail.Add(_name);
				}
			}

			resultBuf.Append("NISTCertPathTest -- ").Append(_name).Append(": ")
				.Append(_pass ? "\n" : "Failed.\n");
		}
		/**
		* Find the issuer certificates of a given certificate.
		*
		* @param cert
		*            The certificate for which an issuer should be found.
		* @param pkixParams
		* @return A <code>Collection</code> object containing the issuer
		*         <code>X509Certificate</code>s. Never <code>null</code>.
		*
		* @exception Exception
		*                if an error occurs.
		*/
		internal static ICollection FindIssuerCerts(
			X509Certificate			cert,
			PkixBuilderParameters	pkixParams)
		{
			X509CertStoreSelector certSelect = new X509CertStoreSelector();
			ISet certs = new HashSet();
			try
			{
				certSelect.Subject = cert.IssuerDN;
			}
			catch (IOException ex)
			{
				throw new Exception(
					"Subject criteria for certificate selector to find issuer certificate could not be set.", ex);
			}

			try
			{
                certs.AddAll(PkixCertPathValidatorUtilities.FindCertificates(certSelect, pkixParams.GetStores()));
                certs.AddAll(PkixCertPathValidatorUtilities.FindCertificates(certSelect, pkixParams.GetAdditionalStores()));
			}
			catch (Exception e)
			{
				throw new Exception("Issuer certificate cannot be searched.", e);
			}

			return certs;
		}
        private static IReadOnlyCollection<X509Certificate> GetChain([NotNull] X509Certificate cert, [CanBeNull] IReadOnlyList<X509Certificate> certs)
        {
            var certList = new List<X509Certificate>();
            if (certs != null)
                certList.AddRange(certs);
            certList.Add(cert);

            var certStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certList));

            var rootCerts = certs.Where(IsSelfSigned).ToList();
            var trustAnchors = rootCerts.Select(x => new TrustAnchor(x, null));
            var trust = new HashSet(trustAnchors);

            var cpb = new PkixCertPathBuilder();
            var targetConstraints = new X509CertStoreSelector()
            {
                Certificate = cert,
            };
            var parameters = new PkixBuilderParameters(trust, targetConstraints)
            {
                IsRevocationEnabled = false,
            };
            parameters.AddStore(certStore);
            var cpbResult = cpb.Build(parameters);

            var result = new List<X509Certificate>();
            result.AddRange(cpbResult.CertPath.Certificates.Cast<X509Certificate>());
            result.Add(cpbResult.TrustAnchor.TrustedCert);
            return result;
        }
		/// <summary>
		/// Return a Collection of all certificates or attribute certificates found
		/// in the X509Store's that are matching the certSelect criteriums.
		/// </summary>
		/// <param name="certSelect">a {@link Selector} object that will be used to select
		/// the certificates</param>
		/// <param name="certStores">a List containing only X509Store objects. These
		/// are used to search for certificates.</param>
		/// <returns>a Collection of all found <see cref="X509Certificate"/> or
		/// <see cref="Org.BouncyCastle.X509.IX509AttributeCertificate"/> objects.
		/// May be empty but never <code>null</code>.</returns>
		/// <exception cref="Exception"></exception>
		internal static ICollection FindCertificates(
			X509CertStoreSelector	certSelect,
			IList					certStores)
		{
			ISet certs = new HashSet();

			foreach (IX509Store certStore in certStores)
			{
				try
				{
//					certs.AddAll(certStore.GetMatches(certSelect));
					foreach (X509Certificate c in certStore.GetMatches(certSelect))
					{
						certs.Add(c);
					}
				}
				catch (Exception e)
				{
					throw new Exception("Problem while picking certificates from X.509 store.", e);
				}
			}

			return certs;
		}
        /// <summary>
        /// Builds certification path for provided signing certificate
        /// </summary>
        /// <param name="signingCertificate">Signing certificate</param>
        /// <param name="otherCertificates">Other certificates that should be used in path building process. Self-signed certificates from this list are used as trust anchors.</param>
        /// <param name="includeRoot">Flag indicating whether root certificate should be included int the certification path.</param>
        /// <returns>Certification path for provided signing certificate</returns>
        public static ICollection<BCX509.X509Certificate> BuildCertPath(byte[] signingCertificate, List<byte[]> otherCertificates, bool includeRoot)
        {
            if (signingCertificate == null)
                throw new ArgumentNullException("signingCertificate");

            List<BCX509.X509Certificate> result = new List<BCX509.X509Certificate>();

            BCX509.X509Certificate signingCert = ToBouncyCastleObject(signingCertificate);
            BCCollections.ISet trustAnchors = new BCCollections.HashSet();
            List<BCX509.X509Certificate> otherCerts = new List<BCX509.X509Certificate>();

            if (IsSelfSigned(signingCert))
            {
                if (includeRoot)
                    result.Add(signingCert);
            }
            else
            {
                otherCerts.Add(signingCert);

                if (otherCertificates != null)
                {
                    foreach (byte[] otherCertificate in otherCertificates)
                    {
                        BCX509.X509Certificate otherCert = ToBouncyCastleObject(otherCertificate);
                        otherCerts.Add(ToBouncyCastleObject(otherCertificate));
                        if (IsSelfSigned(otherCert))
                            trustAnchors.Add(new TrustAnchor(otherCert, null));
                    }
                }

                if (trustAnchors.Count < 1)
                    throw new PkixCertPathBuilderException("Provided certificates do not contain self-signed root certificate");

                X509CertStoreSelector targetConstraints = new X509CertStoreSelector();
                targetConstraints.Certificate = signingCert;

                PkixBuilderParameters certPathBuilderParameters = new PkixBuilderParameters(trustAnchors, targetConstraints);
                certPathBuilderParameters.AddStore(X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(otherCerts)));
                certPathBuilderParameters.IsRevocationEnabled = false;

                PkixCertPathBuilder certPathBuilder = new PkixCertPathBuilder();
                PkixCertPathBuilderResult certPathBuilderResult = certPathBuilder.Build(certPathBuilderParameters);

                foreach (BCX509.X509Certificate certPathCert in certPathBuilderResult.CertPath.Certificates)
                    result.Add(certPathCert);

                if (includeRoot)
                    result.Add(certPathBuilderResult.TrustAnchor.TrustedCert);
            }

            return result;
        }
Example #26
0
        /// <summary>
        /// Validates the cert with the provided ocsp responses.
        /// </summary>
        /// <param name="certificate">The cert to validate</param>
        /// <param name="issuer">The issuer of the cert to validate</param>
        /// <param name="validationTime">The time on which the cert was needed to validated</param>
        /// <param name="ocspResponses">The list of ocsp responses to use</param>
        /// <returns>The OCSP response that was used, <c>null</c> if none was found</returns>
        /// <exception cref="RevocationException{T}">When the certificate was revoked on the provided time</exception>
        /// <exception cref="RevocationUnknownException">When the certificate (or the OCSP) can't be validated</exception>
        public static BCAO.BasicOcspResponse Verify(this X509Certificate2 certificate, X509Certificate2 issuer, DateTime validationTime, IList <BCAO.BasicOcspResponse> ocspResponses)
        {
            DateTime minTime = validationTime - ClockSkewness;
            DateTime maxTime = validationTime + ClockSkewness;

            BCX.X509Certificate certificateBC = DotNetUtilities.FromX509Certificate(certificate);
            BCX.X509Certificate issuerBC      = DotNetUtilities.FromX509Certificate(issuer);

            ValueWithRef <BCO.SingleResp, ValueWithRef <BCO.BasicOcspResp, BCAO.BasicOcspResponse> > singleOcspRespLeaf = ocspResponses
                                                                                                                          .Select((rsp) => new ValueWithRef <BCO.BasicOcspResp, BCAO.BasicOcspResponse>(new BCO.BasicOcspResp(rsp), rsp))                                         //convert, but keep the original
                                                                                                                          .SelectMany((r) => r.Value.Responses.Select(sr => new ValueWithRef <BCO.SingleResp, ValueWithRef <BCO.BasicOcspResp, BCAO.BasicOcspResponse> >(sr, r))) //get the single respononses, but keep the parent
                                                                                                                          .Where((sr) => sr.Value.GetCertID().SerialNumber.Equals(certificateBC.SerialNumber) && sr.Value.GetCertID().MatchesIssuer(issuerBC))                    //is it for this cert?
                                                                                                                          .Where((sr) => sr.Value.ThisUpdate >= minTime || (sr.Value.NextUpdate != null && sr.Value.NextUpdate.Value >= minTime))                                 //was it issued on time?
                                                                                                                          .OrderByDescending((sr) => sr.Value.ThisUpdate)                                                                                                         //newest first
                                                                                                                          .FirstOrDefault();

            if (singleOcspRespLeaf == null)
            {
                return(null);
            }

            BCO.SingleResp         singleOcspResp    = singleOcspRespLeaf.Value;
            BCO.BasicOcspResp      basicOcspResp     = singleOcspRespLeaf.Reference.Value;
            BCAO.BasicOcspResponse basicOcspResponse = singleOcspRespLeaf.Reference.Reference;

            //get the signer name
            BCAX.X509Name responderName = basicOcspResp.ResponderId.ToAsn1Object().Name;
            if (responderName == null)
            {
                trace.TraceEvent(TraceEventType.Error, 0, "OCSP response for {0} does not have a ResponderID", certificate.Subject);
                throw new RevocationUnknownException("OCSP response for {0} does not have a ResponderID");
            }

            //Get the signer certificate
            var selector = new BCS.X509CertStoreSelector();

            selector.Subject = responderName;
            BCX.X509Certificate ocspSignerBc = (BCX.X509Certificate)basicOcspResp
                                               .GetCertificates("Collection").GetMatches(selector)
                                               .Cast <BCX.X509Certificate>().FirstOrDefault();
            if (ocspSignerBc == null)
            {
                throw new RevocationUnknownException("The OCSP is signed by a unknown certificate");
            }

            //verify the response signature
            if (!basicOcspResp.Verify(ocspSignerBc.GetPublicKey()))
            {
                throw new RevocationUnknownException("The OCSP has an invalid signature");
            }


            //OCSP must be issued by same issuer an the certificate that it validates.
            try
            {
                if (!ocspSignerBc.IssuerDN.Equals(issuerBC.SubjectDN))
                {
                    throw new ApplicationException();
                }
                ocspSignerBc.Verify(issuerBC.GetPublicKey());
            }
            catch (Exception e)
            {
                throw new RevocationUnknownException("The OCSP signer was not issued by the proper CA", e);
            }

            //verify if the OCSP signer certificate is stil valid
            if (!ocspSignerBc.IsValid(basicOcspResp.ProducedAt))
            {
                throw new RevocationUnknownException("The OCSP signer was not valid at the time the ocsp was issued");
            }


            //check if the signer may issue OCSP
            IList ocspSignerExtKeyUsage = ocspSignerBc.GetExtendedKeyUsage();

            if (!ocspSignerExtKeyUsage.Contains("1.3.6.1.5.5.7.3.9"))
            {
                throw new RevocationUnknownException("The OCSP is signed by a certificate that isn't allowed to sign OCSP");
            }

            //finally, check if the certificate is revoked or not
            var revokedStatus = (BCO.RevokedStatus)singleOcspResp.GetCertStatus();

            if (revokedStatus != null)
            {
                trace.TraceEvent(TraceEventType.Verbose, 0, "OCSP response for {0} indicates that the certificate is revoked on {1}", certificate.Subject, revokedStatus.RevocationTime);
                if (maxTime >= revokedStatus.RevocationTime)
                {
                    throw new RevocationException <BCAO.BasicOcspResponse>(basicOcspResponse, "The certificate was revoked on " + revokedStatus.RevocationTime.ToString("o"));
                }
            }

            return(basicOcspResponse);
        }
		private string TestPolicies(
			int index,
			X509Certificate trustCert,
			X509Certificate intCert,
			X509Certificate endCert,
			ISet requirePolicies,
			bool okay)
		{
			ISet trust = new HashSet();
			trust.Add(new TrustAnchor(trustCert, null));
			X509CertStoreSelector targetConstraints = new X509CertStoreSelector();
			targetConstraints.Subject = endCert.SubjectDN;
			PkixBuilderParameters pbParams = new PkixBuilderParameters(trust, targetConstraints);

			ISet certs = new HashSet();
			certs.Add(intCert);
			certs.Add(endCert);

			IX509Store store = X509StoreFactory.Create(
				"CERTIFICATE/COLLECTION",
				new X509CollectionStoreParameters(certs));
			pbParams.AddStore(store);

			pbParams.IsRevocationEnabled = false;
			if (requirePolicies != null)
			{
				pbParams.IsExplicitPolicyRequired = true;
				pbParams.SetInitialPolicies(requirePolicies);
			}

//			CertPathBuilder cpb = CertPathBuilder.GetInstance("PKIX");
			PkixCertPathBuilder cpb = new PkixCertPathBuilder();
			PkixCertPathBuilderResult result = null;

			try
			{
				result = (PkixCertPathBuilderResult)cpb.Build(pbParams);

				if (!okay)
				{
					Fail(index + ": path validated when failure expected.");
				}

//				if (result.getPolicyTree() != null)
//				{
//					Console.WriteLine("OK");
//					Console.WriteLine("policy: " + result.getPolicyTree());
//				}
//				else
//				{
//					Console.WriteLine("OK: policy tree = null");
//				}

				return "";
			}
			catch (TestFailedException e)
			{
				throw e;
			}
			catch (Exception e)
			{
				if (okay)
				{
					Fail(index + ": path failed to validate when success expected.");
				}

				Exception ee = e.InnerException;
				if (ee != null)
				{
					return ee.Message;
				}

				return e.Message;
			}
		}
		/**
		* Obtain and validate the certification path for the complete CRL issuer.
		* If a key usage extension is present in the CRL issuer's certificate,
		* verify that the cRLSign bit is set.
		*
		* @param crl                CRL which contains revocation information for the certificate
		*                           <code>cert</code>.
		* @param cert               The attribute certificate or certificate to check if it is
		*                           revoked.
		* @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>.
		* @param defaultCRLSignKey  The public key of the issuer certificate
		*                           <code>defaultCRLSignCert</code>.
		* @param paramsPKIX         paramsPKIX PKIX parameters.
		* @param certPathCerts      The certificates on the certification path.
		* @return A <code>Set</code> with all keys of possible CRL issuer
		*         certificates.
		* @throws AnnotatedException if the CRL is not valid or the status cannot be checked or
		*                            some error occurs.
		*/
		internal static ISet ProcessCrlF(
			X509Crl					crl,
			object					cert,
			X509Certificate			defaultCRLSignCert,
			AsymmetricKeyParameter	defaultCRLSignKey,
			PkixParameters			paramsPKIX,
			IList					certPathCerts)
		{
			// (f)

			// get issuer from CRL
			X509CertStoreSelector selector = new X509CertStoreSelector();
			try
			{
				selector.Subject = crl.IssuerDN;
			}
			catch (IOException e)
			{
				throw new Exception(
					"Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e);
			}

			// get CRL signing certs
			IList coll = Platform.CreateArrayList();

			try
			{
                CollectionUtilities.AddRange(coll, PkixCertPathValidatorUtilities.FindCertificates(selector, paramsPKIX.GetStores()));
                CollectionUtilities.AddRange(coll, PkixCertPathValidatorUtilities.FindCertificates(selector, paramsPKIX.GetAdditionalStores()));
			}
			catch (Exception e)
			{
				throw new Exception("Issuer certificate for CRL cannot be searched.", e);
			}

			coll.Add(defaultCRLSignCert);

			IEnumerator cert_it = coll.GetEnumerator();

            IList validCerts = Platform.CreateArrayList();
            IList validKeys = Platform.CreateArrayList();

			while (cert_it.MoveNext())
			{
				X509Certificate signingCert = (X509Certificate)cert_it.Current;

				/*
				 * CA of the certificate, for which this CRL is checked, has also
				 * signed CRL, so skip the path validation, because is already done
				 */
				if (signingCert.Equals(defaultCRLSignCert))
				{
					validCerts.Add(signingCert);
					validKeys.Add(defaultCRLSignKey);
					continue;
				}
				try
				{
//					CertPathBuilder builder = CertPathBuilder.GetInstance("PKIX");
					PkixCertPathBuilder builder = new PkixCertPathBuilder();
					selector = new X509CertStoreSelector();
					selector.Certificate = signingCert;

					PkixParameters temp = (PkixParameters)paramsPKIX.Clone();
					temp.SetTargetCertConstraints(selector);

					PkixBuilderParameters parameters = (PkixBuilderParameters)
						PkixBuilderParameters.GetInstance(temp);

					/*
					 * if signingCert is placed not higher on the cert path a
					 * dependency loop results. CRL for cert is checked, but
					 * signingCert is needed for checking the CRL which is dependent
					 * on checking cert because it is higher in the cert path and so
					 * signing signingCert transitively. so, revocation is disabled,
					 * forgery attacks of the CRL are detected in this outer loop
					 * for all other it must be enabled to prevent forgery attacks
					 */
					if (certPathCerts.Contains(signingCert))
					{
						parameters.IsRevocationEnabled = false;
					}
					else
					{
						parameters.IsRevocationEnabled = true;
					}
					IList certs = builder.Build(parameters).CertPath.Certificates;
					validCerts.Add(signingCert);
					validKeys.Add(PkixCertPathValidatorUtilities.GetNextWorkingKey(certs, 0));
				}
				catch (PkixCertPathBuilderException e)
				{
					throw new Exception("Internal error.", e);
				}
				catch (PkixCertPathValidatorException e)
				{
					throw new Exception("Public key of issuer certificate of CRL could not be retrieved.", e);
				}
				//catch (Exception e)
				//{
				//    throw new Exception(e.Message);
				//}
			}

			ISet checkKeys = new HashSet();

			Exception lastException = null;
			for (int i = 0; i < validCerts.Count; i++)
			{
				X509Certificate signCert = (X509Certificate)validCerts[i];
				bool[] keyusage = signCert.GetKeyUsage();

				if (keyusage != null && (keyusage.Length < 7 || !keyusage[CRL_SIGN]))
				{
					lastException = new Exception(
						"Issuer certificate key usage extension does not permit CRL signing.");
				}
				else
				{
					checkKeys.Add(validKeys[i]);
				}
			}

			if ((checkKeys.Count == 0) && lastException == null)
			{
				throw new Exception("Cannot find a valid issuer certificate.");
			}
			if ((checkKeys.Count == 0) && lastException != null)
			{
				throw lastException;
			}

			return checkKeys;
		}
		private PkixCertPathBuilderResult doBuilderTest(
			string		trustAnchor,
			string[]	certs,
			string[]	crls,
			ISet		initialPolicies,
			bool		policyMappingInhibited,
			bool		anyPolicyInhibited)
		{
			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);

			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));

//			CertPathBuilder builder = CertPathBuilder.GetInstance("PKIX");   
			PkixCertPathBuilder builder = new PkixCertPathBuilder();

			X509CertStoreSelector endSelector = new X509CertStoreSelector();

			endSelector.Certificate = endCert;

			PkixBuilderParameters builderParams = new PkixBuilderParameters(trustedSet, endSelector);

			if (initialPolicies != null)
			{
				builderParams.SetInitialPolicies(initialPolicies);
				builderParams.IsExplicitPolicyRequired = true;
			}
			if (policyMappingInhibited)
			{
				builderParams.IsPolicyMappingInhibited = policyMappingInhibited;
			}
			if (anyPolicyInhibited)
			{
				builderParams.IsAnyPolicyInhibited = anyPolicyInhibited;
			}

			builderParams.AddStore(x509CertStore);
			builderParams.AddStore(x509CrlStore);

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

			try
			{
				return (PkixCertPathBuilderResult) builder.Build(builderParams);
			}
			catch (PkixCertPathBuilderException e)
			{               
				throw e.InnerException;
			}
		}
		private void v0Test()
		{
			// create certificates and CRLs
			AsymmetricCipherKeyPair rootPair = TestUtilities.GenerateRsaKeyPair();
			AsymmetricCipherKeyPair interPair = TestUtilities.GenerateRsaKeyPair();
			AsymmetricCipherKeyPair 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);

			BigInteger 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");
			}
		}
Example #31
0
 private X509CertPairStoreSelector(X509CertPairStoreSelector o)
 {
     certPair        = o.CertPair;
     forwardSelector = o.ForwardSelector;
     reverseSelector = o.ReverseSelector;
 }