简体   繁体   English

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

[英]Export X509Certificate2 to byte array with the Private key

I have an X509Certificate2 certificate in my store that I would like to export to a byte array with the private key . 我的商店里有一个X509Certificate2证书,我想 私钥导出到一个字节数组。 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. 证书字节数组必须是这样的,当我稍后将从字节数组导入证书时,私钥将具有私钥。

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. 非常感谢帮助。

The Export function of the X509Certificate2 class allows you to export a certificate with the private key to a byte array. X509Certificate2类的Export函数允许您将带有私钥的证书导出到字节数组。

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 Export function: 要保护导出的证书,请使用以下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 结束编辑

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. 不获取私钥的一个原因可能是它最初被添加到CAPI时被标记为“不可导出”。 In that case, I don't believe that is any real way of getting it out. 在这种情况下,我不相信这是真正的解决方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM