I want to create a X509Certificate2 object based on a PEM file. The problem is setting the PrivateKey property of X509Certificate2. I read X509Certificate2.CreateFromCertFile()
Using .NET 5.0 we finally have a nice way of doing this.
The X509Certificate2 class provides two static methods X509Certificate2.CreateFromPem and X509Certificate2.CreateFromPemFile. So if you have the file path then can call:
var cert = X509Certificate2.CreateFromPemFile(filePath);
If creating the certificate without the file then can pass in ReadOnlySpan for the certificate thumbprint and key. There are also X509Certificate2.CreateFromEncryptedPem and X509Certificate2.CreateFromEncryptedPemFile if the contents is encrypted.
More info can be found in the official API docs here: https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate2.createfrompemfile?view=net-5.0