Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the public key of a website's SSL certificate

I'm not really sure about whether the following is doable or not because I'm in no way an expert on the subject (security, certificates...etc).

Anyway, what I want to do is get the Public Key of a website's SSL certificate using C# code. Like is there a way to query that information from the site using an HTTP request or something?

In order for you guys to understand why I really want to do so, I'll briefly explain the scenario I want to make happen. Basically I have a bunch of websites that use OAuth 2.0 to achieve a state of trust among each other. So let's say Site1 issued a request to Site2 and sent it a token which is supposedly from a trusted Authorization Server. Site2 should be able to verify the authenticity of this token.

I hope that was clear enough.

like image 296
Kassem Avatar asked Mar 16 '13 12:03

Kassem


1 Answers

I use the following block of code for a similar purpose. I hope it helps!!!

        Uri u = new Uri(url);
        ServicePoint sp = ServicePointManager.FindServicePoint(u);

        string groupName = Guid.NewGuid().ToString();
        HttpWebRequest req = HttpWebRequest.Create(u) as HttpWebRequest;
        req.ConnectionGroupName = groupName;

        using (WebResponse resp = req.GetResponse())
        {

        }
        sp.CloseConnectionGroup(groupName);
        byte[] key = sp.Certificate.GetPublicKey();

        return key;
like image 56
Ravi Avatar answered Oct 23 '22 04:10

Ravi