Verifying a Certificate from C#

Khalid Abuhakmeh & Maarten Balliauw

How do I verify a certificate in C#? If you've ever typed return true; inside a certificate validation callback to get past a local TLS error, you've turned off the thing that made the connection trustworthy in the first place.

This post covers how to verify a certificate correctly in C#: loading it with X509Certificate2, building and validating the chain with X509Chain, checking revocation, validating against a custom trust store, and confirming the certificate matches the host you intended to connect to.

Loading a Certificate with X509Certificate2

X509Certificate2 represents an X.509 certificate in .NET. You can load one from a file, a byte array, or an existing connection.

Csharp

using System.Security.Cryptography.X509Certificates;

// From a .cer or .pem file (public certificate, no private key)
using X509Certificate2 certificate = X509CertificateLoader.LoadCertificateFromFile("server.cer");

// From a PFX/PKCS12 file with a password (includes the private key)
using X509Certificate2 certificateWithKey = X509CertificateLoader.LoadPkcs12FromFile(
    "server.pfx",
    password: "your-password");

X509CertificateLoader is the loader added in .NET 9. Use it instead of the X509Certificate2 constructors (new X509Certificate2("server.pfx", password)), which are marked obsolete for several overloads starting in .NET 9 and have a history of format confusion: the constructors tried to guess whether you handed them a certificate or a PKCS12 bundle, and that guesswork was a source of bugs and, in a few cases, security issues. X509CertificateLoader makes the format explicit: call LoadCertificateFromFile for a bare certificate, LoadPkcs12FromFile for a certificate plus private key, and so on.

On .NET 8 or earlier, or .NET Framework, you don't have X509CertificateLoader. Use the constructor, but be explicit about the content type:

Csharp

#if NET8_0
using X509Certificate2 legacyLoad = new("server.pfx", "your-password", X509KeyStorageFlags.EphemeralKeySet);
#endif

Loading a certificate tells you nothing about whether you should trust it. That's the chain's job.

How Do You Build and Validate a Certificate Chain in C#? (X509Chain)

A certificate is a signed claim. Trusting it means validating that an unbroken chain of signatures leads from that certificate up to a root certificate your system already trusts. X509Chain builds and evaluates that chain.

Csharp

using System.Security.Cryptography.X509Certificates;

bool isValid = VerifyCertificateChain(certificate);

static bool VerifyCertificateChain(X509Certificate2 certificate)
{
    using var chain = new X509Chain();

    chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
    chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
    chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
    chain.ChainPolicy.UrlRetrievalTimeout = TimeSpan.FromSeconds(10);

    bool chainBuilt = chain.Build(certificate);

    if (!chainBuilt)
    {
        foreach (X509ChainStatus status in chain.ChainStatus)
        {
            Console.WriteLine($"Chain error: {status.Status} - {status.StatusInformation}");
        }
    }

    return chainBuilt;
}

chain.Build walks the certificate's issuer chain, checks each signature, confirms validity periods, and (depending on RevocationMode) checks revocation status. It returns false the moment anything fails, and chain.ChainStatus tells you exactly what went wrong: expired certificate, untrusted root, revoked certificate, or a broken chain link. Log that information. Swallowing the exception is how "it works on my machine" certificate bugs survive into production.

How Do You Check Revocation (CRL and OCSP)?

A certificate can be technically valid and still compromised if its private key has leaked. That's what revocation checking catches. X509Chain.ChainPolicy.RevocationMode controls how .NET checks:

Csharp

// Check Certificate Revocation Lists and OCSP; fail if the revocation status can't be determined.
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;

// Use only cached revocation data. Faster, but can miss a certificate revoked after the last fetch.
chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;

// Skip revocation checking entirely.
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

.NET picks OCSP or CRL automatically based on what the certificate's issuer publishes; you don't choose the protocol directly. Use Online for anything security-sensitive, like mTLS client authentication or validating a signing certificate. NoCheck exists for constrained environments (no outbound network access to a CA, air-gapped systems) and should come with a documented reason, and should not be a shortcut to silence an error.

Revocation checks require network access to the issuer's OCSP responder or CRL distribution point. If that network call fails, Online mode treats the certificate as untrusted by default. Set a reasonable UrlRetrievalTimeout so a slow or unreachable CA doesn't hang your request indefinitely.

Validating Against a Custom Trust Store

Public websites validate against the operating system's trusted root store. Internal services, mTLS between your own services, and private CAs need a different trust anchor: a specific root or intermediate certificate you control, not whatever happens to be in the OS store.

Csharp

using System.Security.Cryptography.X509Certificates;

bool isValid = VerifyAgainstCustomRoot(certificate, trustedRoot);

static bool VerifyAgainstCustomRoot(X509Certificate2 certificate, X509Certificate2 trustedRoot)
{
    using var chain = new X509Chain();

    // Don't trust the OS root store. Trust only what we add explicitly.
    chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
    chain.ChainPolicy.CustomTrustStore.Add(trustedRoot);
    chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; // a private CA often has no CRL/OCSP endpoint

    return chain.Build(certificate);
}

X509ChainTrustMode.CustomRootTrust tells the chain engine to ignore the machine's trusted roots and validate only against certificates you added to CustomTrustStore. This is the pattern you want for mTLS between services where both sides present certificates issued by your own internal CA, and it's how you avoid accidentally trusting a certificate just because it happens to chain to a public root that has nothing to do with your system.

Does the Certificate Cover the Expected Host?

A valid chain proves the certificate is signed by a CA you trust. It does not prove the certificate belongs to the server you meant to connect to. That check is separate, and it's the one attackers rely on you skipping.

Check the Subject Alternative Name (SAN), not the subject's common name. Common name fallback was deprecated years ago and most clients, including .NET's TLS stack, no longer honor it. Don't use certificate.GetNameInfo(X509NameType.DnsName, false) for this: it doesn't reliably enumerate every SAN DNS entry and can silently fall back to the common name, which defeats the point of the check. Instead, read the SAN extension directly with X509SubjectAlternativeNameExtension.EnumerateDnsNames(), added in .NET 9 specifically so you don't have to hand-parse the extension:

Csharp

using System.Security.Cryptography.X509Certificates;

bool matchesHost = CertificateMatchesHost(certificate, "api.example.com");

static bool CertificateMatchesHost(X509Certificate2 certificate, string expectedHost)
{
    X509SubjectAlternativeNameExtension? sanExtension = certificate.Extensions
        .OfType<X509SubjectAlternativeNameExtension>()
        .FirstOrDefault();

    if (sanExtension is null)
    {
        return false;
    }

    foreach (string dnsName in sanExtension.EnumerateDnsNames())
    {
        if (string.Equals(dnsName, expectedHost, StringComparison.OrdinalIgnoreCase))
        {
            return true;
        }

        // Handle a single leading wildcard label, e.g. "*.example.com".
        if (dnsName.StartsWith("*.", StringComparison.Ordinal))
        {
            string wildcardParent = dnsName[2..];
            int firstDot = expectedHost.IndexOf('.');

            if (firstDot > 0)
            {
                string expectedParent = expectedHost[(firstDot + 1)..];

                if (string.Equals(wildcardParent, expectedParent, StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
            }
        }
    }

    return false;
}

This is a supplementary check, on top of chain validation, for cases like thumbprint pinning or an internal trust store where you also want to confirm the SAN. For normal HTTPS calls through SslStream or HttpClient, don't hand-roll this at all: the TLS stack already validates the hostname against the SAN as part of the handshake, and a custom check should only ever add restrictions, never replace that validation.

Pin a certificate by thumbprint when you expect one exact certificate, not just one trusted CA. This is common for client certificate authentication, where you issued the certificate yourself and know its exact fingerprint.

Csharp

bool thumbprintMatches = string.Equals(
    certificate.Thumbprint,
    expectedThumbprint,
    StringComparison.OrdinalIgnoreCase);

Thumbprint pinning is strict: it breaks the moment the certificate rotates. Use it for short-lived, tightly controlled certificates (client certs you issue, signing certs you manage), not for public TLS endpoints whose certificates renew outside your control.

ServerCertificateCustomValidationCallback (and Why You Must Not Just Return True)

HttpClientHandler.ServerCertificateCustomValidationCallback lets you add custom validation logic to an HttpClient's TLS handshake. It also lets you turn off certificate validation in one line, which is why it shows up in almost every "how do I fix this SSL error" answer on Stack Overflow.

Csharp

// DO NOT DO THIS
var handler = new HttpClientHandler
{
    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
};

That line tells .NET to accept any certificate from any server, valid or not, expired or not, self-signed or not. It turns TLS into unauthenticated, unencrypted-in-practice transport dressed up to look secure; this is bad. It ships to production more often than anyone wants to admit, usually as a quick fix for a local development certificate error that frustrates developers under pressure to ship software.

Here's the version that verifies the certificate instead of skipping verification:

Csharp

using System.Net.Http;
using System.Security.Cryptography.X509Certificates;

var handler = new HttpClientHandler
{
    ServerCertificateCustomValidationCallback = (message, cert, chain, sslErrors) =>
    {
        // Reject outright if .NET's built-in TLS validation already found a problem.
        if (sslErrors != System.Net.Security.SslPolicyErrors.None)
        {
            return false;
        }

        if (cert is null || chain is null)
        {
            return false;
        }

        // Add extra checks on top of the default validation, such as pinning
        // to a specific issuer or thumbprint for a sensitive internal service.
        return chain.ChainElements[^1].Certificate.Thumbprint == expectedRootThumbprint;
    }
};

using var client = new HttpClient(handler);

The callback exists for cases like adding thumbprint pinning or trusting a private CA, not for bypassing validation. If sslErrors is non-None, the built-in validation already found a real problem (expired, untrusted, name mismatch). Returning true anyway throws that finding away.

If your real problem is a local development certificate that isn't trusted, trust that certificate in your development environment (dotnet dev-certs https --trust for Kestrel's dev certificate, or import your internal CA into the trust store) instead of turning off validation in code that will eventually reach production.

Common Pitfalls Working With X509 Certificates in C#

  • Disposing certificates too early. X509Certificate2 implements IDisposable. Disposing it while it's still referenced by an HttpClientHandler or a running TLS session causes intermittent, hard-to-reproduce failures.
  • Trusting NotBefore / NotAfter alone. A certificate inside its validity window can still be revoked. Validity dates and revocation are separate checks; X509Chain checks both only when you configure RevocationMode correctly.
  • Comparing the subject common name instead of SAN. Modern TLS clients, including .NET's, ignore the common name for host matching. Relying on it in your own validation code gives you a false sense of a check that isn't actually enforced elsewhere.
  • Catching and discarding chain build failures. chain.Build returning false without inspecting chain.ChainStatus hides the actual reason (expired, revoked, untrusted root) and makes debugging a production TLS failure far harder than it needs to be.
  • Mixing up X509ContentType . Loading a PFX as if it were a DER certificate, or vice versa, throws a cryptic exception. X509CertificateLoader's explicit methods make this mismatch fail immediately and clearly instead of guessing.

Next Step

Start with X509Chain and RevocationMode.Online for any certificate you don't fully control. Add SAN and thumbprint checks only where chain validation alone isn't enough, like thumbprint pinning or an internal trust store. If you're touching ServerCertificateCustomValidationCallback, add checks; don't remove them.

Call to Action

If you're implementing mTLS or client certificate authentication, Duende IdentityServer handles certificate-bound tokens and client authentication for you, with the chain and revocation checks covered in this post applied consistently. Read the token security documentation for mTLS and DPoP configuration, and check the signing credential guidance if you're managing your own signing certificates.

Frequently Asked Questions

How do I verify a certificate in C#? Load it with X509CertificateLoader (or X509Certificate2 on older runtimes), then build a chain with X509Chain and check chain.Build(certificate). A true result with RevocationMode set to Online means the certificate chains to a trusted root, falls within its validity window, and isn't revoked. Also check that the certificate's SAN matches the host you intended to connect to.

How do I validate a certificate chain in C#? Create an X509Chain, set ChainPolicy.RevocationMode and any custom trust store you need, then call chain.Build(certificate); if it returns false, iterate chain.ChainStatus to see exactly which check failed (expired, untrusted root, revoked, or a broken link in the chain).

Why shouldn't I just return true from ServerCertificateCustomValidationCallback? Returning true unconditionally turns off certificate validation for that HttpClient, accepting any certificate, including expired, self-signed, or attacker-controlled ones. It defeats the purpose of TLS. Fix the underlying trust problem (import a dev certificate, add a custom trust store) instead.

What's the difference between X509Certificate2 and X509CertificateLoader? X509Certificate2 is the certificate type itself. X509CertificateLoader, added in .NET 9, is the preferred way to construct one from a file or byte array, because its methods are explicit about content type (LoadCertificateFromFile vs LoadPkcs12FromFile) instead of guessing, which several of the older X509Certificate2 constructors did.

Does X509Chain check revocation by default? No. The default RevocationMode is Online, but you should set it explicitly in your code. Hence, the behavior is clear and intentional, especially since some code paths and older defaults use NoCheck.

About the authors

Khalid Abuhakmeh Senior Customer Success Engineer

I'm a Senior Customer Success Engineer, where I help teams succeed with Duende IdentityServer. I've worked with .NET for over a decade, including ASP.NET Core, C#, and web development.

Maarten Balliauw Head of Customer Success

Loves building web and cloud apps. He focuses on .NET web technologies, C#, Microsoft Azure, and application performance. Creator of SpeakerTravel and formerly founded MyGet.

Related Articles