Search code examples
c#x509certificate-revocation

Extract properties from a CRL file using C#


I'd like to write a program which monitors CRL (Certificate Revocation List) expiration date. Therefore, I'd like to read the following properties from a CRL file: 1) Effective Date 2) Next Update 3) Next CRL Publish

How can I accomplish my task? I've only managed to find types for X509Certificate2, X509Chain, x509RevocationMode etc..


Solution

  • you can use the class X509Certificate2 to get information needed.

    example:To handle one certification file

    X509Certificate2 x509 = new X509Certificate2();
    byte[] rawData = ReadFile(fname);
    x509.Import(rawData);
    var validDate= x509 . NotBefore;    
    var expireDate = x509.NotAfter;
    
    
    //Reads a file.
    internal static byte[] ReadFile (string fileName)
    {
        FileStream f = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        int size = (int)f.Length;
        byte[] data = new byte[size];
        size = f.Read(data, 0, size);
        f.Close();
        return data;
    }
    

    reference:

    https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2(v=vs.110).aspx

    Edit:

    You can use the BouncyCastle.Crypto library to handle CRL. Download the library and reference the BouncyCastle.Crypto.dll or instal the nuget package:

    Install-Package BouncyCastle
    
    
      //reference library BouncyCastle.Crypto
      //http://www.bouncycastle.org/csharp/
      //Load CRL file and access its properties
        public void  GetCrlInfo(string fileName, Org.BouncyCastle.Math.BigInteger serialNumber, Org.BouncyCastle.X509.X509Certificate cert)
        {
            try
            {
                byte[] buf = ReadFile(fileName);
                X509CrlParser xx = new X509CrlParser();
                X509Crl ss = xx.ReadCrl(buf);
                var nextupdate = ss.NextUpdate;
                var isRevoked = ss.IsRevoked(cert);
                Console.WriteLine("{0} {1}",nextupdate,isRevoked);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }