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-----"
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 + .
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With