Search code examples
c#opensslx509certificatepempfx

How can I load a .pem certificate in c# from file?


Context

I have a pfx certificate file. I can successfully load it to an X509Certificate2 class using the following code:

var path = "mycert.pfx"
var password = "mypassword";
var certificate = new X509Certificate2(path, password);

For some reasons I would like to use .pem format instead of binary format. So I've converted my "mycert.pfx" to "mycert.pem" using the following OpenSSL command:

pkcs12 -in mycert.pfx -out mycert.pem -nodes

Question

How can I load my converted mycert.pem in a similar way as I successfully loaded the mycert.pfx? The following code give me a CryptographicException saying "Cannot find the requested object." (note: this is not an io exception about file not found)

var path = "mycert.pem"
var password = "mypassword";
var certificate = new X509Certificate2(path, password);

Solution

  • Windows doesn't support PKCS#12 in PEM (Base64) format. You must use PKCS#12 files in binary encoding only.