Created
October 3, 2019 12:22
-
-
Save YARG/d1f0aebf97390770c02464832abb1473 to your computer and use it in GitHub Desktop.
Get a certificate by thumbprint from the X509 certificate store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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