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

后端 未结 4 742
走了就别回头了
走了就别回头了 2020-12-13 16:31

What is the difference between the two?

4条回答
  •  半阙折子戏
    2020-12-13 17:14

    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
       {
           { "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(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)

提交回复
热议问题