private X509Crl GetCertificateCRL(X509Certificate2 cert, String crlsPath)
        {
            DirectoryInfo di = new DirectoryInfo(crlsPath);

            FileInfo[] files = di.GetFiles();

            for (int i = 0; i < files.Length; i++)
            {
                try
                {
                    FileStream fs  = new FileStream(files[i].FullName, FileMode.Open, FileAccess.Read);
                    X509Crl    crl = new Org.BouncyCastle.X509.X509CrlParser().ReadCrl(fs);
                    fs.Close();
                    X500DistinguishedName crlIssuer = new X500DistinguishedName(crl.IssuerDN.GetEncoded());
                    if (crlIssuer.Name.Equals(cert.Issuer))
                    {
                        return(crl);
                    }
                }
                catch (Exception ex)
                {
                    continue;
                }
            }
            return(null);
        }
		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");
			}
		}
		/// <summary>
		/// Finds the specified certificate revocation list.
		/// </summary>
		/// <remarks>
		/// Searches the database for the specified CRL, returning the matching record with
		/// the desired fields populated.
		/// </remarks>
		/// <returns>The matching record if found; otherwise <c>null</c>.</returns>
		/// <param name="crl">The certificate revocation list.</param>
		/// <param name="fields">The desired fields.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="crl"/> is <c>null</c>.
		/// </exception>
		public X509CrlRecord Find (X509Crl crl, X509CrlRecordFields fields)
		{
			if (crl == null)
				throw new ArgumentNullException ("crl");

			using (var command = GetSelectCommand (crl, fields)) {
				var reader = command.ExecuteReader ();

				try {
					if (reader.Read ()) {
						var parser = new X509CrlParser ();
						var buffer = new byte[4096];

						return LoadCrlRecord (reader, parser, ref buffer);
					}
				} finally {
					reader.Close ();
				}
			}

			return null;
		}
		/// <summary>
		/// Finds the CRL records for the specified issuer.
		/// </summary>
		/// <remarks>
		/// Searches the database for CRL records matching the specified issuer, returning
		/// all matching records populated with the desired fields.
		/// </remarks>
		/// <returns>The matching CRL records populated with the desired fields.</returns>
		/// <param name="issuer">The issuer.</param>
		/// <param name="fields">The desired fields.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="issuer"/> is <c>null</c>.
		/// </exception>
		public IEnumerable<X509CrlRecord> Find (X509Name issuer, X509CrlRecordFields fields)
		{
			if (issuer == null)
				throw new ArgumentNullException ("issuer");

			using (var command = GetSelectCommand (issuer, fields)) {
				var reader = command.ExecuteReader ();

				try {
					var parser = new X509CrlParser ();
					var buffer = new byte[4096];

					while (reader.Read ()) {
						yield return LoadCrlRecord (reader, parser, ref buffer);
					}
				} finally {
					reader.Close ();
				}
			}

			yield break;
		}
Exemple #5
0
        private void checkCrl(
            int     id,
            byte[]  bytes)
        {
            string dump = "";

            try
            {
                X509Crl cert = new X509CrlParser().ReadCrl(bytes);

                // Console.WriteLine(cert);
            }
            catch (Exception e)
            {
                Fail(dump + SimpleTest.NewLine + Name + ": "+ id + " failed - exception " + e.Message, e);
            }

        }
