byte[] certData = File.ReadAllBytes("certificate.cer"); // read certificate data from a file X509Certificate2 cert = new X509Certificate2(certData); // create X509Certificate2 object byte[] certHash = cert.GetCertHash(); // get the hash value of the certificate Console.WriteLine(BitConverter.ToString(certHash)); // print the hash value in hex format
string certThumbprint = "79F23D2C3B1E9352D4CA5BAFE765567D53A0F82F"; // thumbprint of the certificate X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); // create a certificate store store.Open(OpenFlags.ReadOnly); // open the store X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByThumbprint, certThumbprint, false); // find certificate by thumbprint if (certs.Count > 0) { X509Certificate2 cert = certs[0]; // get the first certificate found byte[] certHash = cert.GetCertHash(); // get the hash value of the certificate Console.WriteLine(BitConverter.ToString(certHash)); // print the hash value in hex format }In this example, we first specify the thumbprint of the certificate that we want to retrieve the hash value for. We then create an X509Store object and open it in read-only mode. Next, we use the Find method of the X509Certificate2Collection class to find the certificate based on its thumbprint. If the certificate is found, we retrieve it by specifying the first certificate in the collection and then retrieve the hash value using the GetCertHash method. Finally, we print the hash value in hex format using the BitConverter class. The System.Security.Cryptography.X509Certificates X509Certificate2 class belongs to the .NET Framework Class Library.