1

I'm trying to do a HTTPS get request via the HttpClient class. However there are exceptions thrown when trying to do the request as the provided certificate isn't trusted.

I have access to the private SSL key and the question is how do I install the private key into the application so it can decrypt the public key from the website?

HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://siteUsingSSL.com/");

var response = await httpClient.GetAsync("swagger/index.html");

Console.WriteLine(response.StatusCode);
  • Is it an option to install the certificate as trusted on the machine? – Daniel Stackenland Nov 15 '18 at 15:54
  • 1
    "There are exceptions thrown" Please include the exact exception in your question, since it can affect the answer. Are you getting an error like "Could not establish trust relationship," "The certificate could not be validated according to the validation procedure," or just a simple HTTP 401/403 status? – John Wu Nov 15 '18 at 16:10
  • The proposed dup is a very bad choice, that question is about iOS and the answer is specific to Xamarin. – Remus Rusanu Nov 15 '18 at 17:10

1 Answers1

3

To do custom TLS/SSL certificate validation, use the ServicePointManager.ServerCertificateValidationCallback callback. In the callback you can return true or false based on whatever logic you fancy.

I have access to the private SSL key and the question is how do I install the private key into the application so it can decrypt the public key from the website?

Absolutely No. The private key must never ever leave the site. Besides, there is nothing to decrypt in the certificate. The certificate is signed using the private key and the validation of the signature requires the public key, which is embedded in the certificate. The certificate you receive for sure will be valid, because otherwise the whole SSL/TLS handshake would fail.

What you need to decide is whether you trust the certificate you received.

A naive solution is to hardcode a certificate property in your code (say, the thumbprint) and then validate the received certificate's thumbprint. However, such a validation will prove to be bad as soon as you need to change the site certificate.

Another naive solution is to validate the certificate authority, but then anybody can create a self-signed certificate and fake the authority you expect.

By far, the best solution is to use trusted certificate for your site. Ever since letsencrypt.org became available, there is really no excuse not to have a trusted cert on your site.

Remus Rusanu
  • 288,378
  • 40
  • 442
  • 569