Skip to content

Instantly share code, notes, and snippets.

@jarrettmeyer
Last active October 19, 2017 14:29
Show Gist options
  • Save jarrettmeyer/bf0851889221b8fbe4d84827414cc6ba to your computer and use it in GitHub Desktop.
Save jarrettmeyer/bf0851889221b8fbe4d84827414cc6ba to your computer and use it in GitHub Desktop.
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
namespace ServerCertificateValidationDemo
{
public class Program
{
private static string _defaultUrl = @"https://www.google.com";
public static void Main(string[] args)
{
// Set the URL value. If no argument is given, use the default URL.
string url = _defaultUrl;
if (args != null && args.Length > 0)
{
url = args[0];
}
Console.WriteLine("Using URL: {0}{1}", url, Environment.NewLine);
// Create a new web request and set up a validation callback.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ServerCertificateValidationCallback += OnCertificateValidation;
try
{
// Get the response. If the certificate fails to validate, a
// WebException will be thrown.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Response status: {0} ({1})", response.StatusCode, response.StatusDescription);
}
catch (WebException e)
{
Console.WriteLine("Exception: {0}", e.Message);
}
Console.WriteLine("Press ENTER to close.");
Console.ReadLine();
}
public static bool OnCertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
Console.WriteLine("Subject: {0}", certificate.Subject);
Console.WriteLine("Effective date: {0}", certificate.GetEffectiveDateString());
Console.WriteLine("Expiration date: {0}", certificate.GetExpirationDateString());
Console.WriteLine("Issuer: {0}", certificate.Issuer);
Console.WriteLine("Key algorithm: {0}", certificate.GetKeyAlgorithm());
Console.WriteLine("Certificate hash: {0}", certificate.GetCertHashString());
Console.WriteLine("Public key: {0}", certificate.GetPublicKeyString());
Console.WriteLine("Serial number: {0}", certificate.GetSerialNumberString());
Console.WriteLine("SSL policy errors: {0}", errors);
return (errors == SslPolicyErrors.None);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment