using System.Security.Cryptography.X509Certificates; // Load a certificate from a file X509Certificate2 cert = new X509Certificate2("my_cert.pfx", "my_password"); // Get the certificate hash as a string string hash = cert.GetCertHashString(); // Output the hash value Console.WriteLine("Certificate hash: " + hash);
using System.Security.Cryptography.X509Certificates; // Get the current user's personal certificate store X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); // Find a certificate with a specific subject name string subjectName = "CN=my_cert"; X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, false); if (certs.Count > 0) { // Get the certificate hash as a string X509Certificate2 cert = certs[0]; string hash = cert.GetCertHashString(); // Output the hash value Console.WriteLine("Certificate hash: " + hash); } store.Close();In this example, we open the current user's personal certificate store and search for a certificate with a specific subject name using the Find method of the X509Certificate2Collection class. If we find a matching certificate, we call the GetCertHashString method on it to get its SHA-1 hash value as a string, which we output to the console. The package library for the System.Security.Cryptography.X509Certificates namespace is part of the .NET Framework.