Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting a Certificate as BASE-64 encoded .cer

I am trying to export a cert without the private key as as BASE-64 encoded file, same as exporting it from windows. When exported from windows I am able to open the .cer file in notepad.

When I try the following and open on notepad I get binary data...I think it is...not readable.

X509Certificate2 cert = new X509Certificate2("c:\\myCert.pfx", "test", X509KeyStorageFlags.Exportable);  File.WriteAllBytes("c:\\testcer.cer", cert.Export(X509ContentType.Cert)); 

I tried removing the 'X509KeyStorageFlags.Exportable" but that doesn't work. Am I missing something?

Edit - I tried

File.WriteAllText("c:\\testcer.cer",Convert.ToBase64String(cert.Export(X509ContentType.Cert))) 

and that seems to work, however, missing the "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----"

like image 354
Saif Khan Avatar asked Jan 19 '11 18:01

Saif Khan


People also ask

What is a base-64 encoded certificate?

Base64 encoding is a mechanism to convert binary data into text so that it can be easily transported as text, such as within an e-mail. When converting from binary to text, each three bytes of binary are converted into four characters from the following set: a–z , A–Z , 0–9 , \ , and + .


1 Answers

Perhaps

/// <summary> /// Export a certificate to a PEM format string /// </summary> /// <param name="cert">The certificate to export</param> /// <returns>A PEM encoded string</returns> public static string ExportToPEM(X509Certificate cert) {     StringBuilder builder = new StringBuilder();                  builder.AppendLine("-----BEGIN CERTIFICATE-----");     builder.AppendLine(Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));     builder.AppendLine("-----END CERTIFICATE-----");      return builder.ToString(); } 
like image 193
tyranid Avatar answered Oct 04 '22 03:10

tyranid