Search code examples
c#asp.net-mvcapisslself-signed

Access the self signed certificate details


I have an asp.net mvc website deployed to iis. A self signed SSL certificate is used in order to secure the traffic. I would like to access this self signed certificate from my asp.net, probably in the startup class or something, in order to get the validity of the self signed certificate (i need this metric for something else).

How could i do that?

I would gladly post some code, or what I've tried so far, but sadly i have no clue where to start from!

I would really appreciate any help.

Edit

To rephrase my question, lets say i have an asp.net web service deployed to IIS, how do i access the certificates in that IIS, and retrieve their validity period (from with in the web service using c# code)


Solution

  • You can do this by opening the cert store and finding certs based upon search criteria. If it's a self signed cert that you created you should know something about it.

    object value = "AcmeOrganization";
    X509FindType findType = X509FindType.FindByIssuerName;
    StoreName storeName = StoreName.My;
    StoreLocation storeLocation = StoreLocation.CurrentUser;
    var store = new X509Store(storeName, storeLocation);
    try
    {
      store.Open(OpenFlags.ReadOnly);
      var certs = store.Certificates.Find(findType, value, true);
      if (certs.Count > 0) 
      {
        return certs[0];
      }
    }
    finally
    {
      store.Close();
      store = null;
    }
    

    This will get you the cert you're looking for then you can call Verify which does chain validation. Other properties along with expiration will be available with the X509Certificate2 object.

    certs[0].Verify()