예제 #1
0
 /// <summary>Verifies a certificate against a single CRL.</summary>
 /// <param name="crl">the Certificate Revocation List</param>
 /// <param name="signCert">a certificate that needs to be verified</param>
 /// <param name="issuerCert">its issuer</param>
 /// <param name="signDate">the sign date</param>
 /// <returns>true if the verification succeeded</returns>
 /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
 public virtual bool Verify(X509Crl crl, X509Certificate signCert, X509Certificate issuerCert, DateTime signDate
                            )
 {
     if (crl == null || signDate == SignUtils.UNDEFINED_TIMESTAMP_DATE)
     {
         return(false);
     }
     // We only check CRLs valid on the signing date for which the issuer matches
     if (crl.IssuerDN.Equals(signCert.IssuerDN) && signDate.After(crl.ThisUpdate) && signDate.Before(crl.NextUpdate
                                                                                                     ))
     {
         // the signing certificate may not be revoked
         if (IsSignatureValid(crl, issuerCert) && crl.IsRevoked(signCert))
         {
             throw new VerificationException(signCert, "The certificate has been revoked.");
         }
         return(true);
     }
     return(false);
 }
예제 #2
0
        /// <summary>
        /// Create a reference to a X509Crl
        /// </summary>
        private static CrlValidatedID MakeCrlValidatedID(X509Crl crl)
        {
            OtherHash           hash = new OtherHash(DigestUtilities.CalculateDigest(X509ObjectIdentifiers.IdSha1, crl.GetEncoded()));
            BigInteger          crlnumber;
            CrlIdentifier       crlid;
            DerObjectIdentifier crlExt = new DerObjectIdentifier("2.5.29.20");

            if (crl.GetExtensionValue(crlExt) != null)
            {
                crlnumber = new DerInteger(crl.GetExtensionValue(crlExt).GetDerEncoded()).PositiveValue;
                crlid     = new CrlIdentifier(crl.IssuerDN, crl.ThisUpdate, crlnumber);
            }
            else
            {
                crlid = new CrlIdentifier(crl.IssuerDN, crl.ThisUpdate);
            }
            CrlValidatedID crlvid = new CrlValidatedID(hash, crlid);

            return(crlvid);
        }
예제 #3
0
        private bool ProcessCrlExtensions(X509Crl crl)
        {
            foreach (X509Extension ext in crl.Extensions)
            {
                if (ext.Critical)
                {
                    switch (ext.Oid)
                    {
                    case "2.5.29.20":                             // cRLNumber
                    case "2.5.29.35":                             // authorityKeyIdentifier
                        // we processed/know about this extension
                        break;

                    default:
                        return(false);
                    }
                }
            }
            return(true);
        }
예제 #4
0
        public void basicConstraintsCriticalcAFalseCACRL()
        {
            X509Crl crl = new X509Crl(basicConstraintsCriticalcAFalseCACRL_crl);

            Assert.AreEqual(0, crl.Entries.Count, "Entries.Count");
            Assert.AreEqual(2, crl.Extensions.Count, "Extensions.Count");
            Assert.IsTrue(crl.IsCurrent, "IsCurrent"); // true till 2011
            Assert.AreEqual("C=US, O=Test Certificates, CN=basicConstraints Critical cA False CA", crl.IssuerName, "IssuerName");
            Assert.AreEqual(634388218400000000, crl.NextUpdate.ToUniversalTime().Ticks, "NextUpdate");
            Assert.AreEqual("32-BC-12-1F-84-D0-B6-3E-72-A0-FB-D9-75-99-CA-E5-2A-05-09-E6-C8-27-74-47-1C-DC-0C-D4-9F-BC-9F-B2-62-25-B4-6D-5B-E5-0B-E8-2A-8E-07-EB-3E-6B-C5-1E-9A-D2-14-FD-89-5B-C3-10-BF-19-77-67-0A-33-45-1B-BC-6C-ED-AF-84-30-59-FB-7C-71-95-63-60-31-9B-9B-0A-EA-77-F1-70-F1-B9-2E-D1-A9-04-42-66-94-B9-54-48-DB-44-56-56-1A-57-5A-01-0E-7C-4D-D7-C0-1F-5C-6F-13-F5-A3-57-88-6A-9A-71-CD-D5-AE-C3-00-B1-28", BitConverter.ToString(crl.Signature), "Signature");
            Assert.AreEqual("1.2.840.113549.1.1.5", crl.SignatureAlgorithm, "SignatureAlgorithm");
            Assert.AreEqual(631232890400000000, crl.ThisUpdate.ToUniversalTime().Ticks, "ThisUpdate");
            Assert.AreEqual(2, crl.Version, "Version");

            X509Certificate cert = new X509Certificate(basicConstraintsCriticalcAFalseCACert_crt);

            // certificate has CA set to false
            Assert.IsFalse(crl.VerifySignature(cert), "VerifySignature(cert)");
            Assert.IsTrue(crl.VerifySignature(cert.RSA), "VerifySignature(RSA)");
        }
