Skip to content

Instantly share code, notes, and snippets.

@vkocjancic
Last active February 2, 2026 22:36
Show Gist options
  • Select an option

  • Save vkocjancic/eafd96dee3b6097d22db67483793cda9 to your computer and use it in GitHub Desktop.

Select an option

Save vkocjancic/eafd96dee3b6097d22db67483793cda9 to your computer and use it in GitHub Desktop.
Simple certificate pinning example
using System;
using System.Net;
using System.Net.Security;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
public class Program
{
private static string g_ssPublicKey =
"3082010A0282010100C4FFFFE6F3945AD2BF27D5DD674166130D5D2021CEFF0" +
"4B06AD48F5F56A6245C590433121C8F08B7A565FBF38F1102917CB7434AFE91" +
"18E2CB904BA723D57182B680B872CF05578B234F65DB1A39CD77DEBD07D0939" +
"A0C440A9AE9245D0CAB59480DC3864D744BA6404B0D6DA9BAEE0E85CE0816D9" +
"D7F43468D2E073CBA2EA10114323B0053F8AE29F86AD846B71FE4D7924494FB" +
"0D80E3C78875085163B53121EBEBCF1356A4386DFF9E2CB93D0BD9CA3A39D4A" +
"AC7BB34F2FF4AC70D59DBCD92254D48DE0BC3CCB4A8B4822D64CCE46F1E539B" +
"116A00420825AD2AFF128F7A761D79186FB747761E47187BD527B1398F603DC" +
"F7DCABD3535C28B7FB2C3068230203010001";
public static async Task Main()
{
using var handler = new HttpClientHandler();
handler.CheckCertificateRevocationList = true;
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback = (message, certificate, chain, sslPolicyErrors) =>
{
if (null == certificate)
{
Console.WriteLine("ERROR: No server certificate found");
return false;
}
if (sslPolicyErrors != SslPolicyErrors.None)
{
Console.WriteLine($"SSL Policy Errors: {sslPolicyErrors}");
return false;
}
string sPublicKeyToVerify = certificate.GetPublicKeyString();
if (g_ssPublicKey != sPublicKeyToVerify)
{
Console.WriteLine("ERROR: Certificate public key mismatch");
return false;
}
// here you can do other certificate checks (e.g. check dates valid from and to, issuer etc.)
Console.WriteLine("Certificate public key matches");
return true;
};
using var httpClient = new HttpClient(handler);
string sResponse = await httpClient.GetStringAsync("https://certwatch.dev");
Console.WriteLine(sResponse);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment