问题描述
我正在尝试将没有私钥的证书导出为 BASE-64 编码文件,与从 Windows 中导出它相同.从 Windows 导出时,我可以在记事本中打开 .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));
我尝试删除X509KeyStorageFlags.Exportable",但这不起作用.我错过了什么吗?
I tried removing the 'X509KeyStorageFlags.Exportable" but that doesn't work. Am I missing something?
编辑 - 我试过了
File.WriteAllText("c:\testcer.cer",Convert.ToBase64String(cert.Export(X509ContentType.Cert)))
这似乎可行,但是,缺少-----BEGIN CERTIFICATE-----"和-----END CERTIFICATE-----"
and that seems to work, however, missing the "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----"
推荐答案
也许
/// <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();
}
这篇关于将证书导出为 BASE-64 编码的 .cer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!