0

When I tested the query in Postman I had to add files with extension .cer and .key to the certificates. I wanted to achieve the same in c# code but errors are generated when I add both files.

What do I need to add to the code to be able to perform the same query as in Postman ?

Error.

Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException: Cannot find the requested object.

var handler = new HttpClientHandler();
handler.ClientCertificates.Add(new X509Certificate2(@"C:\test1.cer"));

//This generates an error 
handler.ClientCertificates.Add(new X509Certificate2(@"C:\test2.key"));

var client = new System.Net.Http.HttpClient(handler);
var byteArray = Encoding.ASCII.GetBytes("test:test");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

var data = new Test
{
    test1 = "test"
};

string json = JsonConvert.SerializeObject(data);
StringContent content = new StringContent(json);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
HttpResponseMessage signInResponse = client.PostAsync("https://test-dev:8800/test", content).Result;
lukaszFD
  • 99
  • 6
  • 1
    https://stackoverflow.com/questions/18446135/add-private-key-to-x509certificate – pm100 Mar 03 '22 at 21:22
  • @pm100, Thank you for the tip. It led me to the right solution, which I found at https://stackoverflow.com/a/64142227/7038630. The only change I made was to replace "ImportPkcs8PrivateKey" with "ImportRSAPrivateKey". – lukaszFD Mar 04 '22 at 12:29
  • And here https://stackoverflow.com/a/70132607/7038630 is the answer why I changed "ImportPkcs8PrivateKey" to "ImportRSAPrivateKey". – lukaszFD Mar 04 '22 at 12:37

0 Answers0