I’m using the latest .NET 8’s HttpClient
to call an API endpoint. Here is my code.
var cert = new X509Certificate("myCert.pfx", "mypass");
var handler = new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual
};
handler.ClientCertificates.Add(cert);
using var httpClient = new HttpClient(handler);
var response = await httpClient.PostAsJsonAsync("https://<my-url>");
var resultString = await response.Content.ReadAsStringAsync();
It generated the following exception:
System.Net.Http.HttpRequestException: An error occurred while sending the request.
---> System.IO.IOException: The decryption operation failed, see inner exception.
---> System.ComponentModel.Win32Exception (0x80090326): The message received was unexpected or badly formatted.
--- End of inner exception stack trace ---
at System.Net.Security.SslStream.ReadAsyncInternal[TIOAdapter](Memory`1 buffer, CancellationToken cancellationToken)
at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(Int16 token)
at System.Net.Http.HttpConnection.InitialFillAsync(Boolean async)
at System.Net.Http.HttpConnection.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
This seems to suggest that the private key is not working as expected. I used the same certificate file and password on Postman and the request succeeded and returned meaningful results. Here are some things I have tried:
- Double-checked my password.
- Breaking up the pfx file into a certificate and private key.
- Specify the request as TLS 1.2.
None of the above worked.