gpt4 book ai didi

c# - 动态添加具有指向动态生成的自签名证书的 HTTPS 绑定(bind)的网站

转载 作者:行者123 更新时间:2023-11-30 22:03:08 25 4
gpt4 key购买 nike

我目前正在尝试使用 IIS7+ 提供的 Microsoft.Web.Administration 库动态添加新网站。这将是安装过程的一部分,其中需要添加自签名证书并将其绑定(bind)到该网站的 HTTPS 绑定(bind)。

我的研究让我看到了 StackOverflow 上的这篇帖子,它使用了 BouncyCaSTLe API:Generate self signed certificate on the fly .我试图通过对代码进行轻微改动来复制 IIS 管理工具提供的用于创建此类证书的功能。我已经将这两种方法中的签名算法从 SHA256WithRSA 修改为 SHA1WithRSA。我还使用 Dns.GetHostEntry("127.0.0.1").HostNameSubjectNameIssuerName 作为本地计算机的名称传递。我还设置了 X509Certificate2 对象的 FriendlyName 属性。最后的修改涉及将 addCertToStore 方法的 sl 参数作为 StoreLocation.LocalMachine 传递。

以下是动态创建网站并添加 HTTPS 绑定(bind)的代码片段,将 cert.GetCertHash() 数据作为参数传递给 Site.Bindings.Add( ...) 方法,它接受绑定(bind)信息证书哈希证书存储名称(参见 MSDN documentation ) :

using (ServerManager iisManager = new ServerManager())
{
Site testSite = iisManager.Sites.Add(siteName, targetDir, sitePortNumber);
testSite.Bindings.Add("*:" + sitePortNumber + ":", certificateHash, "MY");
iisManager.CommitChanges();
}

问题是,当尝试在 IIS 中提交更改时,我得到以下 COMException:

A specified logon session does not exist. It may already have been terminated. (Exception from HRESULT: 0x80070520)

检查 IIS 中发生的情况,似乎证书存在但未正确映射:

Server Certificates

在上面链接的图片中,最上面的证书是动态添加的证书,即我的帖子中提到的证书。最后一个是通过 IIS 管理工具创建的示例自签名证书。

HTTPS Binding Details

上面链接的图像显示 HTTPS 绑定(bind)和新创建的 SSL 证书之间的映射失败。

本地计算机下的个人证书 -> 个人:

此图像包含个人证书列表,这些证书位于证书管理器的本地计算机 部分下。上面的是动态生成的,而下面的是使用 IIS 管理工具创建的。

Certificate Details

以上是使用 IIS 管理工具创建的自签名证书(左侧)和动态生成的证书(右侧)的证书详细信息。

两者之间一些最显着的区别是:

  1. 动态生成的缺少 key 使用增强型 key 使用详细信息。
  2. 证书状态和表明有问题的图标。

所以问题是涉及创建自签名证书的代码有什么问题导致映射到新 IIS 网站失败?

谢谢

最佳答案

将 SSL 证书从当前用户转移到本地计算机,它起作用了。

这是我添加证书的代码。我还注意到 X509KeyStorageFlags.MachineKeySet 是唯一没有产生错误的标志。

string certPath = "c:/test2/certName.p12";
string certPass = "TestPassword";

// Create a collection object and populate it using the PFX file
X509Certificate2Collection collection = new X509Certificate2Collection();
collection.Import(certPath, certPass, X509KeyStorageFlags.MachineKeySet);

foreach (X509Certificate2 cert in collection)
{

if(cert.Subject.Equals("CN=TestServer, O=Test"))
{
X509Store store1 = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
store1.Open(OpenFlags.ReadWrite);
store1.Add(cert);
store1.Close();
}


if (cert.Subject.Equals("CN=TestClient, OU=Applications, O=Test"))
{
X509Store store1 = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store1.Open(OpenFlags.ReadWrite);
store1.Add(cert);
store1.Close();
}
}

这是我创建绑定(bind)的代码

ServerManager serverManager = new ServerManager();
var site = serverManager.Sites["Default Web Site"];
site.Bindings.Add("*:443:TestClient", certificate[0].GetCertHash(), "MY");
// site.Bindings.Add("*:443:TestClient", "https");
serverManager.CommitChanges();

关于c# - 动态添加具有指向动态生成的自签名证书的 HTTPS 绑定(bind)的网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26281977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com