예제 #1
0
        private void baseTest()
        {
//			CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
            X509CertificateParser certParser = new X509CertificateParser();
            X509CrlParser         crlParser  = new X509CrlParser();

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

            IList certList = new ArrayList();

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

            IList crlList = new ArrayList();

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

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

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

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

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

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

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

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

            if (path.Certificates.Count != 2)
            {
                Fail("wrong number of certs in baseTest path");
            }
        }
예제 #2
0
        private X509Crl retreiveCrlUrl(string url, string cachePath, bool force = false)
        {
            X509Crl rootCrl = null;

            RetreiveCRL.GetCRL client = new RetreiveCRL.GetCRL();
            client.CachePath = cachePath;

            if (force)
            {
                client.NoCache = true;
            }

            client.GetCRLFromDistributionList(url);
            if (client.CertificationRevocationListBinary != null)
            {
                byte[]        contCRL   = client.CertificationRevocationListBinary;
                X509CrlParser crlParser = new X509CrlParser();
                //Carico la CRL nel reader
                rootCrl = crlParser.ReadCrl(contCRL);

                if (rootCrl.NextUpdate.Value.ToLocalTime() < DateTime.Now) //la crl è scaduta la riscarico.
                {
                    client.NoCache = true;
                    client.GetCRLFromDistributionList(url);
                    contCRL = client.CertificationRevocationListBinary;
                    rootCrl = crlParser.ReadCrl(contCRL);
                }
            }
            return(rootCrl);
        }
예제 #3
0
        protected X509Crl Download(string url)
        {
            try
            {
                if (Regex.IsMatch(url, "http[s]{0,1}://.*"))
                {
                    if (certificateFactory == null)
                    {
                        certificateFactory = new X509CrlParser();
                    }

                    WebClient wc   = new WebClient();
                    var       data = wc.DownloadData(url);

                    X509Crl crl = certificateFactory.ReadCrl(data);
                    this.crlCache.Set(url, crl);
                    return(crl);
                }
                else if (url.StartsWith("ldap://"))
                {
                    // Currently not supported.
                    return(null);
                }
            }
            catch (Exception e)
            {
                throw new CertificateValidationException($"Failed to download CRL '{url}' ({e.Message})", e);
            }

            return(null);
        }
예제 #4
0
        private void AddCrlsFromSet(global::System.Collections.IList crls, Asn1Set crlSet)
        {
            X509CrlParser x509CrlParser = new X509CrlParser();

            global::System.Collections.IEnumerator enumerator = crlSet.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    Asn1Encodable asn1Encodable = (Asn1Encodable)enumerator.get_Current();
                    try
                    {
                        crls.Add((object)x509CrlParser.ReadCrl(asn1Encodable.GetEncoded()));
                    }
                    catch (global::System.Exception e)
                    {
                        throw new CmsException("can't re-encode CRL!", e);
                    }
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }
예제 #5
0
파일: PkixTest.cs 프로젝트: jwtvh/bc-csharp
        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());
            }
        }
예제 #6
0
        internal static X509Crl ParseCrlFromUrl(String crlurl)
        {
            X509CrlParser crlParser = new X509CrlParser();
            // Creates the CRL
            Stream url = WebRequest.Create(crlurl).GetResponse().GetResponseStream();

            return(crlParser.ReadCrl(url));
        }
        static X509Crl DecodeX509Crl(DbDataReader 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));
            }
        }
예제 #8
0
        private void Initialize(byte[] crl)
        {
            X509CrlParser parser = new X509CrlParser();

            m_crl          = parser.ReadCrl(crl);
            UpdateTime     = (m_crl.ThisUpdate == null) ? DateTime.MinValue : m_crl.ThisUpdate;
            NextUpdateTime = (m_crl.NextUpdate == null) ? DateTime.MinValue : m_crl.NextUpdate.Value;
            Issuer         = m_crl.IssuerDN.ToString();
        }
