Пример #1
0
        /// <summary>
        /// Populate a CRL object with revocation entries
        /// </summary>
        /// <param name="Crl">Reference to to CRL object</param>
        /// <param name="DbFileLocation">Loaction of the CA Database file</param>
        internal static void PopulateCRL(X509V2CrlGenerator Crl, string DbFileLocation)
        {
            XDocument db;

            if (XmlSigning.VerifyXmlFile(DbFileLocation))
            {
                db = XDocument.Load(DbFileLocation);
            }
            else
            {
                throw new GeneralSecurityException("Signature failure on database file");
            }

            // Find all certificates where revocation status is revoked
            var records = db.Element("OSCA").Descendants("record").Where(m => m.Element("revocation").Attribute("status").Value == "revoked");


            // Iterate across records and add each certificate details to the CRL
            foreach (XElement record in records)
            {
                string   certNum   = record.Element("serialNumber").Value;
                DateTime revDate   = Convert.ToDateTime(record.Element("revocation").Element("date").Value);
                int      revReason = Convert.ToInt16(record.Element("revocation").Element("reason").Value);

                Crl.AddCrlEntry(new BigInteger(certNum), revDate, revReason);
            }
            return;
        }
        private static X509Crl CreateCrl(
            X509Certificate2 issuerCert,
            BigInteger version,
            X509Certificate2 revokedCertificate = null)
        {
            var bcIssuerCert = DotNetUtilities.FromX509Certificate(issuerCert);
            var crlGen       = new X509V2CrlGenerator();

            crlGen.SetIssuerDN(bcIssuerCert.SubjectDN);
            crlGen.SetThisUpdate(DateTime.Now);
            crlGen.SetNextUpdate(DateTime.Now.AddYears(1));
            crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(bcIssuerCert));
            crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(version));

            if (revokedCertificate != null)
            {
                var bcRevokedCert = DotNetUtilities.FromX509Certificate(revokedCertificate);
                crlGen.AddCrlEntry(bcRevokedCert.SerialNumber, DateTime.Now, CrlReason.PrivilegeWithdrawn);
            }

            var random           = new SecureRandom();
            var issuerPrivateKey = DotNetUtilities.GetKeyPair(issuerCert.PrivateKey).Private;
            var signatureFactory = new Asn1SignatureFactory(bcIssuerCert.SigAlgOid, issuerPrivateKey, random);
            var crl = crlGen.Generate(signatureFactory);

            return(crl);
        }
Пример #3
0
        public byte[] GetCrl(RevocationStatus status)
        {
            if (status == RevocationStatus.Unknown | Issuer == null)
            {
                return(new byte[0]);
            }

            var generator = new X509V2CrlGenerator();

            generator.SetIssuerDN(new X509Name(Issuer.SubjectName.Name));
            generator.SetThisUpdate(DateTime.Now.AddDays(-1));
            generator.SetNextUpdate(DateTime.Now.AddDays(1));
            generator.SetSignatureAlgorithm("SHA256WithRSA");

            if (status == RevocationStatus.Revoked)
            {
                generator.AddCrlEntry(SerialNumber, DateTime.Now.AddHours(-12), CrlReason.KeyCompromise);
            }

            generator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(DotNetUtilities.FromX509Certificate(Issuer)));
            generator.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(new BigInteger(new byte[] { 0x01 })));
            var crl = generator.Generate(DotNetUtilities.GetKeyPair(Issuer.PrivateKey).Private);

            return(crl.GetEncoded());
        }
Пример #4
0
        public X509Crl CreateCRL()
        {
            var caCert = GetRootCert();
            var caKey  = GetRootKey();

            var crlGen = new X509V2CrlGenerator();

            crlGen.SetIssuerDN(caCert.IssuerDN);
            crlGen.SetThisUpdate(DateTime.Now);
            crlGen.SetNextUpdate(DateTime.Now.AddYears(1));

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

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

            crlGen.AddExtension(
                X509Extensions.CrlNumber,
                false,
                new CrlNumber(BigInteger.One)
                );

            var crl = GenerateCrl(caKey, crlGen);

            return(crl);
        }
