Recently in my project, I wanted to test SSL validation in my Unit Test while Making a HttpClient request. This article will show you how to read the certificate file in C# and add it to HttpClient.
How to convert certificates to Base64 (.cer) format
- Open Certificate
- Click on the
Details
Tab - Click on
Copy to File
. - Select
Base-64 encoded X.509.
The code is straightforward. $ads={1}
private X509Certificate2 GetClientTestingCertificate(string certificate)
{
X509Certificate2 certificate2 = null;
try
{
var privateKeyBytes = Convert.FromBase64String(certificate);
var pfxPassword = "";
certificate2 = new X509Certificate2(privateKeyBytes, pfxPassword, X509KeyStorageFlags.Exportable);
return certificate2;
}
catch (Exception)
{
}
return certificate2;
}
How to use
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.SslProtocols = SslProtocols.Tls12;
handler.ClientCertificates.Add(GetClientTestingCertificate("base64 data"));
var client = new HttpClient(handler);