예제 #9
0
        public static void Main(String[] args)
        {
            LoggerFactory.GetInstance().SetLogger(new SysoLogger());
            Properties properties = new Properties();

            properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open));
            String path = properties["PRIVATE"];

            char[] pass = properties["PASSWORD"].ToCharArray();

            Pkcs12Store ks = new Pkcs12Store();

            ks.Load(new FileStream(path, FileMode.Open), pass);
            String alias = "";

            foreach (string al in ks.Aliases)
            {
                if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }
            AsymmetricKeyParameter  pk    = ks.GetKey(alias).Key;
            IList <X509Certificate> chain = new List <X509Certificate>();

            foreach (X509CertificateEntry entry in ks.GetCertificateChain(alias))
            {
                chain.Add(entry.Certificate);
            }
            FileStream   ins  = new FileStream(CRLURL, FileMode.Open);
            MemoryStream baos = new MemoryStream();

            byte[] buf = new byte[1024];
            int    readedBytes;

            while ((readedBytes = ins.Read(buf, 0, 1024)) > 0)
            {
                baos.Write(buf, 0, readedBytes);
            }
            ins.Close();
            ICrlClient crlClient = new CrlClientOffline(baos.ToArray());

            X509CrlParser crlParser = new X509CrlParser();
            X509Crl       crl       = crlParser.ReadCrl(new FileStream(CRLURL, FileMode.Open));

            Console.WriteLine("CRL valid until: " + crl.NextUpdate);
            Console.WriteLine("Certificate revoked: " + crl.IsRevoked(chain[0]));

            IList <ICrlClient> crlList = new List <ICrlClient>();

            crlList.Add(crlClient);
            C3_01_SignWithCAcert.Sign(DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test",
                                      "Ghent",
                                      crlList, null, null, 0);
        }
예제 #10
0
 /**
  * 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);
     }
 }
        /// <summary>
        /// Determines whether timestamp, signed by given certificate, can be considered valid, even after said certificate has been revoked.
        /// It follows rules discribed in RFC3161 section 4.1.
        /// </summary>
        /// <param name="certificate">The certificate.</param>
        /// <param name="timestampGenTime">The timestamp time.</param>
        /// <returns>
        ///   <c>true</c> if [is valid after revocation] [the specified certificate]; otherwise, <c>false</c>.
        /// </returns>
        private static bool IsValidAfterRevocation(X509Certificate2 certificate, DateTime timestampGenTime)
        {
            try
            {
                /* Get CRL url from certificate */
                Org.BouncyCastle.X509.X509Certificate cert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(certificate);
                X509Extension revocationExtension          = (from X509Extension extension in certificate.Extensions where extension.Oid.Value.Equals("2.5.29.31") select extension).Single();
                Regex         rx = new Regex("http://.*?\\.crl");
                foreach (Match match in rx.Matches(new AsnEncodedData(revocationExtension.Oid, revocationExtension.RawData).Format(false)))
                {
                    string    crlUrl = match.Value;
                    WebClient client = new WebClient();

                    X509CrlParser crlParser = new X509CrlParser();
                    X509Crl       crl       = crlParser.ReadCrl(client.DownloadData(crlUrl));

                    if (crl.IsRevoked(cert))
                    {
                        X509CrlEntry revokedEntry   = crl.GetRevokedCertificate(cert.SerialNumber);
                        DateTime     revocationDate = revokedEntry.RevocationDate;

                        /* All timestamps created after revocation date are invalid */
                        if (DateTime.Compare(timestampGenTime, revocationDate) > 0)
                        {
                            return(false);
                        }

                        DerEnumerated reasonCode = DerEnumerated.GetInstance(GetExtensionValue(revokedEntry, Org.BouncyCastle.Asn1.X509.X509Extensions.ReasonCode));

                        /* If the revocation reason is not present, the timestamp is considered invalid */
                        if (reasonCode == null)
                        {
                            return(false);
                        }

                        int reason = reasonCode.Value.IntValue;

                        /* If the revocation reason is any other value, the timestamp is considered invalid */
                        if (!(reason == Org.BouncyCastle.Asn1.X509.CrlReason.Unspecified ||
                              reason == Org.BouncyCastle.Asn1.X509.CrlReason.AffiliationChanged ||
                              reason == Org.BouncyCastle.Asn1.X509.CrlReason.Superseded ||
                              reason == Org.BouncyCastle.Asn1.X509.CrlReason.CessationOfOperation))
                        {
                            return(false);
                        }
                    }
                }
            }
            catch
            {
                return(false);
            }
            return(true);
        }
예제 #12
0
        /// <summary>
        /// Converts DER-encoded CRL to PEM format
        /// </summary>
        /// <param name="derEncodedCrlBytes">DER-encoded CRL (in bytes)</param>
        /// <returns>PEM-encoded CRL.</returns>
        public static string ConvertDerEncodedCrlToPem(byte[] derEncodedCrlBytes)
        {
            var parser = new X509CrlParser();
            var crl    = parser.ReadCrl(derEncodedCrlBytes);

            using (var textWriter = new StringWriter())
            {
                var pemWriter = new PemWriter(textWriter);
                pemWriter.WriteObject(crl);
                return(textWriter.ToString());
            }
        }
예제 #13
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 = new Uri("https://trustcenter-data.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);
        }
예제 #14
0
        public static X509CrlEntry GetRevokedCertificateEntry(BigInteger serialNumber)
        {
            byte[] crlByteArray;

            using (WebClient webClient = new WebClient())
            {
                crlByteArray = webClient.DownloadData(new Uri(ValidationEnums.CRL.CRL_URL));
            }

            X509CrlParser parser = new X509CrlParser();
            X509Crl       crl    = parser.ReadCrl(crlByteArray);

            return(crl.GetRevokedCertificate(serialNumber));
        }
예제 #15
0
        private void AddCrlsFromSet(IList crls, Asn1Set crlSet)
        {
            X509CrlParser x509CrlParser = new X509CrlParser();

            foreach (Asn1Encodable asn1Encodable in crlSet)
            {
                try
                {
                    crls.Add(x509CrlParser.ReadCrl(asn1Encodable.GetEncoded()));
                }
                catch (Exception e)
                {
                    throw new CmsException("can't re-encode CRL!", e);
                }
            }
        }
예제 #16
0
        /// <summary>
        /// CrlReader Constructor 1
        /// </summary>
        /// <param name="crlBytes">byte array containing the CRL contents</param>
        public CrlReader(byte[] crlBytes)
        {
            X509CrlParser Parser = new X509CrlParser();
            X509Crl       CRL    = Parser.ReadCrl(crlBytes);

            NextUpdate = CRL.NextUpdate.Value;
            var RevokedCerts = CRL.GetRevokedCertificates();

            if (RevokedCerts != null)
            {
                foreach (X509CrlEntry Entry in CRL.GetRevokedCertificates())
                {
                    Certificates.Add(Entry.SerialNumber.ToString(16));
                }
            }
        }
예제 #17
0
        //public void GetCrlInfo2(string fileName, Org.BouncyCastle.Math.BigInteger serialNumber, Org.BouncyCastle.X509.X509Certificate cert)

        //Отдает данные из Crl-файла в виде массива строк:
        public string[] GetCrlInfoAsArray(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 CrlInfo1 = new CrlInfo(issuer.ToString(), signature, nextupdate, thisUpdate);
                //CrlInfo CrlInfo1 = new CrlInfo(issuer.ToString(),BitConverter.ToInt32(signature,0),nextupdate,thisUpdate);

                string[] array = { issuer.ToString(), nextupdate.ToString(), thisUpdate.ToString() };

                return(array);
            }
            catch (Exception ex)
            {
                string[] array = { "Операция не удалась" };
                Logger.Write(ex.Message);
                return(array);
            }
        }
예제 #18
0
        public static bool CheckValidation(User user)
        {
            bool   value;
            string CrlPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\Certs\\" + crlName;

            CrlPath = new Uri(CrlPath).LocalPath;
            X509CrlParser parser = new X509CrlParser();

            using (BinaryReader reader = new BinaryReader(File.Open(CrlPath, FileMode.Open)))
            {
                X509Crl          crlData     = parser.ReadCrl(reader.ReadBytes((int)new FileInfo(CrlPath).Length));
                X509Certificate2 certificate = new X509Certificate2(user.CertPath, PASSWORD);
                var bouncyCert = DotNetUtilities.FromX509Certificate(certificate);
                value = crlData.IsRevoked(bouncyCert);
            }
            return(value);
        }
예제 #19
0
        /// <summary>
        /// Checks if certificate has been revoked.
        /// </summary>
        /// <param name="certificateToValidate">Certificate that is checked.</param>
        /// <param name="crlListPath">Path on FS to CRL directory.</param>
        /// <param name="caTrustListPath">Path on FS to CA trust list.</param>
        /// <returns>true if certificate has been revoked, otherwise false.</returns>
        public static bool VerifyCertificateRevocationStatus(X509Certificate2 certificateToValidate, string crlListPath, string caTrustListPath)
        {
            var dir = new DirectoryInfo(crlListPath);

            FileInfo[] crlList = null;

            try
            {
                crlList = dir.GetFiles("*.crl");
            }
            catch (Exception ex)
            {
                if (ex is DirectoryNotFoundException || ex is ArgumentNullException)
                {
                    throw new Exception("User certificate validation failed. CRL file is missing.");
                }
            }

            foreach (var crlRaw in crlList)
            {
                var buffer    = File.ReadAllBytes(crlListPath + "\\" + crlRaw.Name);
                var crlParser = new X509CrlParser();
                var crl       = crlParser.ReadCrl(buffer);

                try
                {
                    var rootCa    = new X509Certificate2(caTrustListPath);
                    var publicKey = ((RSACryptoServiceProvider)rootCa.PublicKey.Key).ExportParameters(false);

                    // Check if the crl is issued by a proper root CA.
                    crl.Verify(DotNetUtilities.GetRsaPublicKey(publicKey));
                }
                catch (Exception)
                {
                    throw new Exception("User certificate validation failed. CRL isn't issued by a proper root CA.");
                }

                var revokeStatus = crl.IsRevoked(DotNetUtilities.FromX509Certificate(certificateToValidate));
                if (revokeStatus == false)
                {
                    return(false);
                }
            }

            return(true);
        }
