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); } } }
/// <summary> /// Retrieve the current CRL /// </summary> /// <returns>The current CRL</returns> public X509Crl GetCRL() { X509CrlParser crlp = new X509CrlParser(); try { return(crlp.ReadCrl(File.ReadAllBytes(crlFileLocation))); } catch (FileNotFoundException ex) { LogEvent.WriteEvent(eventLog, LogEvent.EventType.Error, "CRL not found: " + ex.Message); return(null); } catch (IOException ex) { LogEvent.WriteEvent(eventLog, LogEvent.EventType.Error, "CRL not found: " + ex.Message); return(null); } }
/// <summary> /// Gets a certificate revocation list store. /// </summary> /// <remarks> /// Gets a certificate revocation list store. /// </remarks> /// <returns>A certificate revocation list store.</returns> public IX509Store GetCrlStore() { var crls = new List <X509Crl> (); using (var command = GetSelectAllCrlsCommand()) { using (var reader = command.ExecuteReader()) { var parser = new X509CrlParser(); var buffer = new byte[4096]; while (reader.Read()) { var record = LoadCrlRecord(reader, parser, ref buffer); crls.Add(record.Crl); } } } return(X509StoreFactory.Create("Crl/Collection", new X509CollectionStoreParameters(crls))); }
public ValidationResponse ValidateCertificate(X509Certificate2 certificate, String urlCRL) { try { byte[] crl = transferHttpDataService.GetFile(urlCRL); X509Crl x509crl = new X509CrlParser().ReadCrl(crl); Org.BouncyCastle.X509.X509Certificate certificateBC = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(certificate); X509CrlEntry crlEntry = x509crl.GetRevokedCertificate(certificateBC.SerialNumber); if (crlEntry != null) { return(new ValidationResponse(CertificateStatus.REVOKED, crlEntry.RevocationDate)); } return(new ValidationResponse(CertificateStatus.VALID)); } catch (CommunicationException) { return(new ValidationResponse(CertificateStatus.UNKNOWN)); } }
public CertificateCrlValidator(string pfx, string crl) { System.Security.Cryptography.X509Certificates.X509Certificate2 acertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(pfx, "", System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable | System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.PersistKeySet); CACert = DotNetUtilities.FromX509Certificate(acertificate); // Now you have your private key in binary form as you wanted // You can use rsa.ExportParameters() or rsa.ExportCspBlob() to get you bytes // depending on format you need them in RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)acertificate.PrivateKey; // Just for lulz, let's write out the PEM representation of the private key // using Bouncy Castle, so that we are 100% sure that the result is exaclty the same as: // openssl pkcs12 -in filename.pfx -nocerts -out privateKey.pem // openssl.exe rsa -in privateKey.pem -out private.pem AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetRsaKeyPair(rsa); CAKey = keyPair.Private; Crl = new X509CrlParser().ReadCrl(File.ReadAllBytes(crl)); }
//Отдает содержимое Crl-файла в виде структуры CrlInfo: public CrlInfo GetCrlInfoAsStructure(string fileName) { try { byte[] buf = ReadFile(fileName); X509CrlParser clrParser = new X509CrlParser(); X509Crl crl = clrParser.ReadCrl(buf); var issuer = crl.IssuerDN; var signature = crl.GetSignature(); DateTime nextupdate = crl.NextUpdate.Value; DateTime thisUpdate = crl.ThisUpdate; //Console.WriteLine("Issuerdata.tostring = {0}", issuer.ToString()); //Console.WriteLine("Signature.ToString = {0}", signature.ToString()); //Console.WriteLine("NextUpdate = {0}", nextupdate.ToString()); //Console.WriteLine("ThisUpdate = {0}", thisUpdate); Logger.Write($"Извлечение данных из crl-файла: {fileName}"); Logger.Write($"issuer: {issuer}"); Logger.Write($"signature: {signature}"); Logger.Write($"nextupdate: {nextupdate}"); Logger.Write($"thisupdate: {thisUpdate}"); CrlInfo CrlInfo = new CrlInfo(issuer.ToString(), signature, nextupdate, thisUpdate); return(CrlInfo); } catch (Exception ex) { Crlinfo = new CrlInfo(); Logger.Write(ex.Message); return(Crlinfo); } }
/// <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(nameof(issuer)); } using (var command = GetSelectCommand(issuer, fields)) { using (var reader = command.ExecuteReader()) { var parser = new X509CrlParser(); var buffer = new byte[4096]; while (reader.Read()) { yield return(LoadCrlRecord(reader, parser, ref buffer)); } } } yield break; }
/// <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(nameof(crl)); } using (var command = GetSelectCommand(crl, fields)) { using (var reader = command.ExecuteReader()) { if (reader.Read()) { var parser = new X509CrlParser(); var buffer = new byte[4096]; return(LoadCrlRecord(reader, parser, ref buffer)); } } } return(null); }
/// <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); } }
/** * Fetches a CRL for a specific certificate online (without further checking). * @param signCert the certificate * @param issuerCert its issuer * @return an X509CRL object */ virtual 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 X509Crl GetCrlFromFS(string downloadUrl) { if (downloadUrl != null) { try { using (var input = File.OpenRead(downloadUrl)) { X509CrlParser parser = new X509CrlParser(); X509Crl crl = parser.ReadCrl(input); logger.Info("CRL size: " + crl.GetEncoded().Length + " bytes"); return(crl); } } catch (CannotFetchDataException) { return(null); } } else { return(null); } }
/** * 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); }
public CrlValidator(ILogger <CrlValidator> log) { _log = log; _x509CrlParser = new X509CrlParser(); _certificateParser = new X509CertificateParser(); }
/** * 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(); }
/// <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); }
/// <summary> /// Revoke the CA signed certificate. /// The issuer CA public key, the private key and the crl reside in the storepath. /// The CRL number is increased by one and existing CRL for the issuer are deleted from the store. /// </summary> public static async Task <X509CRL> RevokeCertificateAsync( string storePath, X509Certificate2 certificate, string issuerKeyFilePassword = null ) { X509CRL updatedCRL = null; try { string subjectName = certificate.IssuerName.Name; string keyId = null; string serialNumber = null; // caller may want to create empty CRL using the CA cert itself bool isCACert = IsCertificateAuthority(certificate); // find the authority key identifier. X509AuthorityKeyIdentifierExtension authority = FindAuthorityKeyIdentifier(certificate); if (authority != null) { keyId = authority.KeyId; serialNumber = authority.SerialNumber; } else { throw new ArgumentException("Certificate does not contain an Authority Key"); } if (!isCACert) { if (serialNumber == certificate.SerialNumber || Utils.CompareDistinguishedName(certificate.Subject, certificate.Issuer)) { throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Cannot revoke self signed certificates"); } } X509Certificate2 certCA = null; using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(storePath)) { if (store == null) { throw new ArgumentException("Invalid store path/type"); } certCA = await FindIssuerCABySerialNumberAsync(store, certificate.Issuer, serialNumber); if (certCA == null) { throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Cannot find issuer certificate in store."); } if (!certCA.HasPrivateKey) { throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Issuer certificate has no private key, cannot revoke certificate."); } CertificateIdentifier certCAIdentifier = new CertificateIdentifier(certCA); certCAIdentifier.StorePath = storePath; certCAIdentifier.StoreType = CertificateStoreIdentifier.DetermineStoreType(storePath); X509Certificate2 certCAWithPrivateKey = await certCAIdentifier.LoadPrivateKey(issuerKeyFilePassword); if (certCAWithPrivateKey == null) { throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Failed to load issuer private key. Is the password correct?"); } List <X509CRL> certCACrl = store.EnumerateCRLs(certCA, false); using (var cfrg = new CertificateFactoryRandomGenerator()) { // cert generators SecureRandom random = new SecureRandom(cfrg); BigInteger crlSerialNumber = BigInteger.Zero; Org.BouncyCastle.X509.X509Certificate bcCertCA = new X509CertificateParser().ReadCertificate(certCA.RawData); AsymmetricKeyParameter signingKey = GetPrivateKeyParameter(certCAWithPrivateKey); ISignatureFactory signatureFactory = new Asn1SignatureFactory(GetRSAHashAlgorithm(defaultHashSize), signingKey, random); X509V2CrlGenerator crlGen = new X509V2CrlGenerator(); crlGen.SetIssuerDN(bcCertCA.IssuerDN); crlGen.SetThisUpdate(DateTime.UtcNow); crlGen.SetNextUpdate(DateTime.UtcNow.AddMonths(12)); // merge all existing revocation list X509CrlParser parser = new X509CrlParser(); foreach (X509CRL caCrl in certCACrl) { X509Crl crl = parser.ReadCrl(caCrl.RawData); crlGen.AddCrl(crl); var crlVersion = GetCrlNumber(crl); if (crlVersion.IntValue > crlSerialNumber.IntValue) { crlSerialNumber = crlVersion; } } if (isCACert) { // add a dummy revoked cert crlGen.AddCrlEntry(BigInteger.One, DateTime.UtcNow, CrlReason.Superseded); } else { // add the revoked cert crlGen.AddCrlEntry(GetSerialNumber(certificate), DateTime.UtcNow, CrlReason.PrivilegeWithdrawn); } crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(bcCertCA)); // set new serial number crlSerialNumber = crlSerialNumber.Add(BigInteger.One); crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(crlSerialNumber)); // generate updated CRL X509Crl updatedCrl = crlGen.Generate(signatureFactory); // add updated CRL to store updatedCRL = new X509CRL(updatedCrl.GetEncoded()); store.AddCRL(updatedCRL); // delete outdated CRLs from store foreach (X509CRL caCrl in certCACrl) { store.DeleteCRL(caCrl); } } store.Close(); } } catch (Exception e) { throw e; } return(updatedCRL); }
public static void Main(String[] args) { DirectoryInfo directory = new DirectoryInfo(DEST); directory.Create(); Properties properties = new Properties(); // Specify the correct path to the certificate properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open, FileAccess.Read)); String path = properties.GetProperty("PRIVATE"); char[] pass = properties.GetProperty("PASSWORD").ToCharArray(); Pkcs12Store pk12 = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), pass); string alias = null; foreach (var a in pk12.Aliases) { alias = ((string)a); if (pk12.IsKeyEntry(alias)) { break; } } ICipherParameters pk = pk12.GetKey(alias).Key; X509CertificateEntry[] ce = pk12.GetCertificateChain(alias); X509Certificate[] chain = new X509Certificate[ce.Length]; for (int k = 0; k < ce.Length; ++k) { chain[k] = ce[k].Certificate; } FileStream fileStream = new FileStream(CRLURL, FileMode.Open, FileAccess.Read); MemoryStream baos = new MemoryStream(); byte[] buf = new byte[1024]; while (fileStream.Read(buf, 0, buf.Length) != 0) { baos.Write(buf, 0, buf.Length); } /* Create a CrlClientOffline instance with the read CRL file's data. * Given CRL file is specific to the CAcert provider and was downloaded long time ago. * Make sure that you have the CRL specific for your certificate and CRL is up to date * (by checking NextUpdate properties as seen below). */ ICrlClient crlClient = new CrlClientOffline(baos.ToArray()); X509Crl crl = new X509CrlParser().ReadCrl(new FileStream(CRLURL, FileMode.Open, FileAccess.Read)); Console.WriteLine("CRL valid until: " + crl.NextUpdate); Console.WriteLine("Certificate revoked: " + crl.IsRevoked(chain[0])); IList <ICrlClient> crlList = new List <ICrlClient>(); crlList.Add(crlClient); new C3_05_SignWithCRLOffline().Sign(SRC, DEST + RESULT_FILES[0], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Test", "Ghent", crlList, null, null, 0); }
public static bool certificateValid(string certificateLocation) { FileStream fs = new FileStream(certificateLocation, FileMode.Open); X509CertificateParser certParser = new X509CertificateParser(); X509Certificate userCertificate = certParser.ReadCertificate(fs); fs.Close(); string CA = Application.Current.Properties["CA"].ToString(); string CRL = Application.Current.Properties["CRL"].ToString(); fs = new FileStream(CA, FileMode.Open); X509Certificate CACertificate = certParser.ReadCertificate(fs); fs.Close(); X509CrlParser crlParser = new X509CrlParser(); fs = new FileStream(CRL, FileMode.Open); X509Crl CRLCertificate = crlParser.ReadCrl(fs); fs.Close(); //verify that the certificate is signed by the CA try { userCertificate.Verify(CACertificate.GetPublicKey()); } catch (GeneralSecurityException) { MessageBox.Show("Your certificate is not signed by an authorized CA"); return(false); } //verify that the crl is signed by the CA try { CRLCertificate.Verify(CACertificate.GetPublicKey()); } catch (GeneralSecurityException) { MessageBox.Show("Your CRL is not signed by an authorized CA"); return(false); } //verify that the certificate is not revoked if (CRLCertificate.IsRevoked(userCertificate)) { MessageBox.Show("Your certificate has been revoked"); return(false); } //verify the certificate time validity if (!userCertificate.IsValidNow) { MessageBox.Show("Your certificate is not valid"); return(false); } return(true); }
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(); }
bool certTesting() { Console.WriteLine("Unesite putanju do certifikata!"); X509Certificate2 x509 = new X509Certificate2(); pathOfCert = Console.ReadLine(); //Create X509Certificate2 object from .pem file. try { byte[] rawData = ReadFile(pathOfCert); x509.Import(rawData); var cert = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(x509.GetRawCertData()); bool[] keyUsage = cert.GetKeyUsage(); foreach (bool key in keyUsage) { Console.WriteLine("OK{0}", key); } byte[] buf = ReadFile("lista1.pem"); X509CrlParser xx = new X509CrlParser(); X509Crl ss = xx.ReadCrl(buf); var nextupdate = ss.NextUpdate; var isRevoked = ss.IsRevoked(cert); //Console.WriteLine("{0} {1}", nextupdate, isRevoked); DateTime dateNow = DateTime.Now; //Da uporedimo jel lista jos dalje aktivna! DateTime dateList = nextupdate.Value; if (dateNow.Date > dateList.Date) { Console.WriteLine("Izabrata CRL lista je outOfDate,prosledite novu,za dalji rad!"); return(false); } else if (isRevoked == true) { Console.WriteLine("Certefikat je povucen i ne moze se koristit!\nZelite odabrati drugi certifikat"); string decision = Console.ReadLine(); if (decision == "Y" || decision == "y") { Console.Clear(); certTesting(); } else { return(false); } } //DODATI OVDE JOS else if za provjeru za sta se key certifikata moze koristit! //i ako je uredan ispisati da je cert uredan } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("Nepravilan odabir certifikata!\nZelite opet probati (Y/N)"); string decision = Console.ReadLine(); if (decision == "Y" || decision == "y") { Console.Clear(); certTesting(); } else { return(false); } } return(true); }
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); //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"); } }
public override void PerformTest() { X509CertificateParser certParser = new X509CertificateParser(); X509CrlParser crlParser = new X509CrlParser(); // initialise CertStore X509Certificate rootCert = certParser.ReadCertificate(CertPathTest.rootCertBin); X509Certificate interCert = certParser.ReadCertificate(CertPathTest.interCertBin); X509Certificate finalCert = certParser.ReadCertificate(CertPathTest.finalCertBin); X509Crl rootCrl = crlParser.ReadCrl(CertPathTest.rootCrlBin); X509Crl interCrl = crlParser.ReadCrl(CertPathTest.interCrlBin); IList x509Certs = new ArrayList(); x509Certs.Add(rootCert); x509Certs.Add(interCert); x509Certs.Add(finalCert); IList x509Crls = new ArrayList(); x509Crls.Add(rootCrl); x509Crls.Add(interCrl); // CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list); // CertStore store = CertStore.GetInstance("Collection", ccsp); // X509CollectionStoreParameters ccsp = new X509CollectionStoreParameters(list); IX509Store x509CertStore = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(x509Certs)); IX509Store x509CrlStore = X509StoreFactory.Create( "CRL/Collection", new X509CollectionStoreParameters(x509Crls)); // NB: Month is 1-based in .NET //DateTime validDate = new DateTime(2008,9,4,14,49,10).ToUniversalTime(); DateTime validDate = new DateTime(2008, 9, 4, 5, 49, 10); //validating path IList certchain = new ArrayList(); certchain.Add(finalCert); certchain.Add(interCert); // CertPath cp = CertificateFactory.GetInstance("X.509").GenerateCertPath(certchain); PkixCertPath cp = new PkixCertPath(certchain); ISet trust = new HashSet(); trust.Add(new TrustAnchor(rootCert, null)); // CertPathValidator cpv = CertPathValidator.GetInstance("PKIX"); PkixCertPathValidator cpv = new PkixCertPathValidator(); PkixParameters param = new PkixParameters(trust); param.AddStore(x509CertStore); param.AddStore(x509CrlStore); param.Date = new DateTimeObject(validDate); MyChecker checker = new MyChecker(); param.AddCertPathChecker(checker); PkixCertPathValidatorResult result = (PkixCertPathValidatorResult)cpv.Validate(cp, param); PkixPolicyNode policyTree = result.PolicyTree; AsymmetricKeyParameter subjectPublicKey = result.SubjectPublicKey; if (checker.GetCount() != 2) { Fail("checker not evaluated for each certificate"); } if (!subjectPublicKey.Equals(finalCert.GetPublicKey())) { Fail("wrong public key returned"); } IsTrue(result.TrustAnchor.TrustedCert.Equals(rootCert)); // try a path with trust anchor included. certchain.Clear(); certchain.Add(finalCert); certchain.Add(interCert); certchain.Add(rootCert); cp = new PkixCertPath(certchain); cpv = new PkixCertPathValidator(); param = new PkixParameters(trust); param.AddStore(x509CertStore); param.AddStore(x509CrlStore); param.Date = new DateTimeObject(validDate); checker = new MyChecker(); param.AddCertPathChecker(checker); result = (PkixCertPathValidatorResult)cpv.Validate(cp, param); IsTrue(result.TrustAnchor.TrustedCert.Equals(rootCert)); // // invalid path containing a valid one test // try { // initialise CertStore rootCert = certParser.ReadCertificate(AC_RAIZ_ICPBRASIL); interCert = certParser.ReadCertificate(AC_PR); finalCert = certParser.ReadCertificate(schefer); x509Certs = new ArrayList(); x509Certs.Add(rootCert); x509Certs.Add(interCert); x509Certs.Add(finalCert); // ccsp = new CollectionCertStoreParameters(list); // store = CertStore.GetInstance("Collection", ccsp); // ccsp = new X509CollectionStoreParameters(list); x509CertStore = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(x509Certs)); // NB: Month is 1-based in .NET //validDate = new DateTime(2004,3,21,2,21,10).ToUniversalTime(); validDate = new DateTime(2004, 3, 20, 19, 21, 10); //validating path certchain = new ArrayList(); certchain.Add(finalCert); certchain.Add(interCert); // cp = CertificateFactory.GetInstance("X.509").GenerateCertPath(certchain); cp = new PkixCertPath(certchain); trust = new HashSet(); trust.Add(new TrustAnchor(rootCert, null)); // cpv = CertPathValidator.GetInstance("PKIX"); cpv = new PkixCertPathValidator(); param = new PkixParameters(trust); param.AddStore(x509CertStore); param.IsRevocationEnabled = false; param.Date = new DateTimeObject(validDate); result = (PkixCertPathValidatorResult)cpv.Validate(cp, param); policyTree = result.PolicyTree; subjectPublicKey = result.SubjectPublicKey; Fail("Invalid path validated"); } catch (Exception e) { if (e is PkixCertPathValidatorException && e.Message.StartsWith("Could not validate certificate signature.")) { return; } Fail("unexpected exception", e); } }
private string step_4(string filename) //TODO: Overenie časovej pečiatky { XmlDocument xades = new XmlDocument(); xades.Load(filename); var namespaceId = new XmlNamespaceManager(xades.NameTable); namespaceId.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#"); namespaceId.AddNamespace("xades", "http://uri.etsi.org/01903/v1.3.2#"); string timestamp = xades.SelectSingleNode("//xades:EncapsulatedTimeStamp", namespaceId).InnerText; byte[] newBytes = Convert.FromBase64String(timestamp); byte[] signatureCertificate = Convert.FromBase64String(xades.SelectSingleNode(@"//ds:KeyInfo/ds:X509Data/ds:X509Certificate", namespaceId).InnerText); X509CertificateParser x509parser = new X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate x509cert = x509parser.ReadCertificate(signatureCertificate); string signedInfoSignatureAlg = xades.SelectSingleNode(@"//ds:SignedInfo/ds:SignatureMethod", namespaceId).Attributes.GetNamedItem("Algorithm").Value; byte[] signature = Convert.FromBase64String(xades.SelectSingleNode(@"//ds:SignatureValue", namespaceId).InnerText); TimeStampToken token = new TimeStampToken(new Org.BouncyCastle.Cms.CmsSignedData(newBytes)); try { Org.BouncyCastle.X509.X509Certificate signerCert = null; Org.BouncyCastle.X509.Store.IX509Store x509Certs = token.GetCertificates("Collection"); ArrayList certs = new ArrayList(x509Certs.GetMatches(null)); // nájdenie podpisového certifikátu tokenu v kolekcii foreach (Org.BouncyCastle.X509.X509Certificate cert in certs) { string cerIssuerName = cert.IssuerDN.ToString(true, new Hashtable()); string signerIssuerName = token.SignerID.Issuer.ToString(true, new Hashtable()); // kontrola issuer name a seriového čísla if (cerIssuerName == signerIssuerName && cert.SerialNumber.Equals(token.SignerID.SerialNumber)) { signerCert = cert; break; } } //check certificate, UtcNow int result1 = DateTime.Compare(signerCert.NotAfter, DateTime.UtcNow); int result2 = DateTime.Compare(DateTime.UtcNow, signerCert.NotBefore); //check x509 certtificate, timestamtoken.GenTime int result3 = DateTime.Compare(x509cert.NotAfter, token.TimeStampInfo.TstInfo.GenTime.ToDateTime()); int result4 = DateTime.Compare(token.TimeStampInfo.TstInfo.GenTime.ToDateTime(), x509cert.NotBefore); if (result1 < 0) { return("platnosť certifikátu vypršala"); } if (result2 < 0) { return("certifikát nenadobúdol platnosť"); } if (result3 < 0) { return("platnosť podpisového certifikátu v čase T vypršala"); } if (result4 < 0) { return("platnosť podpisového certifikátu v čase T nenadobudla plastnosť"); } /* * Console.WriteLine("step4"); * //check messageImprint against SignatureValue * string errMsg = ""; * bool res = this.verifySign(signatureCertificate, signature, token.TimeStampInfo.GetMessageImprintDigest(), signedInfoSignatureAlg, out errMsg); * if (!res) * { * Console.WriteLine("Error " + errMsg); * return errMsg; * } */ //check certificate, CRL byte[] buf1 = File.ReadAllBytes("./Crl/certCasvovejPeciatky.crl"); X509CrlParser parserCrl1 = new X509CrlParser(); X509Crl readCrl1 = parserCrl1.ReadCrl(buf1); if (readCrl1.IsRevoked(signerCert)) { return("certifikát je neplatný"); } //check certificate, CRL byte[] buf2 = File.ReadAllBytes("./Crl/dtctsa.crl"); X509CrlParser parserCrl2 = new X509CrlParser(); X509Crl readCrl2 = parserCrl2.ReadCrl(buf2); if (readCrl2.IsRevoked(x509cert)) { return("certifikát je neplatný"); } } catch (Exception e) { return(e.Message.ToString()); } return("OK"); }
/* * private void verifyTimestamp(TimeStampToken token, X509CRL crl) throws SignVerificationException, XPathExpressionException { * // Read timestamp signature certificate * X509CertificateHolder signCert = getTimestampSignatureCertificate(token); * if (signCert == null) { * throw new SignVerificationException("Cannot retrieve timestamp signature certificate (Rule 26)."); * } * * // Rule 26 - Validity * // Check current certificate validity * if (!signCert.isValidOn(new Date())) { * throw new SignVerificationException("Timestamp signature certificate is not valid now (Rule 26)."); * } * * // Check against CRL * X509CRLEntry entry = crl.getRevokedCertificate(signCert.getSerialNumber()); * if (entry != null) { * throw new SignVerificationException("Timestamp signature certificate is revoked (Rule 26)."); * } * * // Rule 27 - Message imprint * byte[] timestampDigest = token.getTimeStampInfo().getMessageImprintDigest(); * String hashAlgorithm = token.getTimeStampInfo().getHashAlgorithm().getAlgorithm().getId(); * * Element signature = querySelector("//ds:Signature/ds:SignatureValue", "Cannot find element 'ds:SignatureValue' (Rule 27)."); * byte[] signatureValue = Base64.decode(signature.getTextContent().getBytes()); * * MessageDigest messageDigest = null; * try { * messageDigest = MessageDigest.getInstance(hashAlgorithm, "BC"); * } catch (NoSuchAlgorithmException | NoSuchProviderException e) { * throw new SignVerificationException("Unsupported digest type (Rule 27)."); * } * * byte[] signatureDigest = messageDigest.digest(signatureValue); * if (!Arrays.equals(timestampDigest, signatureDigest)) { * throw new SignVerificationException("Timestamp MessageImprint check failure (Rule 27)."); * } * }*/ private bool validateTimestamp() { TimeStampToken token = null; X509Crl ss = null; XmlNamespaceManager mn = new XmlNamespaceManager(doc.NameTable); X509CrlParser xx = new X509CrlParser(); mn.AddNamespace("xades", "http://uri.etsi.org/01903/v1.3.2#"); string crlUrl = "http://test.ditec.sk/DTCCACrl/DTCCACrl.crl"; Org.BouncyCastle.X509.X509Certificate signerCert = null; try { var timestamp = this.doc.SelectSingleNode($"//xades:EncapsulatedTimeStamp", mn); var webClient = new WebClient(); byte[] crlBytes = webClient.DownloadData(crlUrl); token = new TimeStampToken(new CmsSignedData(Convert.FromBase64String(timestamp.InnerText))); ss = xx.ReadCrl(crlBytes); if (timestamp == null || crlBytes == null || token == null || ss == null) { generalException(new Exception()); return(false); } var store = token.GetCertificates("Collection"); var certs = new ArrayList(store.GetMatches(null)); foreach (Org.BouncyCastle.X509.X509Certificate cert in certs) { string cerIssuer = cert.IssuerDN.ToString(true, new Hashtable()); string signIssuer = token.SignerID.Issuer.ToString(true, new Hashtable()); if (cerIssuer == signIssuer && cert.SerialNumber.Equals(token.SignerID.SerialNumber)) { signerCert = cert; if (signerCert == null) { generalException(new Exception()); return(false); } break; } } if (!signerCert.IsValidNow) { return(false); } X509CrlEntry revokeCheck = ss.GetRevokedCertificate(signerCert.SerialNumber); if (revokeCheck == null) { generalException(new Exception()); return(false); } } catch (Exception e) { generalException(e); } return(false); }
/// <summary> /// Revoke the certificate. /// The CRL number is increased by one and the new CRL is returned. /// </summary> public static X509CRL RevokeCertificate( X509Certificate2 issuerCertificate, List <X509CRL> issuerCrls, X509Certificate2Collection revokedCertificates ) { if (!issuerCertificate.HasPrivateKey) { throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Issuer certificate has no private key, cannot revoke certificate."); } using (var cfrg = new CertificateFactoryRandomGenerator()) { // cert generators SecureRandom random = new SecureRandom(cfrg); BigInteger crlSerialNumber = BigInteger.Zero; Org.BouncyCastle.X509.X509Certificate bcCertCA = new X509CertificateParser().ReadCertificate(issuerCertificate.RawData); AsymmetricKeyParameter signingKey = GetPrivateKeyParameter(issuerCertificate); ISignatureFactory signatureFactory = new Asn1SignatureFactory(GetRSAHashAlgorithm(defaultHashSize), signingKey, random); X509V2CrlGenerator crlGen = new X509V2CrlGenerator(); crlGen.SetIssuerDN(bcCertCA.IssuerDN); crlGen.SetThisUpdate(DateTime.UtcNow); crlGen.SetNextUpdate(DateTime.UtcNow.AddMonths(12)); // merge all existing revocation list if (issuerCrls != null) { X509CrlParser parser = new X509CrlParser(); foreach (X509CRL issuerCrl in issuerCrls) { X509Crl crl = parser.ReadCrl(issuerCrl.RawData); crlGen.AddCrl(crl); var crlVersion = GetCrlNumber(crl); if (crlVersion.IntValue > crlSerialNumber.IntValue) { crlSerialNumber = crlVersion; } } } DateTime now = DateTime.UtcNow; if (revokedCertificates == null || revokedCertificates.Count == 0) { // add a dummy revoked cert crlGen.AddCrlEntry(BigInteger.One, now, CrlReason.Unspecified); } else { // add the revoked cert foreach (var revokedCertificate in revokedCertificates) { crlGen.AddCrlEntry(GetSerialNumber(revokedCertificate), now, CrlReason.PrivilegeWithdrawn); } } crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(bcCertCA)); // set new serial number crlSerialNumber = crlSerialNumber.Add(BigInteger.One); crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(crlSerialNumber)); // generate updated CRL X509Crl updatedCrl = crlGen.Generate(signatureFactory); return(new X509CRL(updatedCrl.GetEncoded())); } }