X509Certificate2.GetCertHashString Method

Represents a certificate and provides methods to access information about the certificate.

Syntax

public string GetCertHashString();

Remarks

The GetCertHashString method returns a string representation of the certificate's hash. The hash is calculated using the SHA1 algorithm.

This method is useful for comparing certificates or for displaying the certificate's hash in a human-readable format.

The hash string is typically represented as a sequence of hexadecimal characters.

Note: While SHA1 is commonly used, for stronger security, consider using certificates with SHA256 or higher hash algorithms when possible.

Example

The following example demonstrates how to retrieve and display the hash string of an X.509 certificate.

using System;
using System.Security.Cryptography.X509Certificates;

public class Example
{
    public static void Main()
    {
        // Load a certificate from the user's personal store.
        // Replace "My Certificate Name" with the actual subject name or thumbprint of your certificate.
        X509Certificate2 cert = null;
        X509Store store = new X509Store("My", OpenFlags.ReadOnly);

        try
        {
            store.Open(OpenFlags.ReadOnly);
            // You might want to iterate through certs to find a specific one
            // For simplicity, let's assume the first one found is sufficient for this example
            if (store.Certificates.Count > 0)
            {
                cert = store.Certificates[0];

                // Get the certificate hash string.
                string hashString = cert.GetCertHashString();

                Console.WriteLine("Certificate Hash String: " + hashString);
            }
            else
            {
                Console.WriteLine("No certificates found in the 'My' store.");
            }
        }
        finally
        {
            store.Close();
        }
    }
}

Exceptions

Type Condition
CryptographicException The certificate is invalid or could not be processed.

Requirements

Component Value
Namespace System.Net.Security
Assembly System.dll
.NET Framework Versions Available in .NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.6, 4.7, 4.8.