예제 #20
0
        public void RevokeUserCertificate(string uid, string cid)
        {
            //get root cert
            X509Certificate rootCert = DotNetUtilities.FromX509Certificate(getRootCert());

            //get user cert to be revoked
            UserCertificate userCert     = GetUserCertificate(uid, cid);
            X509Certificate certToRevoke = new X509CertificateParser().ReadCertificate(userCert.RawCertBody);

            //parse the last CRL
            X509CrlParser crlParser  = new X509CrlParser();
            FileStream    fileStream = File.Open(_configuration["CrlPath"], FileMode.Open);
            X509Crl       rootCrl    = crlParser.ReadCrl(fileStream);

            fileStream.Close();

            //extract the CRL number
            Asn1OctetString prevCrlNum    = rootCrl.GetExtensionValue(X509Extensions.CrlNumber);
            Asn1Object      obj           = X509ExtensionUtilities.FromExtensionValue(prevCrlNum);
            BigInteger      prevCrlNumVal = DerInteger.GetInstance(obj).PositiveValue;

            //generate new CRL
            X509V2CrlGenerator crlGenerator = new X509V2CrlGenerator();

            crlGenerator.SetIssuerDN(rootCert.SubjectDN);
            crlGenerator.SetThisUpdate(DateTime.UtcNow);
            crlGenerator.SetNextUpdate(DateTime.UtcNow.AddDays(10));
            crlGenerator.AddCrl(rootCrl); //add the old CRL entries
            //add the newly revoked certificates
            crlGenerator.AddCrlEntry(certToRevoke.SerialNumber, DateTime.UtcNow, CrlReason.PrivilegeWithdrawn);
            //increment CRL Number by 1
            crlGenerator.AddExtension("2.5.29.20", false, new CrlNumber(prevCrlNumVal.Add(BigInteger.One)));
            AsymmetricKeyParameter bouncyCastlePrivateKey = PrivateKeyFactory.CreateKey(getRootPrivateKey().ExportPkcs8PrivateKey());

            var     sigFactory = new Asn1SignatureFactory("SHA256WITHECDSA", bouncyCastlePrivateKey);
            X509Crl nextCrl    = crlGenerator.Generate(sigFactory);

            // writePem(_configuration["CrlOldPath"], rootCrl); // write old CRL as backup
            writePem(_configuration["CrlPath"], nextCrl); //write new CRL

            // sanity check
            nextCrl.Verify(rootCert.GetPublicKey());

            userCert.Revoked = true;
            _context.UserCertificates.Update(userCert);
        }
예제 #21
0
 public void ReloadCrl()
 {
     _crlLock.EnterWriteLock();
     try{
         using (var crl_stream = new FileStream(_crlPath, FileMode.Open)) {
             _crl = _crlReader.ReadCrl(crl_stream);
         }
     }catch (System.UnauthorizedAccessException e) {
         throw new OcspFilesystemException("Error reading CRL: " + _crlPath, e);
     }catch (FileNotFoundException e) {
         throw new OcspFilesystemException("Error reading CRL: " + _crlPath, e);
     }
     finally{
         _crlLock.ExitWriteLock();
     }
     SharpOCSP.log.Info("CRL reloaded for CA: " + this);
     return;
 }
예제 #22
0
        private void Initialize(byte[] crl)
        {
            X509CrlParser parser = new X509CrlParser();

            m_crl          = parser.ReadCrl(crl);
            UpdateTime     = m_crl.ThisUpdate;
            NextUpdateTime = (m_crl.NextUpdate == null) ? DateTime.MinValue : m_crl.NextUpdate.Value;
            // a few conversions to match System.Security conventions
            string issuerDN = m_crl.IssuerDN.ToString();

            // replace state ST= with S=
            issuerDN = issuerDN.Replace("ST=", "S=");
            // reverse DN order to match System.Security
            List <string> issuerList = Utils.ParseDistinguishedName(issuerDN);

            issuerList.Reverse();
            Issuer = string.Join(", ", issuerList);
        }
예제 #23
0
        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);
                }
            }
        }
예제 #24
0
        /// <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);
            }
        }
예제 #25
0
        //Отдает содержимое 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);
            }
        }
예제 #26
0
        /**
         * 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);
            }
        }
예제 #27
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);
            }
        }
예제 #28
0
        /**
         * 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);
        }
예제 #29
0
 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);
     }
 }
예제 #30
0
        /**
         * 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();
        }