The certificates themselves do not contain absolutely any information about the bindings used in IIS, so you cannot get certificates from the computer and expect them to have something related to IIS. You will need to request this information from IIS.
To do this, you need to add a link to the library, which is located in %windir%\system32\inetsrv\Microsoft.Web.Administration.dll (note: IIS 7 or later must be installed). After that, you can do something like the following to get the certificate:
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" ) { 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(); }
source share