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
基础教程推荐
- 获取C#保存对话框的文件路径 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 将数据集转换为列表 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 如果条件可以为空 2022-01-01