Exemple #6
0
 private void pemTest()
 {
     X509Certificate cert = readPemCert(PemData.CERTIFICATE_1);
     if (cert == null)
     {
         Fail("PEM cert not read");
     }
     cert = readPemCert("-----BEGIN CERTIFICATE-----" + PemData.CERTIFICATE_2);
     if (cert == null)
     {
         Fail("PEM cert with extraneous header not read");
     }
     X509Crl crl = new X509CrlParser().ReadCrl(Encoding.ASCII.GetBytes(PemData.CRL_1));
     if (crl == null)
     {
         Fail("PEM crl not read");
     }
     ArrayList col = new ArrayList(
         new X509CertificateParser().ReadCertificates(Encoding.ASCII.GetBytes(PemData.CERTIFICATE_2)));
     if (col.Count != 1 || !col.Contains(cert))
     {
         Fail("PEM cert collection not right");
     }
     col = new ArrayList(
         new X509CrlParser().ReadCrls(Encoding.ASCII.GetBytes(PemData.CRL_2)));
     if (col.Count != 1 || !col.Contains(crl))
     {
         Fail("PEM crl collection not right");
     }
 }
		private X509Crl LoadCrl(
			string crlName)
			//throws Exception
		{
			X509Crl crl = (X509Crl)certs[crlName];
        
			if (crl != null)
			{
				return crl;
			}

			Stream fs = null;

			try
			{
				fs = SimpleTest.GetTestDataAsStream("PKITS.crls." + crlName + ".crl");

				crl = new X509CrlParser().ReadCrl(fs);

				crls[crlName] = crl;

				return crl;
			}
			catch (Exception)
			{
				throw new InvalidOperationException("exception loading CRL: " + crlName);
			}
			finally
			{
				fs.Close();
			}
		}
	    /**
	     * Gets a list of X509CRL objects from a Document Security Store.
	     * @return	a list of CRLs
	     * @throws GeneralSecurityException
	     * @throws IOException
	     */
	    virtual public List<X509Crl> GetCRLsFromDSS() {
		    List<X509Crl> crls = new List<X509Crl>();
		    if (dss == null)
			    return crls;
		    PdfArray crlarray = dss.GetAsArray(PdfName.CRLS);
		    if (crlarray == null)
			    return crls;
            X509CrlParser crlParser = new X509CrlParser();
		    for (int i = 0; i < crlarray.Size; ++i) {
			    PRStream stream = (PRStream) crlarray.GetAsStream(i);
			    X509Crl crl = crlParser.ReadCrl(new MemoryStream(PdfReader.GetStreamBytes(stream)));
			    crls.Add(crl);
		    }
		    return crls;
	    }
        /// <summary>
        /// Initializes a new instance of the <see cref="MimeKit.Cryptography.DefaultSecureMimeContext"/> class.
        /// </summary>
        /// <param name="revokedFileName">The path to the revoked certificate lists.</param>
        /// <param name="addressbookFileName">The path to the addressbook certificates.</param>
        /// <param name="rootFileName">The path to the root certificates.</param>
        /// <param name="userFileName">The path to the pkcs12-formatted user certificates.</param>
        /// <param name="password">The password for the pkcs12 user certificates file.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="addressbookFileName"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="rootFileName"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="userFileName"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="password"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An error occurred while reading the file.
        /// </exception>
        protected DefaultSecureMimeContext(string revokedFileName, string addressbookFileName, string rootFileName, string userFileName, string password)
        {
            addressbook = new X509CertificateStore ();
            store = new X509CertificateStore ();
            root = new X509CertificateStore ();
            crls = new HashSet<X509Crl> ();

            try {
                using (var file = File.OpenRead (revokedFileName)) {
                    var parser = new X509CrlParser ();
                    foreach (X509Crl crl in parser.ReadCrls (file))
                        crls.Add (crl);
                }
            } catch (FileNotFoundException) {
            }

            try {
                addressbook.Import (addressbookFileName);
            } catch (FileNotFoundException) {
            }

            try {
                store.Import (userFileName, password);
            } catch (FileNotFoundException) {
            }

            try {
                root.Import (rootFileName);
            } catch (FileNotFoundException) {
            }

            this.addressbookFileName = addressbookFileName;
            this.revokedFileName = revokedFileName;
            this.userFileName = userFileName;
            this.password = password;
        }
		/// <exception cref="System.IO.IOException"></exception>
		public virtual X509Crl FindCrl(X509Certificate certificate, X509Certificate issuerCertificate)
		{
			OnlineCrlSource source = this.CachedSource ?? new OnlineCrlSource();
			string crlUrl = source.GetCrlUri(certificate);            

            if (crlUrl != null)
			{
                try
                {
                    CachedCRL cachedCrl = null;

                    string key = Hex.ToHexString(
                        DigestUtilities.CalculateDigest(DigestAlgorithm.SHA1.GetOid()
                        , Sharpen.Runtime.GetBytesForString(crlUrl)));

                    string pathCrl = Path.Combine("CRL", key);

                    DirectoryInfo dirCrl = new DirectoryInfo("CRL");

                    if (dirCrl.Exists)
                    {
                        FileInfo[] archivosCrl = dirCrl.GetFiles();

                        foreach (FileInfo a in archivosCrl)
                        {
                            if (a.Extension.Equals(".txt"))
                                continue;

                            if (a.Name.Equals(key))
                            {
                                cachedCrl = new CachedCRL()
                                {
                                    Crl = File.ReadAllBytes(a.FullName),
                                    Key = key
                                };

                                break;
                            }
                        }
                    }
                    else
                    {
                        dirCrl.Create();
                    }

                    if (cachedCrl == null)
                    {
                        LOG.Info("CRL not in cache");
                        return FindAndCacheCrlOnline(certificate, issuerCertificate, pathCrl);
                    }

                    X509CrlParser parser = new X509CrlParser();
                    X509Crl x509crl = parser.ReadCrl(cachedCrl.Crl);

                    if (x509crl.NextUpdate.Value.CompareTo(DateTime.Now) > 0)
                    {
                        LOG.Info("CRL in cache");
                        return x509crl;
                    }
                    else
                    {
                        LOG.Info("CRL expired");
                        return FindAndCacheCrlOnline(certificate, issuerCertificate, pathCrl);
                    }
                }
                catch (NoSuchAlgorithmException)
                {
                    LOG.Info("Cannot instantiate digest for algorithm SHA1 !?");
                }
                catch (CrlException)
                {
                    LOG.Info("Cannot serialize CRL");
                }
                catch (CertificateException)
                {
                    LOG.Info("Cannot instanciate X509 Factory");
                }
                catch (WebException)
                {
                    LOG.Info("Cannot connect to CRL URL");
                }
			}
			return null;
		}
