将证书导出为 BASE-64 编码的 .cer

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)