I have a .pem as private key:
-----BEGIN RSA PRIVATE KEY-----
KEY
-----END RSA PRIVATE KEY-----
When I try to convert to X509Certificate2 I get the following error:
Cannot find the requested object.
What I've tried:
static byte[] PEM(string type, byte[] data)
{
string pem = Encoding.ASCII.GetString(data);
string header = String.Format("-----BEGIN {0}-----", type);
string footer = String.Format("-----END {0}-----", type);
int start = pem.IndexOf(header) + header.Length;
int end = pem.IndexOf(footer, start);
string base64 = pem.Substring(start, (end - start));
return Convert.FromBase64String(base64);
}
static X509Certificate2 LoadCertificateFile(string filename)
{
X509Certificate2 x509 = null;
using (FileStream fs = System.IO.File.OpenRead(filename))
{
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
if (data[0] != 0x30)
{
data = PEM("RSA PRIVATE KEY", data);
}
if (data != null)
x509 = new X509Certificate2(data); //Here i get the error
}
return x509;
}
client_pk = LoadCertificateFile(@"..\private.pem");
I can import a full certificate from a .PFX file. I think you could convert your .PEM to .PFX with OpenSSL. Here is the code which is worked for me for a .PFX file load:
SecureString secStr = new SecureString();
"<your_password>".ToCharArray().ToList().ForEach(c => secStr.AppendChar(c));
var cert = new X509Certificate2();
cert.Import("<your path to .PFX file>", secStr, X509KeyStorageFlags.Exportable);