Mentalis.org Security Library documentation

Certificate Services

Validating certificates

Validating a certificate is a two step process. First you have to build the certificate chain associated with the given certificate and after that you can verify the certificate chain. This example explains how to implement these two steps.

using System;
using Org.Mentalis.Security.Certificates;

/// <summary>
/// Validates a given certificate.
/// </summary>
/// <param name="cert">The certificate to validate.</param>
/// <param name="serverName">The domain name of the server that sent
/// the certificate.</param>
/// <returns>true if the certificate is valid, false otherwise.</returns>
/// <exception cref="ArgumentNullException">cert is a null reference (Nothing
/// in Visual Basic).</exception>
/// <exception cref="CertificateException">An error occurs while validating
/// the certificate chain.</exception>
public bool IsCertificateValid(Certificate cert, string serverName) {
    // build the certificate chain of the specified certificate
    CertificateChain chain = new CertificateChain(cert);
    // try to validate the certificate chain
    CertificateStatus status = chain.VerifyChain(serverName, AuthType.Server);
    // return true if the chain is valid, false otherwise
    return status == CertificateStatus.ValidCertificate;
}