簡體   English   中英

c#X509Certificate2添加證書如何標記為可導出

[英]c# X509Certificate2 add certificate how mark as exportable

我有一個.NET 4.0程序在端口9000上運行localhost。我想支持SSL並且要導入.pfx證書。

由於程序在多台計算機上運行,​​因此程序本身負責存儲證書並注冊其端口。

當程序導入和注冊時,一切正常。 但是,當我重新啟動計算機時,https連接不起作用..更多..

事件查看器給出以下錯誤:

嘗試訪問SSL服務器憑據私鑰時發生致命錯誤。 加密模塊返回的錯誤代碼是0x8009030D。 內部錯誤狀態為10001。

使用端點0.0.0.0:9000的SSL配置時發生錯誤。 錯誤狀態代碼包含在返回的數據中。

我找到了一些解決方案,說明您需要在導入時將證書標記為“可導出”,但我無法在代碼中找到我是如何做到這一點的。

網站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>

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);

鍵集標志表示以下內容:

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

私鑰需要與證書的其余部分位於同一位置才能工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM