What is the difference between X509Certificate2 and X509Certificate in .NET?

Viewed 59254

What is the difference between the two?

4 Answers

The x509Certificate was introduced in .NET v1.0/1.1 and was (comparatively) limited in its functionality. It can be used to get information about an existing certificate (valid dates, issuer, etc.). It had simple methods/operations (i.e. reading a cert from disk).

The x509Certificate2 is a subclass of x509Certificate with additional functionality.

  • It represents an actual X509 certificate.
  • It was new in the .NET Framework v2.0.
  • This class gives you access to all the V2 and V3 properties (authority key identifier and key usage).
  • It supports loading a certificate from a certificate store.

For those that would like to read the certificate and use this to authenticate one would simply create a X509Certificate2 and pass the X509Certificate in it's constructor.

For a signed assembly (the exe) the code would be code like this, and I omit error validation for simplicity.

Module m = Assembly.GetEntryAssembly().GetModules()[0];
using (var cert = m.GetSignerCertificate())
using (var cert2 = new X509Certificate2(cert))
{
   var _clientHandler = new HttpClientHandler();
   _clientHandler.ClientCertificates.Add(cert2);
   _clientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
   var myModel = new Dictionary<string, string>
   {
       { "property1","value" },
       { "property2","value" },
   };
   using (var content = new FormUrlEncodedContent(myModel))
   using (var _client = new HttpClient(_clientHandler))
   using (HttpResponseMessage response = _client.PostAsync($"{url}/{controler}/{action}", content).Result)
   {
       response.EnsureSuccessStatusCode();
       string jsonString = response.Content.ReadAsStringAsync().Result;
       var json = new Newtonsoft.Json.JsonSerializer();
       var myClass = JsonConvert.DeserializeObject<MyClass>(json);
    }
}

Obviously you're class isn't called MyClass but some business object that you'd expect from the web service.

You can send a class to your action by sending the property & value you require filled. You can now ensure that the request you received is from a valid mobile or windows client by reading the request certificate like so:

public class MyController : ApiController
{
    public IHttpActionResult Get()
    {           
       X509Certificate2 clientCertInRequest = Request.HttpContext.Connection.ClientCertificate;
       if (!clientCertInRequest.Verify() || !AllowedCerialNumbers(clientCertInRequest.SerialNumber))
       {
            Response.StatusCode = 404;
            return null;
       }
       //your code
   }

}

What is left is to set your webserver to accept client certificates... You can read all about properties that come from the new format and you have secured your public web service, something most fail to do as just being authorized isn't good enough anymore (if it ever was)

Related