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

时间:2014-06-23 12:57:36

标签: c# ssl localhost x509certificate netsh

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

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

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

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

  

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

  

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

我找到了一些解决方案,说明您需要在导入时将证书标记为“可导出” 但我无法在代码中找到我的表现。

Website 1Website 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>

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

进一步了解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);

键设置标志指示以下内容:

    //
    // 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,

私钥必须与证书的其余部分位于同一位置,才能起作用。