Exemple #11
0
		/// <exception cref="Sharpen.CertificateException"></exception>
		/// <exception cref="Sharpen.CRLException"></exception>
		/// <exception cref="Sharpen.NoSuchProviderException"></exception>
		/// <exception cref="Org.BouncyCastle.X509.NoSuchParserException"></exception>
		/// <exception cref="Org.BouncyCastle.X509.Util.StreamParsingException"></exception>
		private X509Crl GetCrl(string downloadUrl)
		{
			if (downloadUrl != null)
			{
				try
				{
					InputStream input = UrlDataLoader.Get(downloadUrl);

                    X509CrlParser parser = new X509CrlParser();
                    X509Crl crl = parser.ReadCrl(input);
					LOG.Info("CRL size: " + crl.GetEncoded().Length + " bytes");
					return crl;
				}
				catch (CannotFetchDataException)
				{
					return null;
				}
			}
			else
			{
				return null;
			}
		}
Exemple #12
0
        public override void PerformTest()
        {
            try
            {
                X509CertificateParser certParser = new X509CertificateParser();
                X509CrlParser crlParser = new X509CrlParser();

                X509Certificate rootCert = certParser.ReadCertificate(rootCertBin);
                X509Certificate userCert1 = certParser.ReadCertificate(userCert1Bin);
                X509Certificate userCert2 = certParser.ReadCertificate(userCert2Bin);

                X509Crl crl = crlParser.ReadCrl(crlBin);

                rootCert.Verify(rootCert.GetPublicKey());
                userCert1.Verify(rootCert.GetPublicKey());

                crl.Verify(rootCert.GetPublicKey());

                if (!crl.IsRevoked(userCert1))
                {
                    Fail(this.Name + ": usercert1 not revoked.");
                }

                if (crl.IsRevoked(userCert2))
                {
                    Fail(this.Name + ": usercert2 revoked.");
                }

            }
            catch (Exception e)
            {
                Fail(this.Name + ": exception - " + e.ToString());
            }
        }
        /**
         * Verifies if an OCSP response is genuine
         *  If it doesn't verify against the issuer certificate and response's certificates, it may verify
         * using a trusted anchor or cert.
         * @param ocspResp	the OCSP response
         * @param issuerCert	the issuer certificate
         * @throws GeneralSecurityException
         * @throws IOException
         */
        virtual public void IsValidResponse(BasicOcspResp ocspResp, X509Certificate issuerCert) {
            //OCSP response might be signed by the issuer certificate or
            //the Authorized OCSP responder certificate containing the id-kp-OCSPSigning extended key usage extension
            X509Certificate responderCert = null;

            //first check if the issuer certificate signed the response
            //since it is expected to be the most common case
            if (IsSignatureValid(ocspResp, issuerCert)) {
                responderCert = issuerCert;
            }

            //if the issuer certificate didn't sign the ocsp response, look for authorized ocsp responses
            // from properties or from certificate chain received with response
            if (responderCert == null) {
                if (ocspResp.GetCerts() != null) {
                    //look for existence of Authorized OCSP responder inside the cert chain in ocsp response
                    X509Certificate[] certs = ocspResp.GetCerts();
                    foreach (X509Certificate cert in certs) {
                        X509Certificate tempCert;
                        try {
                            tempCert = cert;
                        } catch (Exception ex) {
                            continue;
                        }
                        IList keyPurposes = null;
                        try {
                            keyPurposes = tempCert.GetExtendedKeyUsage();
                            if ((keyPurposes != null) && keyPurposes.Contains(id_kp_OCSPSigning) && IsSignatureValid(ocspResp, tempCert)) {
                                responderCert = tempCert;
                                break;
                            }
                        } catch (CertificateParsingException ignored) {
                        }
                    }
                    // Certificate signing the ocsp response is not found in ocsp response's certificate chain received
                    // and is not signed by the issuer certificate.
                    if (responderCert == null) {
                        throw new VerificationException(issuerCert, "OCSP response could not be verified");
                    }
                } else {
                    //certificate chain is not present in response received
                    //try to verify using rootStore
                    if (certificates != null) {
                        foreach (X509Certificate anchor in certificates) {
                            try {
                                if (IsSignatureValid(ocspResp, anchor)) {
                                    responderCert = anchor;
                                    break;
                                }
                            } catch (GeneralSecurityException ignored) {
                            }
                        }
                    }

                    // OCSP Response does not contain certificate chain, and response is not signed by any
                    // of the rootStore or the issuer certificate.
                    if (responderCert == null) {
                        throw new VerificationException(issuerCert, "OCSP response could not be verified");
                    }
                }
            }

            //check "This certificate MUST be issued directly by the CA that issued the certificate in question".
            responderCert.Verify(issuerCert.GetPublicKey());

            // validating ocsp signers certificate
            // Check if responders certificate has id-pkix-ocsp-nocheck extension,
            // in which case we do not validate (perform revocation check on) ocsp certs for lifetime of certificate
            if (responderCert.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNocheck.Id) == null) {
                X509Crl crl;
                try {
                    X509CrlParser crlParser = new X509CrlParser();
			        // Creates the CRL
		            Stream url = WebRequest.Create(CertificateUtil.GetCRLURL(responderCert)).GetResponse().GetResponseStream();
			        crl = crlParser.ReadCrl(url);
                } catch (Exception ignored) {
                    crl = null;
                }
                if (crl != null) {
                    CrlVerifier crlVerifier = new CrlVerifier(null, null);
                    crlVerifier.Certificates = certificates;
                    crlVerifier.OnlineCheckingAllowed = onlineCheckingAllowed;
                    crlVerifier.Verify(crl, responderCert, issuerCert, DateTime.UtcNow);
                    return;
                }
            }

            //check if lifetime of certificate is ok
            responderCert.CheckValidity();
	    }
		/// <summary>
		/// Gets a certificate revocation list store.
		/// </summary>
		/// <remarks>
		/// Gets a certificate revocation list store.
		/// </remarks>
		/// <returns>A certificate recovation list store.</returns>
		public IX509Store GetCrlStore ()
		{
			var crls = new List<X509Crl> ();

			using (var command = GetSelectAllCrlsCommand ()) {
				var reader = command.ExecuteReader ();

				try {
					var parser = new X509CrlParser ();
					var buffer = new byte[4096];

					while (reader.Read ()) {
						var record = LoadCrlRecord (reader, parser, ref buffer);
						crls.Add (record.Crl);
					}
				} finally {
					reader.Close ();
				}
			}

			return X509StoreFactory.Create ("Crl/Collection", new X509CollectionStoreParameters (crls));
		}
Exemple #15
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();
		}
 /**
  * Helper method that tries to construct the CRLs.
  */
 private void FindCRL(Asn1Sequence seq)
 {
     crls = new List<X509Crl>();
     for (int k = 0; k < seq.Count; ++k) {
         X509CrlParser pp = new X509CrlParser();
         X509Crl crl = pp.ReadCrl(seq[k].GetDerEncoded());
         crls.Add(crl);
     }
 }
		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");
			}

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

				//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);
			}
		}
        /**
         * Fetches a CRL for a specific certificate online (without further checking).
         * @param signCert	the certificate
         * @param issuerCert	its issuer
         * @return	an X509CRL object
         */
        public X509Crl GetCrl(X509Certificate signCert, X509Certificate issuerCert)
        {
            try {
                // gets the URL from the certificate
                String crlurl = CertificateUtil.GetCRLURL(signCert);
                if (crlurl == null)
                    return null;
                LOGGER.Info("Getting CRL from " + crlurl);

                X509CrlParser crlParser = new X509CrlParser();
                // Creates the CRL
                Stream url = WebRequest.Create(crlurl).GetResponse().GetResponseStream();
                return crlParser.ReadCrl(url);
            }
            catch (IOException) {
                return null;
            }
            catch (GeneralSecurityException) {
                return null;
            }
        }
        private void AddCrlsFromSet(
			IList	crls,
			Asn1Set	crlSet)
        {
            X509CrlParser cf = new X509CrlParser();

            foreach (Asn1Encodable ae in crlSet)
            {
                try
                {
                    // TODO Build CRL directly from ae.ToAsn1Object()?
                    crls.Add(cf.ReadCrl(ae.GetEncoded()));
                }
                catch (Exception ex)
                {
                    throw new CmsException("can't re-encode CRL!", ex);
                }
            }
        }
Exemple #20
0
        private void checkCrlCreation3()
        {
            IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
            kpGen.Init(
                new RsaKeyGenerationParameters(
                    BigInteger.ValueOf(0x10001), new SecureRandom(), 768, 25));

            X509V2CrlGenerator crlGen = new X509V2CrlGenerator();
            DateTime now = DateTime.UtcNow;
            AsymmetricCipherKeyPair pair = kpGen.GenerateKeyPair();

            crlGen.SetIssuerDN(new X509Name("CN=Test CA"));

            crlGen.SetThisUpdate(now);
            crlGen.SetNextUpdate(now.AddSeconds(100));
            crlGen.SetSignatureAlgorithm("SHA256WithRSAEncryption");

            IList extOids = new ArrayList();
            IList extValues = new ArrayList();

            CrlReason crlReason = new CrlReason(CrlReason.PrivilegeWithdrawn);

            try
            {
                extOids.Add(X509Extensions.ReasonCode);
                extValues.Add(new X509Extension(false, new DerOctetString(crlReason.GetEncoded())));
            }
            catch (IOException e)
            {
                throw new ArgumentException("error encoding reason: " + e);
            }

            X509Extensions entryExtensions = new X509Extensions(extOids, extValues);

            crlGen.AddCrlEntry(BigInteger.One, now, entryExtensions);

            crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.Public));

            X509Crl crl = crlGen.Generate(pair.Private);

            if (!crl.IssuerDN.Equivalent(new X509Name("CN=Test CA"), true))
            {
                Fail("failed CRL issuer test");
            }

            Asn1OctetString authExt = crl.GetExtensionValue(X509Extensions.AuthorityKeyIdentifier);

            if (authExt == null)
            {
                Fail("failed to find CRL extension");
            }

            AuthorityKeyIdentifier authId = new AuthorityKeyIdentifierStructure(authExt);

            X509CrlEntry entry = crl.GetRevokedCertificate(BigInteger.One);

            if (entry == null)
            {
                Fail("failed to find CRL entry");
            }

            if (!entry.SerialNumber.Equals(BigInteger.One))
            {
                Fail("CRL cert serial number does not match");
            }

            if (!entry.HasExtensions)
            {
                Fail("CRL entry extension not found");
            }

            Asn1OctetString ext = entry.GetExtensionValue(X509Extensions.ReasonCode);

            if (ext != null)
            {
                DerEnumerated reasonCode = (DerEnumerated)X509ExtensionUtilities.FromExtensionValue(ext);

                if (reasonCode.Value.IntValue != CrlReason.PrivilegeWithdrawn)
                {
                    Fail("CRL entry reasonCode wrong");
                }
            }
            else
            {
                Fail("CRL entry reasonCode not found");
            }

            //
            // check loading of existing CRL
            //
            crlGen = new X509V2CrlGenerator();
            now = DateTime.UtcNow;

            crlGen.SetIssuerDN(new X509Name("CN=Test CA"));

            crlGen.SetThisUpdate(now);
            crlGen.SetNextUpdate(now.AddSeconds(100));
            crlGen.SetSignatureAlgorithm("SHA256WithRSAEncryption");

            crlGen.AddCrl(crl);

            crlGen.AddCrlEntry(BigInteger.Two, now, entryExtensions);

            crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.Public));

            X509Crl newCrl = crlGen.Generate(pair.Private);

            int count = 0;
            bool oneFound = false;
            bool twoFound = false;

            foreach (X509CrlEntry crlEnt in newCrl.GetRevokedCertificates())
            {
                if (crlEnt.SerialNumber.IntValue == 1)
                {
                    oneFound = true;
                }
                else if (crlEnt.SerialNumber.IntValue == 2)
                {
                    twoFound = true;
                }

                count++;
            }

            if (count != 2)
            {
                Fail("wrong number of CRLs found");
            }

            if (!oneFound || !twoFound)
            {
                Fail("wrong CRLs found in copied list");
            }

            //
            // check factory read back
            //
            X509Crl readCrl = new X509CrlParser().ReadCrl(newCrl.GetEncoded());

            if (readCrl == null)
            {
                Fail("crl not returned!");
            }

//			ICollection col = cFact.generateCRLs(new ByteArrayInputStream(newCrl.getEncoded()));
            ICollection col = new X509CrlParser().ReadCrls(newCrl.GetEncoded());

            if (col.Count != 1)
            {
                Fail("wrong number of CRLs found in collection");
            }
        }
		static X509Crl DecodeX509Crl (IDataRecord reader, X509CrlParser parser, int column, ref byte[] buffer)
		{
			int nread = ReadBinaryBlob (reader, column, ref buffer);

			using (var memory = new MemoryStream (buffer, 0, nread, false)) {
				return parser.ReadCrl (memory);
			}
		}
Exemple #22
0
        private void pkcs7Test()
        {
            Asn1Encodable rootCert = Asn1Object.FromByteArray(CertPathTest.rootCertBin);
            Asn1Encodable rootCrl = Asn1Object.FromByteArray(CertPathTest.rootCrlBin);

            X509CertificateParser certParser = new X509CertificateParser();
            X509CrlParser crlParser = new X509CrlParser();

            SignedData sigData = new SignedData(
                DerSet.Empty,
                new ContentInfo(CmsObjectIdentifiers.Data, null),
                new DerSet(
                    rootCert,
                    new DerTaggedObject(false, 2, Asn1Object.FromByteArray(AttrCertTest.attrCert))),
                new DerSet(rootCrl),
                DerSet.Empty);

            ContentInfo info = new ContentInfo(CmsObjectIdentifiers.SignedData, sigData);

            X509Certificate cert = certParser.ReadCertificate(info.GetEncoded());
            if (cert == null || !AreEqual(cert.GetEncoded(), rootCert.ToAsn1Object().GetEncoded()))
            {
                Fail("PKCS7 cert not read");
            }
            X509Crl crl = crlParser.ReadCrl(info.GetEncoded());
            if (crl == null || !AreEqual(crl.GetEncoded(), rootCrl.ToAsn1Object().GetEncoded()))
            {
                Fail("PKCS7 crl not read");
            }
            ArrayList col = new ArrayList(certParser.ReadCertificates(info.GetEncoded()));
            if (col.Count != 1 || !col.Contains(cert))
            {
                Fail("PKCS7 cert collection not right");
            }
            col = new ArrayList(crlParser.ReadCrls(info.GetEncoded()));
            if (col.Count != 1 || !col.Contains(crl))
            {
                Fail("PKCS7 crl collection not right");
            }

            // data with no certificates or CRLs

            sigData = new SignedData(DerSet.Empty, new ContentInfo(CmsObjectIdentifiers.Data, null), DerSet.Empty, DerSet.Empty, DerSet.Empty);

            info = new ContentInfo(CmsObjectIdentifiers.SignedData, sigData);

            cert = certParser.ReadCertificate(info.GetEncoded());
            if (cert != null)
            {
                Fail("PKCS7 cert present");
            }
            crl = crlParser.ReadCrl(info.GetEncoded());
            if (crl != null)
            {
                Fail("PKCS7 crl present");
            }

            // data with absent certificates and CRLS

            sigData = new SignedData(DerSet.Empty, new ContentInfo(CmsObjectIdentifiers.Data, null), null, null, DerSet.Empty);

            info = new ContentInfo(CmsObjectIdentifiers.SignedData, sigData);

            cert = certParser.ReadCertificate(info.GetEncoded());
            if (cert != null)
            {
                Fail("PKCS7 cert present");
            }
            crl = crlParser.ReadCrl(info.GetEncoded());
            if (crl != null)
            {
                Fail("PKCS7 crl present");
            }

            //
            // sample message
            //
            ICollection certCol = certParser.ReadCertificates(pkcs7CrlProblem);
            ICollection crlCol = crlParser.ReadCrls(pkcs7CrlProblem);

            if (crlCol.Count != 0)
            {
                Fail("wrong number of CRLs: " + crlCol.Count);
            }

            if (certCol.Count != 4)
            {
                Fail("wrong number of Certs: " + certCol.Count);
            }
        }
		X509CrlRecord LoadCrlRecord (IDataRecord reader, X509CrlParser parser, ref byte[] buffer)
		{
			var record = new X509CrlRecord ();

			for (int i = 0; i < reader.FieldCount; i++) {
				switch (reader.GetName (i).ToUpperInvariant ()) {
				case "CRL":
					record.Crl = DecodeX509Crl (reader, parser, i, ref buffer);
					break;
				case "THISUPDATE":
					record.ThisUpdate = reader.GetDateTime (i);
					break;
				case "NEXTUPDATE":
					record.NextUpdate = reader.GetDateTime (i);
					break;
				case "DELTA":
					record.IsDelta = reader.GetBoolean (i);
					break;
				case "ID":
					record.Id = reader.GetInt32 (i);
					break;
				}
			}

			return record;
		}
