c# X509Certificate2添加证书标记为可导出的

本文关键字:记为 X509Certificate2 添加 证书 | 更新日期: 2023-09-27 18:10:06

我有一个。net 4.0程序,它在9000端口上运行localhost。我想支持SSL,并有一个。pfx证书导入。

因为程序在多台计算机上运行,所以程序本身负责存储证书并注册其端口。

当程序导入并注册时,一切正常。但是当我重新启动计算机时,https连接不工作了。更多. .

事件查看器给出以下错误:

访问SSL服务器时发生致命错误凭证私钥。方法返回的错误代码密码模块为0x8009030D。内部错误状态为10001。

在为端点使用SSL配置时发生错误0.0.0.0:9000。错误状态码包含在返回的数据中。

我发现了一些解决方案,其中规定您需要在导入时将证书标记为"可导出"但我不知道如何在代码中做到这一点。

网站1和网站2

存储证书:

String path = String.Concat(IOHelper.AssemblyPath, @"'certificate.pfx");
X509Certificate2 cert = new X509Certificate2(path, "password");
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
if(!store.Certificates.Contains(cert))
{
    store.Add(cert);
}

注册主机:

netsh http add sslcert ipport=0.0.0.0:9000 certhash=<cert hash> appid=<app id>

c# X509Certificate2添加证书标记为可导出的

X509Certificate2标记为可导出实际上非常简单。添加第三个参数(X509KeyStorageFlags.Exportable),表示该证书是可导出的。

var cert = new X509Certificate2(path, "password", X509KeyStorageFlags.Exportable);

对于Madeillei的回答,您可以传递以下标志:

var cert = new X509Certificate2(path, "password", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable| X509KeyStorageFlags.MachineKeySet);

如果您将证书存储在CurrentUser存储库而不是LocalMachine存储库中,请执行以下操作:

var cert = new X509Certificate2(path, "password", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable| X509KeyStorageFlags.UserKeySet);

Key set标志表示以下内容:

    //
    // Summary:
    //     Private keys are stored in the current user store rather than the local computer
    //     store. This occurs even if the certificate specifies that the keys should go
    //     in the local computer store.
    UserKeySet = 1,
    //
    // Summary:
    //     Private keys are stored in the local computer store rather than the current user
    //     store.
    MachineKeySet = 2,

私钥需要与证书的其余部分位于相同的位置才能起作用。