31

我的商店中有一个 X509Certificate2 证书,我想使用private key导出到一个字节数组。证书字节数组必须是这样,当我稍后从字节数组导入证书时,私钥将带有私钥。

我尝试了很多方法,但没有成功导出带有私钥的证书。

X509Store store = new X509Store(StoreLocation.CurrentUser);      

store.Open(OpenFlags.ReadOnly);

X509Certificate2 cert = store.Certificates[1];

byte[] certBytes = cert.GetRawCertData(); // Obviously does not work!

是否可以将带有私钥的证书成功导出到字节数组?

非常感谢帮助。

4

2 回答 2

35

该类的Export功能X509Certificate2允许您将带有私钥的证书导出到字节数组。

以下代码演示了使用私钥导出证书:

X509Store store = new X509Store(StoreLocation.CurrentUser);

store.Open(OpenFlags.ReadOnly);

X509Certificate2 cert = store.Certificates[1];

// Export the certificate including the private key.
byte[] certBytes = cert.Export(X509ContentType.Pkcs12);

要保护您导出的证书,请使用以下Export函数重载:

byte[] certBytes = cert.Export(X509ContentType.Pkcs12, "SecurePassword");

开始编辑

要导入证书,请使用以下代码:

X509Certificate2 certToImport = new X509Certificate2(arr, "SecurePassword");

// To mark it as exportable use the following constructor:
X509Certificate2 certToImport = new X509Certificate2(arr, "SecurePassword", X509KeyStorageFlags.Exportable);
// certToImport.HasPrivateKey must be true here!!

X509Store store2 = new X509Store(StoreName.TrustedPublisher,
                                 StoreLocation.CurrentUser);
store2.Open(OpenFlags.MaxAllowed);

store2.Add(certToImport);
store2.Close();

结束编辑

于 2012-03-21T19:22:41.907 回答
4

未获取私钥的一个原因可能是它在最初添加到 CAPI 时已被标记为“不可导出”。在那种情况下,我不相信这是任何真正的摆脱它的方法。

于 2012-03-22T10:05:25.257 回答