Created
July 10, 2019 13:37
-
-
Save DalSoft/00590fa5c136905e0e5b5a9f3f55cec8 to your computer and use it in GitHub Desktop.
ValidateCertificateChain for custom Root CA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static bool ValidateCertificateChain(X509Certificate certificate) | |
{ | |
var chain = new X509Chain(); | |
var root = new X509Certificate2("ca.cer"); // Root CA of Self signed cert | |
var cert = new X509Certificate2(certificate); | |
chain.Reset(); // Not sure is this is needed | |
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreRootRevocationUnknown; | |
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online; // Check with our own CA if the cert has been revoked | |
chain.ChainPolicy.ExtraStore.Add(root); // Self signed Root CA | |
if (!chain.Build(cert)) | |
{ // checking if the certificates chain failed, let check if it's just an UntrustedRoot error, that is expected for Self signed Root CA | |
foreach (var chainStatus in chain.ChainStatus) // what is the status of each cert in the chain | |
{ | |
if (chainStatus.Status == X509ChainStatusFlags.NoError) | |
continue; //Awesome this cert good was carry on. | |
if (chainStatus.Status == X509ChainStatusFlags.UntrustedRoot) | |
{ | |
// Got you - Untrusted Root error can happen with a self signed cert because the Root CA isn't installed in the OS's CA Root Certificate Store | |
// Now just check it's the root CA we expect | |
var providedRoot = chain.ChainElements[chain.ChainElements.Count - 1]; // Root CA is last or something is broken | |
return root.Thumbprint == providedRoot.Certificate.Thumbprint; // Is expected Root CA | |
} | |
} | |
return false; // Any other cert error other than X509ChainStatusFlags.UntrustedRoot | |
} | |
return true; // No errors at all | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment