Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private static X509Certificate2 GetCertificate(string thumbprint)
- {
- return CertificateUtil.FindCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, thumbprint, isValid: false);
- }
- public static class CertificateUtil
- {
- public static X509Certificate2 FindCertificate(StoreLocation location, StoreName name, X509FindType findType, object value, bool isValid = true)
- {
- var store = new X509Store(name, location);
- try
- {
- store.Open(OpenFlags.ReadOnly);
- if (findType == X509FindType.FindByThumbprint)
- {
- var thumbprint = value.ToString().Trim().Replace(" ", "");
- foreach (var cert in store.Certificates)
- {
- if (string.Equals(cert.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase) || string.Equals(cert.Thumbprint, thumbprint, StringComparison.InvariantCultureIgnoreCase))
- {
- return cert;
- }
- }
- }
- if (findType == X509FindType.FindBySerialNumber)
- {
- var serial = value.ToString().Trim().Replace(" ", "");
- foreach (var cert in store.Certificates)
- {
- if (string.Equals(cert.SerialNumber, serial, StringComparison.OrdinalIgnoreCase) || string.Equals(cert.SerialNumber, serial, StringComparison.InvariantCultureIgnoreCase))
- {
- return cert;
- }
- }
- }
- var certs = store.Certificates.Find(findType, value, isValid);
- if (certs.Count != 1)
- {
- throw new InvalidOperationException(String.Format("Certificate not found: {0}", value));
- }
- return certs[0];
- }
- finally
- {
- store.Close();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement