X509Certificate2.CreateFromPem(ReadOnlySpan<Char>, ReadOnlySpan<Char>) Method

Definition

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

public:
 static System::Security::Cryptography::X509Certificates::X509Certificate2 ^ CreateFromPem(ReadOnlySpan<char> certPem, ReadOnlySpan<char> keyPem);
public static System.Security.Cryptography.X509Certificates.X509Certificate2? CreateFromPem (ReadOnlySpan<char> certPem, ReadOnlySpan<char> keyPem);
static member CreateFromPem : ReadOnlySpan<char> * ReadOnlySpan<char> -> System.Security.Cryptography.X509Certificates.X509Certificate2
Public Shared Function CreateFromPem (certPem As ReadOnlySpan(Of Char), keyPem As ReadOnlySpan(Of Char)) As X509Certificate2

Parameters

certPem
ReadOnlySpan<Char>

The text of the PEM-encoded X509 certificate.

keyPem
ReadOnlySpan<Char>

The text of the PEM-encoded private key.

Returns

X509Certificate2

A new certificate with the private key.

Exceptions

The contents of certPem do not contain a PEM-encoded certificate, or it is malformed.

-or-

The contents of keyPem do not contain a PEM-encoded private key, or it is malformed.

-or-

The contents of keyPem contains a key that does not match the public key in the certificate.

-or-

The certificate uses an unknown public key algorithm.

Remarks

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.

If the PEM-encoded certificate and private key are in the same text, use the same string for both certPem and keyPem, for example, CreateFromPem(combinedCertAndKey, combinedCertAndKey);. Combined PEM-encoded certificates and keys do not require a specific order. For the certificate, the 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 CreateFromEncryptedPem(ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>) to specify a password.

Applies to