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