예제 #5
0
        /// <summary>
        /// Imports a certificate revocation list.
        /// </summary>
        /// <remarks>
        /// Imports the specified certificate revocation list.
        /// </remarks>
        /// <param name="crl">The certificate revocation list.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="crl"/> is <c>null</c>.
        /// </exception>
        public override void Import(X509Crl crl)
        {
            if (crl == null)
            {
                throw new ArgumentNullException(nameof(crl));
            }

            // check for an exact match...
            if (dbase.Find(crl, X509CrlRecordFields.Id) != null)
            {
                return;
            }

            const X509CrlRecordFields fields = ~X509CrlRecordFields.Crl;
            var obsolete = new List <X509CrlRecord> ();
            var delta    = crl.IsDelta();

            // scan over our list of CRLs by the same issuer to check if this CRL obsoletes any
            // older CRLs or if there are any newer CRLs that obsolete that obsolete this one.
            foreach (var record in dbase.Find(crl.IssuerDN, fields))
            {
                if (!record.IsDelta && record.ThisUpdate >= crl.ThisUpdate)
                {
                    // we have a complete CRL that obsoletes this CRL
                    return;
                }

                if (!delta)
                {
                    obsolete.Add(record);
                }
            }

            // remove any obsoleted CRLs
            foreach (var record in obsolete)
            {
                dbase.Remove(record);
            }

            dbase.Add(new X509CrlRecord(crl));
        }
예제 #6
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);
            }
        }
        public bool Generate()
        {
            using (var dlg = new SaveFileDialog())
            {
                dlg.Filter           = @"Crl files (*.crl)|*.crl|All files (*.*)|*.*";
                dlg.FilterIndex      = 0;
                dlg.RestoreDirectory = true;

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    string file = dlg.FileName;

                    var listGenerator = new DefaultCertificateRevocationListGenerator();

                    DateTime beginDate      = View.From;
                    DateTime nextUpdateDate = beginDate.AddDays(View.NextUpdate);

                    X509Certificate         caFile         = IOPEMUtils.LoadPemCertificate(View.CAFile);
                    AsymmetricCipherKeyPair caPriveKeyFile = IOPEMUtils.LoadPemPrivateKey(View.CAPrivateKeyFile);

                    X509Crl result = listGenerator.Create(
                        View.Algoritm,
                        caFile,
                        caPriveKeyFile,
                        beginDate,
                        nextUpdateDate
                        );

                    IOPEMUtils.SavePemCrl(result, file);

                    MessageBox.Show(String.Format("Lista gravada em '{0}'", file), @"Informação",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information
                                    );

                    return(true);
                }

                return(false);
            }
        }
