Quote:
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[
^].