Exporting a Certificate as BASE-64 encoded .cer(将证书导出为 BASE-64 编码的 .cer)
问题描述
我正在尝试将没有私钥的证书导出为 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将证书导出为 BASE-64 编码的 .cer


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01