예제 #8
0
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        /// <exception cref="System.IO.IOException"/>
        private bool VerifyTest(TestCrlBuilder crlBuilder)
        {
            String            caCertFileName    = certsSrc + "rootRsa.p12";
            X509Certificate   caCert            = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(caCertFileName, password)[0];
            ICipherParameters caPrivateKey      = Pkcs12FileHelper.ReadFirstKey(caCertFileName, password, password);
            String            checkCertFileName = certsSrc + "signCertRsa01.p12";
            X509Certificate   checkCert         = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(checkCertFileName, password)[
                0];
            TestCrlClient        crlClient          = new TestCrlClient(crlBuilder, caPrivateKey);
            ICollection <byte[]> crlBytesCollection = crlClient.GetEncoded(checkCert, null);
            bool verify = false;

            foreach (byte[] crlBytes in crlBytesCollection)
            {
                X509Crl     crl      = (X509Crl)SignTestPortUtil.ParseCrlFromStream(new MemoryStream(crlBytes));
                CRLVerifier verifier = new CRLVerifier(null, null);
                verify = verifier.Verify(crl, checkCert, caCert, DateTimeUtil.GetCurrentUtcTime());
                break;
            }
            return(verify);
        }
예제 #9
0
        public X509Crl Get(string url)
        {
            X509Crl crl = this.crlCache.Get(url);

            if (crl == null)
            {
                // Not in cache
                crl = this.Download(url);
            }
            else if (crl.NextUpdate != null && crl.NextUpdate.Value < DateTime.Now)
            {
                // Outdated
                crl = this.Download(url);
            }
            else if (crl.NextUpdate == null)
            {
                // No action.
            }

            return(crl);
        }
예제 #10
0
        /// <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);
        }
예제 #11
0
        static void Download(string url, X509Store store)
        {
            if (verbose)
            {
                Console.WriteLine("Downloading: {0}", url);
            }

            WebClient wc    = new WebClient();
            string    error = "download";

            try {
                byte [] data = wc.DownloadData(url);
                error = "decode";
                X509Crl crl = new X509Crl(data);
                error = "import";
                // warn if CRL is not current - but still allow it to be imported
                if (!crl.IsCurrent && verbose)
                {
                    Console.WriteLine("WARNING: CRL is not current: {0}", url);
                }

                // only import the CRL if its signature is valid and coming from a trusted root
                if (VerifyCrl(crl))
                {
                    store.Import(crl);
                }
                else
                {
                    Console.WriteLine("ERROR: could not validate CRL: {0}", url);
                }
            }
            catch (Exception e) {
                Console.WriteLine("ERROR: could not {0}: {1}", error, url);
                if (verbose)
                {
                    Console.WriteLine(e);
                    Console.WriteLine();
                }
            }
        }
예제 #12
0
        /// <summary>
        /// Issue a CRL (containing all revoked certificates)
        /// </summary>
        /// <returns></returns>
        public virtual string IssueCRL()
        {
            X509V2CrlGenerator crlGen = new X509V2CrlGenerator();

            // Generate CRL
            try
            {
                createCRL(crlGen);
                X509Crl crl = crlGen.Generate(privateKey);

                // Write CRL to file
                File.WriteAllBytes(crlFileLocation, crl.GetEncoded());

                logEvent(LogEvent.EventType.IssueCert, "CRL Published. Serial: " + lastCRL);
            }
            catch (Exception ex)
            {
                LogEvent.WriteEvent(eventLog, LogEvent.EventType.Error, "Failed CRL issue: " + ex.Message);
                throw new ApplicationException("Failed CRL Issue", ex);
            }
            return(lastCRL);
        }
예제 #13
0
        /// <summary>
        /// Publishes the crl
        /// </summary>
        public void PublishCrl()
        {
            if (_revoked == null)
            {
                return;
                //TODO: may be show a messagebox or something?
            }
            Pkcs12Store store = LoadCAPfx(KeyStorePassword);

            if (!store.ContainsAlias(CaAlias) || !store.IsEntryOfType(CaAlias, typeof(AsymmetricKeyEntry)))
            {
                return;
            }
            AsymmetricKeyParameter key    = store.GetKey(CaAlias).Key;
            X509Certificate        caCert = store.GetCertificate(CaAlias).Certificate;


            var crlNumber = new BigInteger(ReadCrlSerialNumber(), SerialNumberRadix);
            var crlGen    = new X509V2CrlGenerator();

            crlGen.SetIssuerDN(caCert.SubjectDN);
            //crlGen.SetNextUpdate();
            crlGen.SetSignatureAlgorithm(caCert.SigAlgName.Replace("-", ""));
            crlGen.SetThisUpdate(DateTime.UtcNow);
            crlGen.SetNextUpdate(DateTime.UtcNow.AddHours(CrlFrequency));
            crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(crlNumber));
            crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false,
                                new AuthorityKeyIdentifierStructure(caCert));
            //crlGen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.KeyAgreement | KeyUsage.CrlSign | KeyUsage.DataEncipherment | KeyUsage.DecipherOnly | KeyUsage.EncipherOnly | KeyUsage.KeyEncipherment | KeyUsage.NonRepudiation));
            foreach (RevokedSerial rs in _revoked.RevokedSerialCollection)
            {
                crlGen.AddCrlEntry(new BigInteger(rs.Serial), rs.RevocationDate, rs.Reason);
            }
            X509Crl crl        = crlGen.Generate(key);
            string  crlEncoded = PemUtilities.Encode(crl);

            File.WriteAllText(CrlFilePath, crlEncoded);
            IncrementCrlSerial();
        }
예제 #14
0
 private bool ProcessCrlExtensions(X509Crl crl)
 {
     foreach (object obj in crl.Extensions)
     {
         X509Extension x509Extension = (X509Extension)obj;
         if (x509Extension.Critical)
         {
             string oid = x509Extension.Oid;
             if (oid != null)
             {
                 if (X509Chain.< > f__switch$mapC == null)
                 {
                     X509Chain.< > f__switch$mapC = new Dictionary <string, int>(2)
                     {
                         {
                             "2.5.29.20",
                             0
                         },
                         {
                             "2.5.29.35",
                             0
                         }
                     };
                 }
                 int num;
                 if (X509Chain.< > f__switch$mapC.TryGetValue(oid, out num))
                 {
                     if (num == 0)
                     {
                         continue;
                     }
                 }
             }
             return(false);
         }
     }
     return(true);
 }
예제 #15
0
        private X509Crl FindCrl(BCX509Certificate2 caCertificate)
        {
#if !NETCF
            string subject = caCertificate.SubjectDN.Decode(X500DistinguishedNameFlags.None);
            string ski     = GetSubjectKeyIdentifier(caCertificate);

            // consider that the LocalMachine directories could not exists... and cannot be created by the user
            X509Crl result = CheckCrls(subject, ski, LMCAStore.Store);
            if (result != null)
            {
                return(result);
            }
            if (location == StoreLocation.CurrentUser)
            {
                result = CheckCrls(subject, ski, UserCAStore.Store);
                if (result != null)
                {
                    return(result);
                }
            }

            // consider that the LocalMachine directories could not exists... and cannot be created by the user
            result = CheckCrls(subject, ski, LMRootStore.Store);
            if (result != null)
            {
                return(result);
            }
            if (location == StoreLocation.CurrentUser)
            {
                result = CheckCrls(subject, ski, UserRootStore.Store);
                if (result != null)
                {
                    return(result);
                }
            }
#endif
            return(null);
        }
예제 #16
0
 public static global::System.Collections.IList GetCrlsFromStore(IX509Store crlStore)
 {
     try
     {
         global::System.Collections.IList list = Platform.CreateArrayList();
         if (crlStore != null)
         {
             {
                 global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)crlStore.GetMatches(null)).GetEnumerator();
                 try
                 {
                     while (enumerator.MoveNext())
                     {
                         X509Crl x509Crl = (X509Crl)enumerator.get_Current();
                         list.Add((object)CertificateList.GetInstance(Asn1Object.FromByteArray(x509Crl.GetEncoded())));
                     }
                 }
                 finally
                 {
                     global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                     if (disposable != null)
                     {
                         disposable.Dispose();
                     }
                 }
             }
         }
         return(list);
     }
     catch (CrlException e)
     {
         throw new CmsException("error encoding crls", e);
     }
     catch (global::System.Exception e2)
     {
         throw new CmsException("error processing crls", e2);
     }
 }
