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
基础教程推荐
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
