6

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.

Kassem
  • 8,116
  • 17
  • 75
  • 116
  • 1
    See this question: http://stackoverflow.com/questions/2768670/does-httpwebrequest-automatically-take-care-of-certificate-validation . The answer to it shows how to perform custom validation and in the validation handler you can pick the certificate and extract its private key. – Eugene Mayevski 'Callback Mar 16 '13 at 13:39
  • @EugeneMayevski'EldoSCorp thanks for the link, but this is not exactly what I need. What I really need is being able to query facebook.com to get its certificate information. The public key is all I need actually. – Kassem Mar 16 '13 at 21:43

1 Answers1

7

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;
Ravi
  • 86
  • 1
  • Yup, that's exactly what I needed. I would appreciate it if you would comment your code snippet to highlight what the important bits are doing. Thank you so much anyway :) – Kassem Mar 18 '13 at 22:05