예제 #17
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);
            }
        }
예제 #18
0
        /// <summary>
        /// Issue a CRL (containing all revoked certificates)
        /// </summary>
        /// <returns>CRL number</returns>
        public override string IssueCRL()
        {
            SysCrlGen crlGen = new SysCrlGen();

            // Generate CRL
            try
            {
                createCRL(crlGen);
                X509Crl crl = crlGen.Generate(cspParam);

                // Write CRL to file
                File.WriteAllBytes(crlFileLocation, crl.GetEncoded());

                logEvent(LogEvent.EventType.IssueCert, "CRL Published. Serial: " + lastCRL);
            }
            catch (Exception ex)
            {
                logEvent(LogEvent.EventType.Error, "Failed CRL issue: " + ex.Message);
                throw new ApplicationException("Failed CRL Issue", ex);
            }

            return(lastCRL);
        }
예제 #19
0
        private X509Crl FindCrl(X509Certificate2 caCertificate)
        {
            string b = caCertificate.SubjectName.Decode(X500DistinguishedNameFlags.None);
            string subjectKeyIdentifier = this.GetSubjectKeyIdentifier(caCertificate);

            foreach (object obj in this.CertificateAuthorities.Store.Crls)
            {
                X509Crl x509Crl = (X509Crl)obj;
                if (x509Crl.IssuerName == b && (subjectKeyIdentifier.Length == 0 || subjectKeyIdentifier == this.GetAuthorityKeyIdentifier(x509Crl)))
                {
                    return(x509Crl);
                }
            }
            foreach (object obj2 in this.Roots.Store.Crls)
            {
                X509Crl x509Crl2 = (X509Crl)obj2;
                if (x509Crl2.IssuerName == b && (subjectKeyIdentifier.Length == 0 || subjectKeyIdentifier == this.GetAuthorityKeyIdentifier(x509Crl2)))
                {
                    return(x509Crl2);
                }
            }
            return(null);
        }
    public void AddCrl(X509Crl other)
    {
        if (other == null)
        {
            throw new ArgumentNullException("other");
        }
        ISet revokedCertificates = other.GetRevokedCertificates();

        if (revokedCertificates != null)
        {
            foreach (X509CrlEntry item in revokedCertificates)
            {
                try
                {
                    tbsGen.AddCrlEntry(Asn1Sequence.GetInstance(Asn1Object.FromByteArray(item.GetEncoded())));
                }
                catch (IOException e)
                {
                    throw new CrlException("exception processing encoding of CRL", e);
                }
            }
        }
    }
예제 #21
0
 /// <summary>Checks if a CRL verifies against the issuer certificate or a trusted anchor.</summary>
 /// <param name="crl">the CRL</param>
 /// <param name="crlIssuer">the trusted anchor</param>
 /// <returns>true if the CRL can be trusted</returns>
 public virtual bool IsSignatureValid(X509Crl crl, X509Certificate crlIssuer)
 {
     // check if the CRL was issued by the issuer
     if (crlIssuer != null)
     {
         try {
             crl.Verify(crlIssuer.GetPublicKey());
             return(true);
         }
         catch (GeneralSecurityException) {
             LOGGER.Warn("CRL not issued by the same authority as the certificate that is being checked");
         }
     }
     // check the CRL against trusted anchors
     if (rootStore == null)
     {
         return(false);
     }
     try {
         // loop over the certificate in the key store
         foreach (X509Certificate anchor in SignUtils.GetCertificates(rootStore))
         {
             try {
                 // check if the crl was signed by a trusted party (indirect CRLs)
                 crl.Verify(anchor.GetPublicKey());
                 return(true);
             }
             catch (GeneralSecurityException) {
                 continue;
             }
         }
     }
     catch (GeneralSecurityException) {
         return(false);
     }
     return(false);
 }
