简体   繁体   中英

Loading certificate from X509Store using SHA256 hash

I'm using the following code to retrieve a certificate from the X509Store :

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);            
X509Certificate2Collection certificateCollection = store.Certificates.Find(X509FindType.FindByThumbprint, configuration.CertificateThumbprint, false);
if (certificateCollection == null || certificateCollection.Count == 0)
{
    throw new Exception("Certificate not installed in the store");
}

certificate = certificateCollection[0];

This works perfectly when I use the cert's SHA1 hash. It does not work when I try to load it by its SHA256 hash. Here's the cert as seein in MMC.

MMC中显示的证书

As I understand and according to what I've read here , the thumbprint and thumbprint algorithm are not stored on the certificate. The thumbprint is a hash of the entire certificate. Is this just a limitation within X509Store in that it only knows about the SHA1 hashes of its certificates or am I misunderstanding things here?

A bit of info: thumbprint is not a part of certificate, however it can be a certificate store context property. When certificate is installed in the certificate store, a CryptHashCertificate function is used to calculate SHA1 hash and stores it in the context property. So when you enumerate certificates in the store, their thumbprint is not calculated each time, the system may use already saved hash in the context property.

If there is no saved thumprint, or certificate context is outside of certificate store, then thumbprint is calculated on a fly by using CryptHashCertificate function. In certificate context, the function defaults to SHA1 and there is no way to change this behavior.

So you are correct that X509Store will always use SHA1 for thumbprint. It is not actual X509Store limitation, it is limitation of the underlying CryptoAPI library.

ps certutil may show SHA256 thumbprint, but it is certutil-specific feature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM