Click here to Skip to main content
16,021,823 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

What I have tried:

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));
Posted
Updated 4-Jul-23 21:47pm

1 solution

Quote:
C#
string base64cert = Convert.ToBase64String(File.ReadAllBytes(pemFilePath));
var cert = new X509Certificate2(Convert.FromBase64String(base64cert), certAuthCode);
First obvious problem: converting the byte array read from the file to a Base64 string, only to convert that string back to a byte array on the following line, is a waste of resources. Simply pass the byte array directly to the constructor, without the intermediate conversion.

However, your variable name suggests that you are reading a PEM file[^]. This is a text file which contains the Base64-encoded certificate data within specific delimited sections. Passing the raw bytes of the file to the X509Certificate2 constructor won't work.

In .NET 5 or later, the RSA class offers the ImportFromPem method[^], which might work. Otherwise, you'll need to use a library to parse the file - for example, bouncycastle[^] or pem-utils[^]. For specific details, see this SO thread[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900