如何从文件加载 C# 中的 .pem 证书?

问题描述 投票:0回答:2

背景

我有一个 pfx 证书文件。我可以使用以下代码成功将其加载到

X509Certificate2
类:

var path = "mycert.pfx"
var password = "mypassword";
var certificate = new X509Certificate2(path, password);

出于某些原因,我想使用 .pem 格式而不是二进制格式。因此,我使用以下 OpenSSL 命令将“mycert.pfx”转换为“mycert.pem”:

pkcs12 -in mycert.pfx -out mycert.pem -nodes

问题

如何以与成功加载 mycert.pfx 类似的方式加载转换后的 mycert.pem?下面的代码给我一个 CryptographicException ,说“找不到请求的对象”。 (注意:这不是关于文件未找到的io异常)

var path = "mycert.pem"
var password = "mypassword";
var certificate = new X509Certificate2(path, password);
c# openssl x509certificate pem pfx
2个回答
3
投票

Windows 不支持 PEM (Base64) 格式的 PKCS#12。您必须仅使用二进制编码的 PKCS#12 文件。


0
投票

.NET 5 有新方法

X509Certificate2.CreateFromPemFile()

© www.soinside.com 2019 - 2024. All rights reserved.