C# 使用私钥将 X509Certificate2 导出到字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9810887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 10:42:22  来源:igfitidea点击:

Export X509Certificate2 to byte array with the Private key

c#x509x509certificate2

提问by Erik Larsson

I have an X509Certificate2 certificate in my store that I would like to export to a byte array withthe private key. The certificate byte array has to be so that when I then later would import the certificate from the byte array the private key would have the private key with it.

我在我的店里的X509Certificate2证书,我想导出到一个字节数组私有密钥。证书字节数组必须是这样,当我稍后从字节数组导入证书时,私钥将带有私钥。

I have tried many wayes but has not succeded to export the certificate with the 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!

Is it possible to successfully export the certificate with private key to a byte array?

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

Help is very appreciated.

非常感谢帮助。

采纳答案by Hans

The Exportfunction of the X509Certificate2class allows you to export a certificate with the private key to a byte array.

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

The following code demonstrates exporting a certificate with the private key:

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

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);

To secure your exported certificate use the following overload of the Exportfunction:

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

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

BEGIN EDIT

开始编辑

To import the certificate use the following code:

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

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();

END EDIT

结束编辑

回答by S?ren Mors

One reason for not getting the private key, could be that it has been marked as "Not Exportable" when it was originally added to CAPI. In that case, I don't believe that is any real way of getting it out.

无法获取私钥的原因之一可能是它最初添加到 CAPI 时已被标记为“不可导出”。在那种情况下,我认为这不是解决问题的任何真正方法。