예제 #22
0
 /// <summary>
 /// For level -XL, every X509Crl values contained in the ValidationContext must be in the RevocationValues of the
 /// signature
 /// </summary>
 /// <param name="ctx"></param>
 /// <param name="refs"></param>
 /// <param name="signingCert"></param>
 /// <returns></returns>
 protected internal virtual bool EveryCRLValueOrRefAreThere <_T0>(ValidationContext
                                                                  ctx, IList <_T0> crlValuesOrRef)
 {
     foreach (X509Crl crl in ctx.GetNeededCRL())
     {
         LOG.Info("Looking for CRL ref issued by " + crl.IssuerDN);
         bool found = false;
         foreach (object valueOrRef in crlValuesOrRef)
         {
             if (valueOrRef is X509Crl)
             {
                 X509Crl sigCRL = (X509Crl)valueOrRef;
                 if (sigCRL.Equals(crl))
                 {
                     found = true;
                     break;
                 }
             }
             if (valueOrRef is CRLRef)
             {
                 CRLRef @ref = (CRLRef)valueOrRef;
                 if (@ref.Match(crl))
                 {
                     found = true;
                     break;
                 }
             }
         }
         LOG.Info("Ref " + (found ? " found" : " not found"));
         if (!found)
         {
             return(false);
         }
     }
     return(true);
 }
예제 #23
0
        private BigInteger GetCrlNumber(X509Crl crl)
        {
            //byte[] crlNumberExtensionValue = crl.GetExtensionValue(X509Extensions.CrlNumber);
            Asn1OctetString crlNumberExtensionValue = crl.GetExtensionValue(X509Extensions.CrlNumber);

            if (null == crlNumberExtensionValue)
            {
                return(null);
            }
            try
            {
                //DerOctetString octetString = (DerOctetString)(new ASN1InputStream(new ByteArrayInputStream
                //    (crlNumberExtensionValue)).ReadObject());
                DerOctetString octetString = (DerOctetString)crlNumberExtensionValue;
                byte[]         octets      = octetString.GetOctets();
                DerInteger     integer     = (DerInteger) new Asn1InputStream(octets).ReadObject();
                BigInteger     crlNumber   = integer.PositiveValue;
                return(crlNumber);
            }
            catch (IOException e)
            {
                throw new RuntimeException("IO error: " + e.Message, e);
            }
        }
예제 #24
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);
        }
예제 #25
0
        /// <summary>
        /// Generate CRL.
        /// </summary>
        /// <returns>Result.</returns>
        public X509Crl Generate()
        {
            var signer = DotNetUtilities.FromX509Certificate(signerCertificate.Certificate);
            ISignatureFactory signatureFactory =
                new Asn1SignatureFactory(SignatureAlgorithm, signerCertificate.KeyPair.Private, random);

            crlGenerator.SetIssuerDN(signer.IssuerDN);
            crlGenerator.SetThisUpdate(DateTime.Now);
            crlGenerator.SetNextUpdate(DateTime.Now.AddYears(1));

            crlGenerator.AddCrlEntry(BigInteger.One, DateTime.Now, CrlReason.PrivilegeWithdrawn);

            crlGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier,
                                      false,
                                      new AuthorityKeyIdentifierStructure(signer));

            var crlNumber = new BigInteger(DateTime.UtcNow.ToString("yyyyMMddHHmm"));

            crlGenerator.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(crlNumber));

            X509Crl crlTemp = crlGenerator.Generate(signatureFactory);

            return(crlTemp);
        }
예제 #26
0
파일: crlupdate.cs 프로젝트: ischyrus/mono
        static void UpdateStore(X509Store store)
        {
            // for each certificate
            foreach (X509Certificate cert in store.Certificates)
            {
                // do we already have a matching CRL ? (or are we forced to download?)
                X509Crl crl = force ? null : FindCrl(cert, store);
                // without a CRL (or with a CRL in need of updating)
                if ((crl == null) || !crl.IsCurrent)
                {
                    X509Extension ext = cert.Extensions ["2.5.29.31"];
                    if (ext == null)
                    {
                        if (verbose)
                        {
                            Console.WriteLine("WARNING: No cRL distribution point found for '{0}'", cert.SubjectName);
                        }
                        continue;
                    }

                    CRLDistributionPointsExtension crlDP = new CRLDistributionPointsExtension(ext);
                    foreach (var dp in crlDP.DistributionPoints)
                    {
                        string name = dp.Name.Trim();
                        if (name.StartsWith("URL="))
                        {
                            Download(name.Substring(4), store);
                        }
                        else if (verbose)
                        {
                            Console.WriteLine("WARNING: Unsupported distribution point: '{0}'", name);
                        }
                    }
                }
            }
        }
예제 #27
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);
     }
 }
예제 #28
0
 /// <summary>
 /// Imports the specified certificate revocation list.
 /// </summary>
 /// <remarks>
 /// Imports the specified certificate revocation list.
 /// </remarks>
 /// <param name="crl">The certificate revocation list.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <paramref name="crl"/> is <c>null</c>.
 /// </exception>
 public abstract void Import(X509Crl crl);
 /// <summary>
 /// Gets the database command to select the record for the specified CRL.
 /// </summary>
 /// <remarks>
 /// Gets the database command to select the record for the specified CRL.
 /// </remarks>
 /// <returns>The database command.</returns>
 /// <param name="crl">The X.509 CRL.</param>
 /// <param name="fields">The fields to return.</param>
 protected abstract DbCommand GetSelectCommand(X509Crl crl, X509CrlRecordFields fields);
        public virtual bool Match(
            object obj)
        {
            X509Crl c = obj as X509Crl;

            if (c == null)
            {
                return(false);
            }

            if (dateAndTime != null)
            {
                DateTime       dt = dateAndTime.Value;
                DateTime       tu = c.ThisUpdate;
                DateTimeObject nu = c.NextUpdate;

                if (dt.CompareTo(tu) < 0 || nu == null || dt.CompareTo(nu.Value) >= 0)
                {
                    return(false);
                }
            }

            if (issuers != null)
            {
                X509Name i = c.IssuerDN;

                bool found = false;

                foreach (X509Name issuer in issuers)
                {
                    if (issuer.Equivalent(i, true))
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    return(false);
                }
            }

            if (maxCrlNumber != null || minCrlNumber != null)
            {
                Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CrlNumber);
                if (extVal == null)
                {
                    return(false);
                }

                BigInteger cn = CrlNumber.GetInstance(
                    X509ExtensionUtilities.FromExtensionValue(extVal)).PositiveValue;

                if (maxCrlNumber != null && cn.CompareTo(maxCrlNumber) > 0)
                {
                    return(false);
                }

                if (minCrlNumber != null && cn.CompareTo(minCrlNumber) < 0)
                {
                    return(false);
                }
            }

            DerInteger dci = null;

            try
            {
                Asn1OctetString bytes = c.GetExtensionValue(X509Extensions.DeltaCrlIndicator);
                if (bytes != null)
                {
                    dci = DerInteger.GetInstance(X509ExtensionUtilities.FromExtensionValue(bytes));
                }
            }
            catch (Exception)
            {
                return(false);
            }

            if (dci == null)
            {
                if (DeltaCrlIndicatorEnabled)
                {
                    return(false);
                }
            }
            else
            {
                if (CompleteCrlEnabled)
                {
                    return(false);
                }

                if (maxBaseCrlNumber != null && dci.PositiveValue.CompareTo(maxBaseCrlNumber) > 0)
                {
                    return(false);
                }
            }

            if (issuingDistributionPointEnabled)
            {
                Asn1OctetString idp = c.GetExtensionValue(X509Extensions.IssuingDistributionPoint);
                if (issuingDistributionPoint == null)
                {
                    if (idp != null)
                    {
                        return(false);
                    }
                }
                else
                {
                    if (!Arrays.AreEqual(idp.GetOctets(), issuingDistributionPoint))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }