Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get certificate from specific binding C#

Tags:

c#

iis

ssl

binding

I found on the internet only way to got all the certificates from the iis and i do it like the following (c#):

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

Now I try to get a specific certificate of specific binding, how can I do it in C#?

like image 913
Erez Avatar asked Dec 31 '15 13:12

Erez


People also ask

Can I generate certificate from private key?

You can use OpenSSL to create a private key and a certificate signing request (CSR) that can be transformed into a certificate after it is signed by a certificate authority (CA).

How do I get a certificate from ADCS?

Connect to the Active Directory Certificate Services website and click Request a certificate. Click advanced certificate request. Click Submit a certificate request by using a base-64-encoded CMC or PKCS #10 file, or submit a renewal request by using a base-64-encoded PKCS #7 file.

How do I check my certificate bindings?

Chrome has made it simple for any site visitor to get certificate information with just a few clicks: Click the padlock icon in the address bar for the website. Click on Certificate (Valid) in the pop-up. Check the Valid from dates to validate the SSL certificate is current.


1 Answers

The certificates themselves hold absolutely no information about the bindings used in IIS, so you cannot retrieve the certificates from the machine and expect them to have anything related to IIS. You would need to query that information from IIS.

To do this, you will need add a reference to the library that can be found under %windir%\system32\inetsrv\Microsoft.Web.Administration.dll (note: IIS 7 or newer must be installed). After this, 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" /*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();
}
like image 122
Camilo Terevinto Avatar answered Oct 03 '22 17:10

Camilo Terevinto