X509Certificate.Export方法

3 c#

我尝试导出证书.pfx:

string certPath = "D:\\cert.pfx";
cert = new X509Certificate2(certPath, "pass");

byte[] certData = cert.Export(X509ContentType.Pfx,"pass"); /// **error in this line** 

X509Certificate newCert = new X509Certificate(certData,"pass");
Run Code Online (Sandbox Code Playgroud)

但它完成了这个错误:

密钥无法在指定状态下使用.

有人能帮帮我吗?任何解决方案作为出口证书从商店?

and*_*i m 8

我认为您无法导出私钥,因为您用于创建证书的构造函数X509Certificate2(filePath, password)不会将生成的证书标记为可导出.我建议使用一个允许您指定可导出标志的重载构造函数 - 例如X509KeyStorageFlags.Exportable X509Certificate2(filePath, password, X509KeyStorageFlags.Exportable).

有关X509Certificate2和MSDN Library上的其他X509KeyStorageFlags的可用构造函数重载的详细信息.

此外,您应该检查X509Certificate2.HasPrivateKey属性以确保您具有与证书关联的私钥.