我正在尝试导出没有私钥的证书,如BASE-64编码文件,与从Windows导出它相同。从Windows导出时,我可以在记事本中打开.cer文件。
当我尝试以下操作并在记事本上打开时,我会得到二进制数据......我认为它是......不可读。
X509Certificate2 cert = new X509Certificate2("c:\\myCert.pfx", "test", X509KeyStorageFlags.Exportable);
File.WriteAllBytes("c:\\testcer.cer", cert.Export(X509ContentType.Cert));
我尝试删除'X509KeyStorageFlags.Exportable',但这不起作用。我错过了什么吗?
编辑 - 我试过了
File.WriteAllText("c:\\testcer.cer",Convert.ToBase64String(cert.Export(X509ContentType.Cert)))
然而,这似乎有效,错过了“----- BEGIN CERTIFICATE -----”和“----- END CERTIFICATE -----”
答案 0 :(得分:58)
也许
/// <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();
}
答案 1 :(得分:6)
试试这个:
X509Certificate2 cerifikata = new X509Certificate2("C://certificate.pfx");
File.WriteAllBytes("D://Test.cer",cerifikata.Export(X509ContentType.Cert));
答案 2 :(得分:1)
对于那些在.NET Core中实现类似功能的人来说,这里是基于tyranid所做的代码。 Base64FormattingOptions.InsertLineBreaks并不存在于.NET Core中,因此我必须以自己的方式实现换行。
// Certificates content has 64 characters per lines
private const int MaxCharactersPerLine = 64;
/// <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(this X509Certificate2 cert)
{
var builder = new StringBuilder();
var certContentBase64 = Convert.ToBase64String(cert.Export(X509ContentType.Cert));
// Calculates the max number of lines this certificate will take.
var certMaxNbrLines = Math.Ceiling((double)certContentBase64.Length / MaxCharactersPerLine);
builder.AppendLine("-----BEGIN CERTIFICATE-----");
for (var index = 0; index < certMaxNbrLines; index++)
{
var maxSubstringLength = index * MaxCharactersPerLine + MaxCharactersPerLine > certContentBase64.Length
? certContentBase64.Length - index * MaxCharactersPerLine
: MaxCharactersPerLine;
builder.AppendLine(certContentBase64.Substring(index * MaxCharactersPerLine, maxSubstringLength));
}
builder.AppendLine("-----END CERTIFICATE-----");
return builder.ToString();
}
答案 3 :(得分:0)
//然而,错过了“----- BEGIN CERTIFICATE -----”和“----- END CERTIFICATE -----”
这些缺失的行是可选的。 CA可能会生成它们,具体取决于设置。出于所有实际原因,可以从Base64编码文件中删除它们。