gpt4 book ai didi

c# - 如何从特定绑定(bind) C# 获取证书

转载 作者:太空狗 更新时间:2023-10-29 22:30:25 25 4
gpt4 key购买 nike

我在互联网上找到了从 iis 获取所有证书的唯一方法,我按照以下方式 (c#) 进行操作:

var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
store.Certificates;

现在我尝试获取特定绑定(bind)的特定证书,我该如何在 C# 中执行此操作?

最佳答案

证书本身绝对不包含有关 IIS 中使用的绑定(bind)的信息,因此您无法从计算机检索证书并期望它们具有与 IIS 相关的任何信息。您需要从 IIS 查询该信息。

为此,您需要添加对可在 %windir%\system32\inetsrv\Microsoft.Web.Administration.dll 下找到的库的引用(注意:IIS 7 或更新版本必须安装)。在此之后,您可以执行以下操作来获取证书:

ServerManager manager = new ServerManager();
Site yourSite = manager.Sites["yourSiteName"];

X509Certificate2 yourCertificate = null;

foreach (Binding binding in yourSite.Bindings)
{
if (binding.Protocol == "https" && binding.EndPoint.ToString() == "127.0.0.1" /*your binding IP*/)
{
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
yourCertificate = store.Certificates.Find(X509FindType.FindByThumbprint, ToHex(binding.CertificateHash), true)[0];
break;
}
}

public static string ToHex(byte[] ba)
{
var hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
{
hex.AppendFormat("{0:x2}", b);
}

return hex.ToString();
}

关于c# - 如何从特定绑定(bind) C# 获取证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34547159/

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