How to validate server
certificate
Security isveryimportant insoftware development. We have differentwaystosecure ourapplication.
Like ApplicationSecurity,Network Security, Database Securityetc.
Many timeswe use SSL Certificate tosecure our application.Foruse SSLCertificate we install certificate
intoserverand configure webservertoserve ourwebpagesoversecure channel (https). Afterusing
secure channel all communicationtoserveruse secure channel byencryptdata.It’smore secure our
communicationtoserverbysecure network.
Thinkaboutthe scenariowhenyou have aclientapplication whichsendingdatato serverbutserver
certificate have some problem orcertificate notavailable onserver. Now pointisthatwe needfirst
validate servercertificate andif everything fine thenstartsendandreceive datafrom server. Forthat
we need validate servercertificate.
ServerCertificateValidationCallback Property isuse togetsor sets the callbackto validate aserver
certificate. Whenwe doingcertificate validationthe senderparameterpassedtothe
RemoteCertificateValidationCallback.
RemoteCertificateValidationCallback Parameters
sender
Type:System.Object
An objectthatcontains state informationforthisvalidation.
certificate
Type:System.Security.Cryptography.X509Certificates.X509Certificate
The certificate usedtoauthenticate the remote party.
chain
Type:System.Security.Cryptography.X509Certificates.X509Chain
The chain of certificate authoritiesassociatedwiththe remote certificate.
sslPolicyErrors
Type:System.Net.Security.SslPolicyErrors
One or more errors associatedwiththe remote certificate.
ReturnValue
Type:System.Boolean
A Boolean value thatdetermineswhetherthe specifiedcertificate isacceptedforauthentication.
Steps for validate server certificate
1. Get PublicKeyfrom ServerCertificate
2. Create RemoteCertificateValidationCallbackDelegate
3. Match PublicKeyandServerCertificatePublicKey
1. GetPublicKey from ServerCertificate–We are gettingdatafromfollowing URL
https://private-634da8-test11074.apiary-mock.com/SubscriberByWeek
It’sreturningJSON data
[{"RegistedDay":"Tuesday","SubscriberRegisted":4},
{"RegistedDay":"Tuesday","SubscriberRegisted":8},
{"RegistedDay":"Wednesday","SubscriberRegisted":10},
{"RegistedDay":"Friday","SubscriberRegisted":12},
{"RegistedDay":"Saturday","SubscriberRegisted":15},
{"RegistedDay":"Saturday","SubscriberRegisted":20}
]
For gettingPublickey accessURL intochrome browser,youwill see screenlike this.
Clickon lockicons it will show youpermissionscreen
Go into“Connection” tab andthen “Certificate Information” button
It will showyouservercertificateanditsinformationandthenclickon “Details” tab
Select“All”fromdrop downand chose PublicKey.It will show you Publickey
CopythisPublicKeyandremove space between
Now we have Publickey
3082010a0282010100953b6be2bde72aae46a2c5a1af890ac29764444d27f69ec4745b674784bb3148550038d
42f456851a2eac1c9a7ac8aebd8431c74875d4a2a61314047c3da3879bd4b57e932bc33ed3ae342fe500e1851
5e3e7a0fe682aae70ba04e7c718a49e1570e15b6bb6133a50813f9660d6f820487388c020944cf6ff8222d721
3f06456f41985f4815895656ccac76764f2ec704cbce841d1d07e296d3123d4817e572eec8f317bef234677c7
f474b56f95b986de5a0b898b54c2bb80d3605079cbb3c48fbe35671c4b467bed69cc6ed192a6b3d9bf916c4c8
979fc9716fcb148c1c40ce4beabd4d128beca1759b76a78575b19d4572a9b1caef289ebd20ed85567460d0203
010001
2. Create RemoteCertificateValidationCallbackDelegate - Create a
RemoteCertificateValidationCallbackdelegate like this.Whenwe doingcertificate validationthe
senderparameterpassedtothe RemoteCertificateValidationCallback.
// Set remote certificate callBack validation delegate
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
3. Match Public Keyand ServerCertificate PublicKey – In Callback we have sender,certificate,
chain,and sslPolicyErrors.Firstwe needtocheckcertificate andanyerrorsincertificate.If yes
thenreturnfalse.
Otherwise we needtocall GetPublicKeyString()methodtogetPublicKeyof certificate.And
thenmatch of both PublicKeyfirstone whichwe have andsecondone we gotfrom certificate.
// This method will be invoked by the RemoteCertificateValidationDelegate.
public static bool ValidateServerCertificate(object sender, X509Certificate
certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
// stop communicate with unauthenticated servers.
if (certificate == null || chain == null)
return false;
// stop communicate with unauthenticated servers.
if (sslPolicyErrors != SslPolicyErrors.None)
return false;
// match certificate public key and allow communicate with authenticated
servers.
String publicekey = certificate.GetPublicKeyString();
if (publicekey.Equals(_PUBLICKEY.ToUpper()))
return true;
// stop communicate with unauthenticated servers.
return false;
}
If both PublicKeywill notmatchthenmethodwill be returnfalse andyouwill got SSL/TLS
exception.
Example
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace ServerCertificateValidate
{
class ValidateCertificate
{
// public key of certificate
private static String _PUBLICKEY =
"3082010a0282010100953b6be2bde72aae46a2c5a1af890ac29764444d27f69ec4745b674784bb3148550038
d42f456851a2eac1c9a7ac8aebd8431c74875d4a2a61314047c3da3879bd4b57e932bc33ed3ae342fe500e185
15e3e7a0fe682aae70ba04e7c718a49e1570e15b6bb6133a50813f9660d6f820487388c020944cf6ff8222d72
13f06456f41985f4815895656ccac76764f2ec704cbce841d1d07e296d3123d4817e572eec8f317bef234677c
7f474b56f95b986de5a0b898b54c2bb80d3605079cbb3c48fbe35671c4b467bed69cc6ed192a6b3d9bf916c4c
8979fc9716fcb148c1c40ce4beabd4d128beca1759b76a78575b19d4572a9b1caef289ebd20ed85567460d020
3010001";
public static void Main(string[] args)
{
// Set remote certificate callBack validation delegate
ServicePointManager.ServerCertificateValidationCallback =
ValidateServerCertificate;
// Create request
WebRequest request = WebRequest.Create("https://private-634da8-
test11074.apiary-mock.com/SubscriberByWeek");
request.Timeout = 10000 ;
//Get response
WebResponse response = request.GetResponse();
// Get the stream associated with the response.
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
// This method will be invoked by the RemoteCertificateValidationDelegate.
public static bool ValidateServerCertificate(object sender, X509Certificate
certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
// stop communicate with unauthenticated servers.
if (certificate == null || chain == null)
return false;
// stop communicate with unauthenticated servers.
if (sslPolicyErrors != SslPolicyErrors.None)
return false;
// match certificate public key and allow communicate with authenticated
servers.
String publicekey = certificate.GetPublicKeyString();
if (publicekey.Equals(_PUBLICKEY.ToUpper()))
return true;
// stop communicate with unauthenticated servers.
return false;
}
}
}
Output
Thanks
www.codeandyou.com
http://www.codeandyou.com/2015/11/how-to-
validate-server-certificate.html
Keywords - How to validate server certificate
, validate server certificate, server certificate validation

How to validate server certificate

  • 1.
    How to validateserver certificate
  • 2.
    Security isveryimportant insoftwaredevelopment. We have differentwaystosecure ourapplication. Like ApplicationSecurity,Network Security, Database Securityetc. Many timeswe use SSL Certificate tosecure our application.Foruse SSLCertificate we install certificate intoserverand configure webservertoserve ourwebpagesoversecure channel (https). Afterusing secure channel all communicationtoserveruse secure channel byencryptdata.It’smore secure our communicationtoserverbysecure network. Thinkaboutthe scenariowhenyou have aclientapplication whichsendingdatato serverbutserver certificate have some problem orcertificate notavailable onserver. Now pointisthatwe needfirst validate servercertificate andif everything fine thenstartsendandreceive datafrom server. Forthat we need validate servercertificate. ServerCertificateValidationCallback Property isuse togetsor sets the callbackto validate aserver certificate. Whenwe doingcertificate validationthe senderparameterpassedtothe RemoteCertificateValidationCallback. RemoteCertificateValidationCallback Parameters sender Type:System.Object An objectthatcontains state informationforthisvalidation. certificate Type:System.Security.Cryptography.X509Certificates.X509Certificate The certificate usedtoauthenticate the remote party. chain Type:System.Security.Cryptography.X509Certificates.X509Chain The chain of certificate authoritiesassociatedwiththe remote certificate. sslPolicyErrors Type:System.Net.Security.SslPolicyErrors One or more errors associatedwiththe remote certificate. ReturnValue Type:System.Boolean A Boolean value thatdetermineswhetherthe specifiedcertificate isacceptedforauthentication.
  • 3.
    Steps for validateserver certificate 1. Get PublicKeyfrom ServerCertificate 2. Create RemoteCertificateValidationCallbackDelegate 3. Match PublicKeyandServerCertificatePublicKey 1. GetPublicKey from ServerCertificate–We are gettingdatafromfollowing URL https://private-634da8-test11074.apiary-mock.com/SubscriberByWeek It’sreturningJSON data [{"RegistedDay":"Tuesday","SubscriberRegisted":4}, {"RegistedDay":"Tuesday","SubscriberRegisted":8}, {"RegistedDay":"Wednesday","SubscriberRegisted":10}, {"RegistedDay":"Friday","SubscriberRegisted":12}, {"RegistedDay":"Saturday","SubscriberRegisted":15}, {"RegistedDay":"Saturday","SubscriberRegisted":20} ] For gettingPublickey accessURL intochrome browser,youwill see screenlike this.
  • 4.
    Clickon lockicons itwill show youpermissionscreen Go into“Connection” tab andthen “Certificate Information” button
  • 5.
    It will showyouservercertificateanditsinformationandthenclickon“Details” tab Select“All”fromdrop downand chose PublicKey.It will show you Publickey
  • 6.
    CopythisPublicKeyandremove space between Nowwe have Publickey 3082010a0282010100953b6be2bde72aae46a2c5a1af890ac29764444d27f69ec4745b674784bb3148550038d 42f456851a2eac1c9a7ac8aebd8431c74875d4a2a61314047c3da3879bd4b57e932bc33ed3ae342fe500e1851 5e3e7a0fe682aae70ba04e7c718a49e1570e15b6bb6133a50813f9660d6f820487388c020944cf6ff8222d721 3f06456f41985f4815895656ccac76764f2ec704cbce841d1d07e296d3123d4817e572eec8f317bef234677c7 f474b56f95b986de5a0b898b54c2bb80d3605079cbb3c48fbe35671c4b467bed69cc6ed192a6b3d9bf916c4c8 979fc9716fcb148c1c40ce4beabd4d128beca1759b76a78575b19d4572a9b1caef289ebd20ed85567460d0203 010001 2. Create RemoteCertificateValidationCallbackDelegate - Create a RemoteCertificateValidationCallbackdelegate like this.Whenwe doingcertificate validationthe senderparameterpassedtothe RemoteCertificateValidationCallback. // Set remote certificate callBack validation delegate ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate; 3. Match Public Keyand ServerCertificate PublicKey – In Callback we have sender,certificate, chain,and sslPolicyErrors.Firstwe needtocheckcertificate andanyerrorsincertificate.If yes thenreturnfalse. Otherwise we needtocall GetPublicKeyString()methodtogetPublicKeyof certificate.And thenmatch of both PublicKeyfirstone whichwe have andsecondone we gotfrom certificate. // This method will be invoked by the RemoteCertificateValidationDelegate. public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { // stop communicate with unauthenticated servers. if (certificate == null || chain == null) return false; // stop communicate with unauthenticated servers. if (sslPolicyErrors != SslPolicyErrors.None) return false; // match certificate public key and allow communicate with authenticated servers. String publicekey = certificate.GetPublicKeyString(); if (publicekey.Equals(_PUBLICKEY.ToUpper())) return true; // stop communicate with unauthenticated servers.
  • 7.
    return false; } If bothPublicKeywill notmatchthenmethodwill be returnfalse andyouwill got SSL/TLS exception.
  • 8.
    Example using System; using System.IO; usingSystem.Net; using System.Text; using System.Net.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace ServerCertificateValidate { class ValidateCertificate { // public key of certificate private static String _PUBLICKEY = "3082010a0282010100953b6be2bde72aae46a2c5a1af890ac29764444d27f69ec4745b674784bb3148550038 d42f456851a2eac1c9a7ac8aebd8431c74875d4a2a61314047c3da3879bd4b57e932bc33ed3ae342fe500e185 15e3e7a0fe682aae70ba04e7c718a49e1570e15b6bb6133a50813f9660d6f820487388c020944cf6ff8222d72 13f06456f41985f4815895656ccac76764f2ec704cbce841d1d07e296d3123d4817e572eec8f317bef234677c 7f474b56f95b986de5a0b898b54c2bb80d3605079cbb3c48fbe35671c4b467bed69cc6ed192a6b3d9bf916c4c 8979fc9716fcb148c1c40ce4beabd4d128beca1759b76a78575b19d4572a9b1caef289ebd20ed85567460d020 3010001"; public static void Main(string[] args) { // Set remote certificate callBack validation delegate ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate; // Create request WebRequest request = WebRequest.Create("https://private-634da8- test11074.apiary-mock.com/SubscriberByWeek"); request.Timeout = 10000 ; //Get response WebResponse response = request.GetResponse(); // Get the stream associated with the response. using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { Console.WriteLine(reader.ReadToEnd()); } } } // This method will be invoked by the RemoteCertificateValidationDelegate. public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { // stop communicate with unauthenticated servers. if (certificate == null || chain == null) return false;
  • 9.
    // stop communicatewith unauthenticated servers. if (sslPolicyErrors != SslPolicyErrors.None) return false; // match certificate public key and allow communicate with authenticated servers. String publicekey = certificate.GetPublicKeyString(); if (publicekey.Equals(_PUBLICKEY.ToUpper())) return true; // stop communicate with unauthenticated servers. return false; } } } Output
  • 10.
    Thanks www.codeandyou.com http://www.codeandyou.com/2015/11/how-to- validate-server-certificate.html Keywords - Howto validate server certificate , validate server certificate, server certificate validation