As in Postman we have certificate and key file, how do I validate the KEY file using c# or MVC. I have tried adding the below code but seems like for the KEY file we've some other code to write. Please suggest some help.
C#
string base64cert = Convert.ToBase64String(File.ReadAllBytes(pemFilePath));
var cert = new X509Certificate2(Convert.FromBase64String(base64cert), certAuthCode);
cert.PrivateKey = null;
handler.ClientCertificates.Add(cert);
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.SslProtocols = SslProtocols.Tls12;
handler.ClientCertificates.Add(new X509Certificate2(crtFilePath));
//For Key File Path
handler.ClientCertificates.Add(new X509Certificate2(crtKeyPath));

Amit MohantyRank #112 · 20K reputationPosted Jun 28, 2023, 6:48 AM EDT
Please take a look at the code below; it may be helpful to you.
var keyBytes = File.ReadAllBytes(crtKeyPath); cert.PrivateKey = DecodePrivateKey(keyBytes); // Function to decode the private key from the file bytes private static AsymmetricAlgorithm DecodePrivateKey(byte[] keyBytes) { var rsa = RSA.Create(); rsa.ImportPkcs8PrivateKey(keyBytes, out _); return rsa; }Akaash Chintamani MeherRank #5,130 · 310 reputationPosted Jun 28, 2023, 6:59 AM EDT
@Amit Mohanty - Thanks for the response. I think the ImportPkcs8PrivateKey() method is available in higher version of .Net because I'm getting error for the same. Could you please provide any alternatives.
Amit MohantyRank #112 · 20K reputationPosted Jun 28, 2023, 7:08 AM EDT
Try this
private static RSACryptoServiceProvider LoadPrivateKey(byte[] keyBytes) { var rsa = new RSACryptoServiceProvider(); rsa.ImportCspBlob(keyBytes); return rsa; }