Exemple #24
0
		public void TestDirectCrl()
		{
			X509Crl crl = new X509CrlParser().ReadCrl(directCrl);

			foreach (X509CrlEntry crlEntry in crl.GetRevokedCertificates())
			{
				if (crlEntry.GetCertificateIssuer() != null)
				{
					Fail("certificate issuer CRL entry extension is not null");
				}
			}
		}
Exemple #25
0
        /// <summary>
        /// Zertifikatsperrliste vom OSTC-Server laden
        /// </summary>
        /// <param name="certType">Art des Zertifikats (SHA1 oder SHA256)</param>
        /// <param name="preferFtp">FTP-Server-Download bevorzugen?</param>
        /// <returns>Zertifikatsperrliste</returns>
        public async Task<X509Crl> DownloadCrlAsync(OstcCertificateType certType, bool preferFtp = true)
        {
            Uri downloadUrl = null;
            if ((certType & OstcCertificateType.Sha1) == OstcCertificateType.Sha1)
                downloadUrl = new Uri("ftp://trustcenter-ftp.itsg.de/agv/sperrliste-ag.crl");
            else if ((certType & OstcCertificateType.Sha256) == OstcCertificateType.Sha256)
                downloadUrl = new Uri("ftp://trustcenter-ftp.itsg.de/agv/sperrliste-ag-sha256.crl");

            Debug.Assert(downloadUrl != null);

            var data = await DownloadAsync(downloadUrl);

            var crlParser = new X509CrlParser();
            var crl = crlParser.ReadCrl(data);

            return crl;
        }