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

标签 c# x509 x509certificate2

我的商店中有一个 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/

相关文章:

c# - WPF MeasureOverride 不适用于我的自定义控件

c# - C# 代码中的 Excel 引用问题

c# - 将证书添加到 x509Store 不会执行任何操作 C#

java - 使用 Java 和 BouncycaSTLe 进行 X.509 证书验证

mongodb - 无法使用来自 c# 的 x509 证书身份验证连接到 MongoDB 服务器

c# - 处理多类事件的最佳方式?

c# - 使用 Windows Installer 安装时如何更改应用程序的 exe.config 文件

ssl - Root CA Certificate 可以位于证书路径的中间吗?

c# - 在 C# 和 iText 7 中使用 x509Certificate2 创建 IExternalSignature

c# - X509Certificate2.使用 NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG 导入