我的商店中有一个 X509Certificate2 证书,我想将其导出到字节数组和私钥。证书字节数组必须这样,当我稍后从字节数组导入证书时,私钥将包含私钥。
我尝试了很多方法都没有成功导出带有私钥的证书。
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2 cert = store.Certificates[1];
byte[] certBytes = cert.GetRawCertData(); // Obviously does not work!
是否可以将带私钥的证书成功导出为字节数组?
非常感谢您的帮助。
最佳答案
X509Certificate2
类的Export
函数允许您导出
带有字节数组私钥的证书。
以下代码演示了使用私钥导出证书:
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();
结束编辑
关于c# - 使用私钥将 X509Certificate2 导出到字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9810887/