Skip to content

Instantly share code, notes, and snippets.

@YARG
Created October 3, 2019 12:22
Show Gist options
  • Save YARG/d1f0aebf97390770c02464832abb1473 to your computer and use it in GitHub Desktop.
Save YARG/d1f0aebf97390770c02464832abb1473 to your computer and use it in GitHub Desktop.
Get a certificate by thumbprint from the X509 certificate store
static X509Certificate2 GetCertificate(string thumbPrint)
{
List<StoreLocation> locations = new List<StoreLocation>
{
StoreLocation.CurrentUser,
StoreLocation.LocalMachine
};
foreach (var location in locations)
{
X509Store store = new X509Store(StoreName.My, location);
try
{
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection certificates = store.Certificates.Find(
X509FindType.FindByThumbprint, thumbPrint, true);
if (certificates.Count >= 1)
{
return certificates[0];
}
}
finally
{
store.Close();
}
}
throw new ArgumentException($"A Certificate with Thumbprint '{thumbPrint}' could not be located.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment