Create X509Certificate2 from PEM file in .NET Core

前端 未结 2 1822
情话喂你
情话喂你 2021-02-13 04:22

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()

2条回答
  •  -上瘾入骨i
    2021-02-13 04:50

    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

提交回复
热议问题