Create CRL file with Bouncy Castle c#

2019-08-08 18:07发布

I've build my own root CA certificate with Bouncy Castle, and I'm using it to build other certificates. I want to build a Certificate Revocation List (CRL) to include the list of revoqued certificates, using Bouncy Castle C#. Example:

//Retrieve CA root certificate

X509Store CAstore = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
CAstore.Open(OpenFlags.ReadWrite | OpenFlags.OpenExistingOnly);

X509Certificate2Collection x509Certificate2Collection =
CAstore.Certificates.Find(X509FindType.FindBySerialNumber,
                         this.textBoxSerialCA.Text, true);

X509Certificate2 cert = x509Certificate2Collection[0];
var certCA = DotNetUtilities.FromX509Certificate(cert);
CAstore.Close();

X509V2CrlGenerator crlGen = new X509V2CrlGenerator();
crlGen.SetIssuerDN(certCA.IssuerDN);
crlGen.SetThisUpdate(DateTime.Now);
crlGen.SetNextUpdate(DateTime.Now.AddYears(1));
crlGen.SetSignatureAlgorithm("SHA1withRSA");

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

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

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

var randomGenerator = new CryptoApiRandomGenerator();
var random = new SecureRandom(randomGenerator);

var Akp = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(cert.PrivateKey).Private;                


X509Crl crlTemp = crlGen.Generate(Akp,random);

All is OK until this point. How can I save the X509Crl object into a .crl file?

Best regards.

3条回答
时光不老,我们不散
2楼-- · 2019-08-08 18:42

This answer comes quite late, but you can use the PemWriter class in Bouncy Castle to write to a PEM file.

PemWriter pemWriter = new PemWriter(new StreamWriter(File.Open(fileName, FileMode.Create)));
pemWriter.WriteObject(crlTemp);
pemWriter.Writer.Flush();
pemWriter.Writer.Close();
查看更多
戒情不戒烟
3楼-- · 2019-08-08 18:43

In BouncyCastle.Crypto version 1.7.4114.6375, I was able to take your code and simply add:

var b = crlTemp.GetEncoded();

System.IO.File.WriteAllBytes(@"C:\temp\test.crl", b);

Then, in Windows, double clicking on the 'test.crl' file will open the standard, built-in Certificate Revocation List dialog without any errors and all the information looks correct when compared to other CRL files.

查看更多
\"骚年 ilove
4楼-- · 2019-08-08 18:46

And after you've got a CRL in PEM format you can convert it via openssl with the following command:

openssl crl -in list.pem -outform der -out list.crl
查看更多
登录 后发表回答