Пример #5
0
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Org.BouncyCastle.Operator.OperatorCreationException"/>
        public virtual byte[] MakeCrl(ICipherParameters caPrivateKey)
        {
            crlBuilder.SetNextUpdate(nextUpdate);
            X509Crl crl = crlBuilder.Generate(new Asn1SignatureFactory(SIGN_ALG, (AsymmetricKeyParameter)caPrivateKey));

            crlBuilder = null;
            return(crl.GetEncoded());
        }
        /// <exception cref="Org.BouncyCastle.Security.Certificates.CertificateEncodingException"/>
        public TestCrlBuilder(X509Certificate caCert, DateTime thisUpdate)
        {
            X509Name issuerDN = caCert.IssuerDN;

            crlBuilder = new X509V2CrlGenerator();
            crlBuilder.SetIssuerDN(issuerDN);
            crlBuilder.SetThisUpdate(thisUpdate);
        }
Пример #7
0
        public X509Crl GenerateCRL()
        {
            var coreCApkcs = new Org.BouncyCastle.Pkcs.Pkcs12Store(
                new FileStream(CAConfig.CoreCACertPath, FileMode.Open, FileAccess.Read),
                "".ToCharArray()
                );

            string alias = System.Environment.MachineName;

            Org.BouncyCastle.X509.X509Certificate coreCaCert = coreCApkcs.GetCertificate(alias).Certificate;
            X509V2CrlGenerator crlGen = new X509V2CrlGenerator();

            DateTime now = DateTime.UtcNow;

            crlGen.SetIssuerDN(coreCaCert.SubjectDN);
            crlGen.SetThisUpdate(now);
            crlGen.SetNextUpdate(now.AddMinutes(Constants.CRLNextUpdatedIntervalMinutes));

            var revokedPubCerts = _dbContext.PublicCertificates.Where(p => p.IsRevoked);

            foreach (PublicCertificate pubCert in revokedPubCerts)
            {
                crlGen.AddCrlEntry(
                    new Org.BouncyCastle.Math.BigInteger(pubCert.GetSerialNumber().SerialNrBytes),
                    now,
                    Org.BouncyCastle.Asn1.X509.CrlReason.KeyCompromise
                    );
            }

            crlGen.AddExtension(
                Org.BouncyCastle.Asn1.X509.X509Extensions.AuthorityKeyIdentifier,
                false,
                new Org.BouncyCastle.X509.Extension.AuthorityKeyIdentifierStructure(
                    coreCaCert.GetPublicKey()
                    )
                );

            X509Crl crl = crlGen.Generate(
                new Org.BouncyCastle.Crypto.Operators.Asn1SignatureFactory(
                    "SHA512WITHRSA",
                    coreCApkcs.GetKey(alias).Key
                    )
                );

            _logger.LogInformation(
                string.Format(
                    "Generated CRL at {0} valid for {1} minutes",
                    now,
                    Constants.CRLNextUpdatedIntervalMinutes
                    )
                );

            return(crl);
        }
        /// <summary>
        /// Generate and return a new certificate revocation list.
        /// </summary>
        /// <returns>Certificate revocation list.</returns>
        public X509Crl Generate()
        {
            var generator = new X509V2CrlGenerator();

            // RFC 5280 section 5.1.2.3. Issuer Name
            generator.SetIssuerDN(IssuerDN);

            // RFC 5280 section 5.1.2.4. This Update
            generator.SetThisUpdate(ThisUpdate);

            // RFC 5280 section 5.1.2.5. Next Update
            generator.SetNextUpdate(NextUpdate);

            // RFC 5280 section 5.1.2.6. Revoked Certificates
            foreach (var revokedCertificate in RevokedCertificates)
            {
                var serialNumber   = revokedCertificate.Item1;
                var revocationDate = revokedCertificate.Item2;
                var reason         = CrlReason.PrivilegeWithdrawn;

                generator.AddCrlEntry(serialNumber, revocationDate, reason);
            }

            // RFC 5280 section 5.2.1. Authority Key Identifier
            generator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(Issuer));

            // RFC 5280 section 5.2.2. Issuer Alternative Name
            var issuerAlternativeName = GetIssuerAlternativeName();

            if (issuerAlternativeName != null)
            {
                generator.AddExtension(X509Extensions.IssuerAlternativeName, false, issuerAlternativeName);
            }

            // RFC 5280 section 5.2.3. CRL Number
            generator.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(CrlNumber));

            // RFC 5280 section 5.2.7. Authority Information Access
            var authorityInfoAccess = GetAuthorityInfoAccessEncoded();

            if (authorityInfoAccess != null)
            {
                generator.AddExtension(X509Extensions.AuthorityInfoAccess, false, authorityInfoAccess);
            }

            // Generate and return.
            return(generator.Generate(new Asn1SignatureFactory(SignatureAlgorithmName, IssuerKeyPair.Private, SecureRandom)));
        }
Пример #9
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);
        }
Пример #10
0
        /// <summary>
        /// Creates a CRL.
        /// </summary>
        /// <param name="crlGen">The CRL generator.</param>
        protected void createCRL(X509V2CrlGenerator crlGen)
        {
            // Set generic fields
            crlGen.SetSignatureAlgorithm(signatureAlgorithm);
            crlGen.SetIssuerDN(caCertificate.SubjectDN);
            DateTime issueDate  = DateTime.Now.ToUniversalTime();
            DateTime updateDate = issueDate.AddDays(crlInterval);

            crlGen.SetThisUpdate(issueDate);
            crlGen.SetNextUpdate(updateDate);

            // Set serial number
            crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(nextCrlSerial()));

            // Load the revocation entries
            Database.PopulateCRL(crlGen, dbFileLocation);
        }
Пример #11
0
        public static X509Crl GenerateCrl(X509Certificate certificate, ISignatureFactory signatureFactory, int reason)
        {
            X509V2CrlGenerator crlGen = new X509V2CrlGenerator();

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

            DateTime now = DateTime.Now;

            crlGen.SetThisUpdate(now);
            crlGen.SetNextUpdate(DateTime.Now.AddDays(10));

            crlGen.AddCrlEntry(certificate.SerialNumber, now, reason);

            crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(certificate));
            crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(BigInteger.One));

            return(crlGen.Generate(signatureFactory));
        }
Пример #12
0
        public static X509Crl MakeCrl(
            AsymmetricCipherKeyPair pair)
        {
            X509V2CrlGenerator crlGen = new X509V2CrlGenerator();
            DateTime           now    = DateTime.UtcNow;

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

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

            crlGen.AddCrlEntry(BigInteger.One, now, CrlReason.PrivilegeWithdrawn);

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

            return(crlGen.Generate(pair.Private));
        }
        public X509Crl Update(
            string algorithm,
            X509Crl existingCrl,
            X509Certificate[] certificates,
            X509Certificate caCert,
            AsymmetricCipherKeyPair caKey,
            DateTime thisUpdate,
            DateTime nextUpdate,
            int /*CrlReason*/ reason)
        {
            var crlGenerator = new X509V2CrlGenerator();

            crlGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert));

            crlGenerator.SetThisUpdate(thisUpdate);
            crlGenerator.SetNextUpdate(nextUpdate);

            var signatureFactory = new Asn1SignatureFactory(
                algorithm,
                caKey.Private);

            crlGenerator.AddCrl(existingCrl);

            if (!certificates.IsNullOrEmpty())
            {
                foreach (X509Certificate certificate in certificates)
                {
                    // a ver... a questão da CrlRerason... pode ser individual ?!?!?!
                    crlGenerator.AddCrlEntry(certificate.SerialNumber, thisUpdate, reason);
                }
            }

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

            BigInteger existingCrlNumber = DerInteger.GetInstance(
                Asn1Object.FromByteArray(existingCrl.GetExtensionValue(X509Extensions.CrlNumber).GetOctets())
                ).PositiveValue;

            crlGenerator.AddExtension(
                X509Extensions.CrlNumber, false, new CrlNumber(existingCrlNumber.Add(BigInteger.One)));

            return(crlGenerator.Generate(signatureFactory));
        }
Пример #14
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();
        }
Пример #15
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);
        }
Пример #16
0
        public static X509Crl CreateCrl(
            X509Certificate caCert,
            IAsymmetricKeyParameter caKey,
            IBigInteger serialNumber)
        {
            X509V2CrlGenerator crlGen = new X509V2CrlGenerator();
            DateTime           now    = DateTime.UtcNow;

//			BigInteger			revokedSerialNumber = BigInteger.Two;

            crlGen.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert));

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

            crlGen.AddCrlEntry(serialNumber, now, CrlReason.PrivilegeWithdrawn);

            crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
            crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(BigInteger.One));

            return(crlGen.Generate(caKey));
        }
        // LISTA vazia .....
        public X509Crl Create(
            string algorithm,
            X509Certificate caCert,
            AsymmetricCipherKeyPair caKey,
            DateTime thisUpdate,
            DateTime nextUpdate)
        {
            var crlGenerator = new X509V2CrlGenerator();

            crlGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert));

            crlGenerator.SetThisUpdate(thisUpdate);
            crlGenerator.SetNextUpdate(nextUpdate);

            var signatureFactory = new Asn1SignatureFactory(
                algorithm,
                caKey.Private);

            crlGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false,
                                      new AuthorityKeyIdentifierStructure(caCert));
            crlGenerator.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(BigInteger.One));

            return(crlGenerator.Generate(signatureFactory));
        }
Пример #18
0
        protected override X509Crl GenerateCrl(AsymmetricKeyParameter privateKey, X509V2CrlGenerator crlGen)
        {
            var signer = new GostSignerFactory(privateKey);

            return(crlGen.Generate(signer));
        }
Пример #19
0
 protected abstract X509Crl GenerateCrl(
     AsymmetricKeyParameter privateKey,
     X509V2CrlGenerator certGen);
Пример #20
0
        protected override X509Crl GenerateCrl(AsymmetricKeyParameter privateKey, X509V2CrlGenerator crlGen)
        {
            crlGen.SetSignatureAlgorithm("SHA1withRSA");

            return(crlGen.Generate(privateKey));
        }
Пример #21
0
    /// <summary>
    /// Revoke the CA signed certificate.
    /// The issuer CA public key, the private key and the crl reside in the storepath.
    /// The CRL number is increased by one and existing CRL for the issuer are deleted from the store.
    /// </summary>
    public static async Task <X509CRL> RevokeCertificateAsync(
        string storePath,
        X509Certificate2 certificate,
        string issuerKeyFilePassword = null
        )
    {
        X509CRL updatedCRL = null;

        try
        {
            string subjectName  = certificate.IssuerName.Name;
            string keyId        = null;
            string serialNumber = null;

            // caller may want to create empty CRL using the CA cert itself
            bool isCACert = IsCertificateAuthority(certificate);

            // find the authority key identifier.
            X509AuthorityKeyIdentifierExtension authority = FindAuthorityKeyIdentifier(certificate);

            if (authority != null)
            {
                keyId        = authority.KeyId;
                serialNumber = authority.SerialNumber;
            }
            else
            {
                throw new ArgumentException("Certificate does not contain an Authority Key");
            }

            if (!isCACert)
            {
                if (serialNumber == certificate.SerialNumber ||
                    Utils.CompareDistinguishedName(certificate.Subject, certificate.Issuer))
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Cannot revoke self signed certificates");
                }
            }

            X509Certificate2 certCA = null;
            using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(storePath))
            {
                if (store == null)
                {
                    throw new ArgumentException("Invalid store path/type");
                }
                certCA = await FindIssuerCABySerialNumberAsync(store, certificate.Issuer, serialNumber);

                if (certCA == null)
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Cannot find issuer certificate in store.");
                }

                if (!certCA.HasPrivateKey)
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Issuer certificate has no private key, cannot revoke certificate.");
                }

                CertificateIdentifier certCAIdentifier = new CertificateIdentifier(certCA);
                certCAIdentifier.StorePath = storePath;
                certCAIdentifier.StoreType = CertificateStoreIdentifier.DetermineStoreType(storePath);
                X509Certificate2 certCAWithPrivateKey = await certCAIdentifier.LoadPrivateKey(issuerKeyFilePassword);

                if (certCAWithPrivateKey == null)
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Failed to load issuer private key. Is the password correct?");
                }

                List <X509CRL> certCACrl = store.EnumerateCRLs(certCA, false);

                using (var cfrg = new CertificateFactoryRandomGenerator())
                {
                    // cert generators
                    SecureRandom random          = new SecureRandom(cfrg);
                    BigInteger   crlSerialNumber = BigInteger.Zero;

                    Org.BouncyCastle.X509.X509Certificate bcCertCA = new X509CertificateParser().ReadCertificate(certCA.RawData);
                    AsymmetricKeyParameter signingKey = GetPrivateKeyParameter(certCAWithPrivateKey);

                    ISignatureFactory signatureFactory =
                        new Asn1SignatureFactory(GetRSAHashAlgorithm(defaultHashSize), signingKey, random);

                    X509V2CrlGenerator crlGen = new X509V2CrlGenerator();
                    crlGen.SetIssuerDN(bcCertCA.IssuerDN);
                    crlGen.SetThisUpdate(DateTime.UtcNow);
                    crlGen.SetNextUpdate(DateTime.UtcNow.AddMonths(12));

                    // merge all existing revocation list
                    X509CrlParser parser = new X509CrlParser();
                    foreach (X509CRL caCrl in certCACrl)
                    {
                        X509Crl crl = parser.ReadCrl(caCrl.RawData);
                        crlGen.AddCrl(crl);
                        var crlVersion = GetCrlNumber(crl);
                        if (crlVersion.IntValue > crlSerialNumber.IntValue)
                        {
                            crlSerialNumber = crlVersion;
                        }
                    }

                    if (isCACert)
                    {
                        // add a dummy revoked cert
                        crlGen.AddCrlEntry(BigInteger.One, DateTime.UtcNow, CrlReason.Superseded);
                    }
                    else
                    {
                        // add the revoked cert
                        crlGen.AddCrlEntry(GetSerialNumber(certificate), DateTime.UtcNow, CrlReason.PrivilegeWithdrawn);
                    }

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

                    // set new serial number
                    crlSerialNumber = crlSerialNumber.Add(BigInteger.One);
                    crlGen.AddExtension(X509Extensions.CrlNumber,
                                        false,
                                        new CrlNumber(crlSerialNumber));

                    // generate updated CRL
                    X509Crl updatedCrl = crlGen.Generate(signatureFactory);

                    // add updated CRL to store
                    updatedCRL = new X509CRL(updatedCrl.GetEncoded());
                    store.AddCRL(updatedCRL);

                    // delete outdated CRLs from store
                    foreach (X509CRL caCrl in certCACrl)
                    {
                        store.DeleteCRL(caCrl);
                    }
                }
                store.Close();
            }
        }
        catch (Exception e)
        {
            throw e;
        }
        return(updatedCRL);
    }
Пример #22
0
 private void Init()
 {
     crlGenerator = new X509V2CrlGenerator();
     secureRandom = new SecureRandom(new VmpcRandomGenerator());
 }
    /// <summary>
    /// Revoke the certificate.
    /// The CRL number is increased by one and the new CRL is returned.
    /// </summary>
    public static X509CRL RevokeCertificate(
        X509Certificate2 issuerCertificate,
        List <X509CRL> issuerCrls,
        X509Certificate2Collection revokedCertificates
        )
    {
        if (!issuerCertificate.HasPrivateKey)
        {
            throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Issuer certificate has no private key, cannot revoke certificate.");
        }

        using (var cfrg = new CertificateFactoryRandomGenerator())
        {
            // cert generators
            SecureRandom random          = new SecureRandom(cfrg);
            BigInteger   crlSerialNumber = BigInteger.Zero;

            Org.BouncyCastle.X509.X509Certificate bcCertCA = new X509CertificateParser().ReadCertificate(issuerCertificate.RawData);
            AsymmetricKeyParameter signingKey = GetPrivateKeyParameter(issuerCertificate);

            ISignatureFactory signatureFactory =
                new Asn1SignatureFactory(GetRSAHashAlgorithm(defaultHashSize), signingKey, random);

            X509V2CrlGenerator crlGen = new X509V2CrlGenerator();
            crlGen.SetIssuerDN(bcCertCA.IssuerDN);
            crlGen.SetThisUpdate(DateTime.UtcNow);
            crlGen.SetNextUpdate(DateTime.UtcNow.AddMonths(12));

            // merge all existing revocation list
            if (issuerCrls != null)
            {
                X509CrlParser parser = new X509CrlParser();
                foreach (X509CRL issuerCrl in issuerCrls)
                {
                    X509Crl crl = parser.ReadCrl(issuerCrl.RawData);
                    crlGen.AddCrl(crl);
                    var crlVersion = GetCrlNumber(crl);
                    if (crlVersion.IntValue > crlSerialNumber.IntValue)
                    {
                        crlSerialNumber = crlVersion;
                    }
                }
            }

            DateTime now = DateTime.UtcNow;
            if (revokedCertificates == null || revokedCertificates.Count == 0)
            {
                // add a dummy revoked cert
                crlGen.AddCrlEntry(BigInteger.One, now, CrlReason.Unspecified);
            }
            else
            {
                // add the revoked cert
                foreach (var revokedCertificate in revokedCertificates)
                {
                    crlGen.AddCrlEntry(GetSerialNumber(revokedCertificate), now, CrlReason.PrivilegeWithdrawn);
                }
            }

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

            // set new serial number
            crlSerialNumber = crlSerialNumber.Add(BigInteger.One);
            crlGen.AddExtension(X509Extensions.CrlNumber,
                                false,
                                new CrlNumber(crlSerialNumber));

            // generate updated CRL
            X509Crl updatedCrl = crlGen.Generate(signatureFactory);
            return(new X509CRL(updatedCrl.GetEncoded()));
        }
    }
Пример #24
0
        /// <inheritdoc/>
        public Task <Crl> CreateCrlAsync(Certificate issuer, SignatureType signature,
                                         IEnumerable <Certificate> revokedCertificates, DateTime?nextUpdate,
                                         CancellationToken ct)
        {
            try {
                if (issuer == null)
                {
                    throw new ArgumentNullException(nameof(issuer));
                }
                if (issuer.RawData == null)
                {
                    throw new ArgumentNullException(nameof(issuer.RawData));
                }
                if (issuer.IssuerPolicies == null)
                {
                    throw new ArgumentNullException(nameof(issuer.IssuerPolicies));
                }
                if (issuer.KeyHandle == null)
                {
                    throw new ArgumentNullException(nameof(issuer.KeyHandle));
                }

                var bcCertCA   = new X509CertificateParser().ReadCertificate(issuer.RawData);
                var thisUpdate = DateTime.UtcNow;
                var crlGen     = new X509V2CrlGenerator();

                crlGen.SetIssuerDN(bcCertCA.SubjectDN);
                crlGen.SetThisUpdate(DateTime.UtcNow);
                crlGen.SetNextUpdate(nextUpdate ?? issuer.NotAfterUtc);

                if (revokedCertificates == null || !revokedCertificates.Any())
                {
                    // add a dummy entry
                    crlGen.AddCrlEntry(BigInteger.One, thisUpdate, CrlReason.Unspecified);
                }
                else
                {
                    // add the revoked certs
                    foreach (var revokedCertificate in revokedCertificates)
                    {
                        var revoked = revokedCertificate.Revoked?.Date ?? thisUpdate;
                        crlGen.AddCrlEntry(new BigInteger(1, revokedCertificate.SerialNumber),
                                           revoked, CrlReason.PrivilegeWithdrawn);
                    }
                }
                crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false,
                                    new AuthorityKeyIdentifierStructure(bcCertCA));

                // set new serial number
                var crlSerialNumber = BigInteger.ValueOf(DateTime.UtcNow.ToFileTimeUtc());
                crlGen.AddExtension(X509Extensions.CrlNumber, false,
                                    new CrlNumber(crlSerialNumber));

                // generate updated CRL
                var signatureGenerator = _signer.CreateX509SignatureGenerator(
                    issuer.KeyHandle, signature);
                var signatureFactory = new SignatureFactory(signature, signatureGenerator);
                var updatedCrl       = crlGen.Generate(signatureFactory);
                return(Task.FromResult(CrlEx.ToCrl(updatedCrl.GetEncoded())));
            }
            catch (Exception ex) {
                return(Task.FromException <Crl>(ex));
            }
        }