Bewerken

Share via


X509Certificate2.CreateFromPemFile(String, String) Method

Definition

Creates a new X509 certificate from the file contents of an RFC 7468 PEM-encoded certificate and private key.

public static System.Security.Cryptography.X509Certificates.X509Certificate2 CreateFromPemFile (string certPemFilePath, string? keyPemFilePath = default);
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static System.Security.Cryptography.X509Certificates.X509Certificate2 CreateFromPemFile (string certPemFilePath, string? keyPemFilePath = default);
static member CreateFromPemFile : string * string -> System.Security.Cryptography.X509Certificates.X509Certificate2
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
static member CreateFromPemFile : string * string -> System.Security.Cryptography.X509Certificates.X509Certificate2
Public Shared Function CreateFromPemFile (certPemFilePath As String, Optional keyPemFilePath As String = Nothing) As X509Certificate2

Parameters

certPemFilePath
String

The path for the PEM-encoded X509 certificate.

keyPemFilePath
String

If specified, the path for the PEM-encoded private key. If unspecified, the certPemFilePath file will be used to load the private key.

Returns

A new certificate with the private key.

Attributes

Exceptions

The contents of the file path in certPemFilePath do not contain a PEM-encoded certificate, or it is malformed.

-or-

The contents of the file path in keyPemFilePath do not contain a PEM-encoded private key, or it is malformed.

-or-

The contents of the file path in keyPemFilePath contains a key that does not match the public key in the certificate.

-or-

The certificate uses an unknown public key algorithm.

certPemFilePath is null.

Remarks

See ReadAllText(String) for additional documentation about exceptions that can be thrown.

The SubjectPublicKeyInfo from the certificate determines what PEM labels are accepted for the private key. For RSA certificates, accepted private key PEM labels are "RSA PRIVATE KEY" and "PRIVATE KEY". For ECDSA certificates, accepted private key PEM labels are "EC PRIVATE KEY" and "PRIVATE KEY". For DSA certificates, the accepted private key PEM label is "PRIVATE KEY".

PEM-encoded items that have a different label are ignored.

Combined PEM-encoded certificates and keys do not require a specific order. For the certificate, the first certificate with a CERTIFICATE label is loaded. For the private key, the first private key with an acceptable label is loaded. More advanced scenarios for loading certificates and private keys can leverage PemEncoding to enumerate PEM-encoded values and apply any custom loading behavior.

For password protected PEM-encoded keys, use CreateFromEncryptedPemFile(String, ReadOnlySpan<Char>, String) to specify a password.

Applies to