Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create CRL file with Bouncy Castle c#

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.

like image 455
Julio Loizaga Avatar asked Dec 23 '15 13:12

Julio Loizaga


2 Answers

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();
like image 89
Luke Joshua Park Avatar answered Nov 02 '22 05:11

Luke Joshua Park


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.

like image 21
Kevin Avatar answered Nov 02 '22 03:11

Kevin