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

Eri*_*son 22 c# x509certificate2 x509

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

我尝试了许多方法,但没有成功使用私钥导出证书.

X509Store store = new X509Store(StoreLocation.CurrentUser);      

store.Open(OpenFlags.ReadOnly);

X509Certificate2 cert = store.Certificates[1];

byte[] certBytes = cert.GetRawCertData(); // Obviously does not work!
Run Code Online (Sandbox Code Playgroud)

是否可以使用私钥将证书成功导出到字节数组?

非常感谢帮助.

Han*_*ans 29

类的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);
Run Code Online (Sandbox Code Playgroud)

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

byte[] certBytes = cert.Export(X509ContentType.Pkcs12, "SecurePassword");
Run Code Online (Sandbox Code Playgroud)

开始编辑

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

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();
Run Code Online (Sandbox Code Playgroud)

结束编辑

  • 这将抛出```System.Security.Cryptography.CryptographicException:'键无法在指定的状态下使用.````为.NET 4.6.2控制台应用程序. (3认同)