by Andreas

Accepting invalid SSL certificates programmatically (C#)

This might initially sound like a very bad idea, because it undermines one of the fundamental reasons for using SSL in the first place. But it’s suprising how often I come across situations where this comes in very handy, especially during development and testing when valid certificates aren’t present and you still want to test your code over a secured encrypted channel.

Add a static method for handling the validation logic (or to skip it entirely):

// callback for validating SSL certificate during handshake
private static bool CustomCertificateValidatior(object sender,
    X509Certificate certificate, X509Chain chain,
    SslPolicyErrors policyErrors)
{
    // anything goes!
    return true;

    // PS: you could put your own validation logic here, 
    // through accessing the certificate properties:
    // var publicKey = certificate.GetPublicKey();

}

You then just add a RemoteCertificateValidationCallback before you make the SOAP / HTTP request, and your custom validator will take care of the validation.

 

// method where request is made

// ensure SSL certificate validation uses custom method
ServicePointManager.ServerCertificateValidationCallback +=
       new RemoteCertificateValidationCallback(CustomCertificateValidatior);

// initiate a SOAP or HTTP request like normal
// and your custom method will be used for validation

// ..
Tags: ,