Harvey Lin Harvey Lin - 1 month ago 21
C# Question

Convert different certificate revocation list formats in .net

I need to convert a bunch of certificate revocation list in .crl extension,they are in DER format (Binary), and I need to convert them into PEM format (Base64 string representation of the binary content of each .crl file).

As per instructions in Convert .der to .pem using OpenSSL-Net, I have created the following code trying to convert a single .crl file from its DER format to PEM format:

private static void generateCrl()
{
byte [] certbyte = File.ReadAllBytes("D:\\certsunzip\\DODIDCA_44.crl");
Console.WriteLine("First byte: {0}", certbyte[0]);
X509Certificate2 cert = new X509Certificate2(certbyte);
string pem = "-----BEGIN X509 CRL-----\r\n" + Convert.ToBase64String(cert.RawData, Base64FormattingOptions.InsertLineBreaks) + "-----END X509 CRL-----";
using (StreamWriter outputFile = new StreamWriter(@"D:\certsunzip\test.crl"))
{
foreach (char chr in pem)
outputFile.WriteLine(chr);
}
}


However, when I run the code, the X509Certificate2 constructor is throwing me an CryptographicException saying "Cannot find the requested object". I would like to know is there another way I can do this conversion, maybe the X509Certificate2 constructor does not like the crl files?

Answer

Remove 3rd line, because it doesn't make sense (because X509Certificate2 class doesn't support CRLs) and use 'certbyte' variable on a 4th line:

private static void generateCrl()
{
    byte [] certbyte = File.ReadAllBytes("D:\\certsunzip\\DODIDCA_44.crl");
    Console.WriteLine("First byte: {0}", certbyte[0]);
    string pem = "-----BEGIN X509 CRL-----\r\n" + Convert.ToBase64String(certbyte, Base64FormattingOptions.InsertLineBreaks) + "-----END X509 CRL-----";
    using (StreamWriter outputFile = new StreamWriter(@"D:\certsunzip\test.crl"))
    {
        outputFile.Write(pem);
    }
}

This will work.