Advertisement
Guest User

CertificateUtil

a guest
May 24th, 2013
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.12 KB | None | 0 0
  1. private static X509Certificate2 GetCertificate(string thumbprint)
  2. {
  3.     return CertificateUtil.FindCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, thumbprint, isValid: false);
  4. }
  5.  
  6.  
  7.     public static class CertificateUtil
  8.     {
  9.         public static X509Certificate2 FindCertificate(StoreLocation location, StoreName name, X509FindType findType, object value, bool isValid = true)
  10.         {
  11.             var store = new X509Store(name, location);
  12.             try
  13.             {
  14.                 store.Open(OpenFlags.ReadOnly);
  15.  
  16.                 if (findType == X509FindType.FindByThumbprint)
  17.                 {
  18.                     var thumbprint = value.ToString().Trim().Replace(" ", "");
  19.  
  20.                     foreach (var cert in store.Certificates)
  21.                     {
  22.                         if (string.Equals(cert.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase) || string.Equals(cert.Thumbprint, thumbprint, StringComparison.InvariantCultureIgnoreCase))
  23.                         {
  24.                             return cert;
  25.                         }
  26.                     }
  27.                 }
  28.                 if (findType == X509FindType.FindBySerialNumber)
  29.                 {
  30.                     var serial = value.ToString().Trim().Replace(" ", "");
  31.  
  32.                     foreach (var cert in store.Certificates)
  33.                     {
  34.                         if (string.Equals(cert.SerialNumber, serial, StringComparison.OrdinalIgnoreCase) || string.Equals(cert.SerialNumber, serial, StringComparison.InvariantCultureIgnoreCase))
  35.                         {
  36.                             return cert;
  37.                         }
  38.                     }
  39.                 }
  40.  
  41.                 var certs = store.Certificates.Find(findType, value, isValid);
  42.  
  43.                 if (certs.Count != 1)
  44.                 {
  45.                     throw new InvalidOperationException(String.Format("Certificate not found: {0}", value));
  46.                 }
  47.  
  48.                 return certs[0];
  49.             }
  50.             finally
  51.             {
  52.                 store.Close();
  53.             }
  54.         }
  55.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement