X509Certificate2.GetCertHash Method

public byte[] GetCertHash();

Retrieves the hash of the certificate. The hash is calculated using the SHA-1 algorithm.

Parameters

This method has no parameters.

Return Value
System.Byte[]
A byte array containing the hash of the certificate. The hash is computed using the SHA-1 algorithm.
Remarks

The GetCertHash method returns the raw byte array of the certificate's hash. If you need a string representation of the hash, use the GetCertHashString method.

The hash algorithm used is SHA-1, which is a common cryptographic hash function. However, SHA-1 is considered cryptographically weak and should be replaced with stronger algorithms like SHA-256 or SHA-3 where possible.

Requirements

Namespace:System.Net.Security

Assembly:System.dll (in System.dll)

Examples

The following code example demonstrates how to get the certificate hash.

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

public class CertificateHashExample
{
    public static void Main(string[] args)
    {
        try
        {
            // Assume 'myCertificate' is an initialized X509Certificate2 object
            // For demonstration, let's try to get the current user's personal certificate
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);

            X509Certificate2Collection certificates = store.Certificates;
            X509Certificate2 myCertificate = null;

            if (certificates.Count > 0)
            {
                myCertificate = certificates[0]; // Get the first certificate
                Console.WriteLine($"Certificate Subject: {myCertificate.Subject}");

                // Get the certificate hash
                byte[] certHash = myCertificate.GetCertHash();

                Console.WriteLine("Certificate Hash (byte array):");
                foreach (byte b in certHash)
                {
                    Console.Write("{0:x2}", b);
                }
                Console.WriteLine();

                // Get the string representation of the hash
                string certHashString = myCertificate.GetCertHashString();
                Console.WriteLine($"Certificate Hash (string): {certHashString}");
            }
            else
            {
                Console.WriteLine("No certificates found in the personal store.");
            }

            store.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}
See Also
Note: As of TLS 1.2 and newer, SHA-1 is considered insufficient for cryptographic security. Consider using SHA-256 or a stronger hashing algorithm for new applications.