This method converts X509Certificate2 to PEM format in C#:
public static string ConvertToPEM(X509Certificate2 cert)
{
if (cert == null)
throw new ArgumentNullException("cert");
string base64 = Convert.ToBase64String(cert.RawData).Trim();
string pem = "-----BEGIN CERTIFICATE-----" + Environment.NewLine;
do
{
pem += base64.Substring(0, 64) + Environment.NewLine;
base64 = base64.Remove(0, 64);
}
while (base64.Length > 64);
pem += base64 + Environment.NewLine + "-----END CERTIFICATE-----";
return pem;
}
This method uses OpenSSL to parse PEM encoded certificate in C:
X509* parse_pem_cert(const char* buffer, int buffer_len)
{
X509* cert = NULL;
BIO* bio = NULL;
if ((NULL == buffer) || (buffer_len < 1))
return NULL;
bio = BIO_new_mem_buf((char *) buffer, buffer_len);
if (NULL == bio)
return NULL;
cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
if (NULL == cert)
{
BIO_free(bio);
return NULL;
}
BIO_free(bio);
return cert;
}