1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Security.Cryptography.X509Certificates; 5 using System.Text; 6 using System.Threading.Tasks; 7 using System.Web; 8 9 10 namespace makecertdemo 11 { 12 public class MakecertHelper 13 { 14 /// <summary> 15 /// 根據私鑰證書得到證書實體,得到實體后可以根據其公鑰和私鑰進行加解密 16 /// 加解密函數使用DEncrypt的RSACryption類 17 /// </summary> 18 /// <param name="pfxFileName"></param> 19 /// <param name="password"></param> 20 /// <returns></returns> 21 public static X509Certificate2 GetCertificateFromPfxFile(string pfxFileName, 22 string password) 23 { 24 try 25 { 26 return new X509Certificate2(pfxFileName, password, X509KeyStorageFlags.Exportable); 27 } 28 catch (Exception e) 29 { 30 return null; 31 } 32 } 33 34 /// <summary> 35 /// 從證書存儲區讀取證書 36 /// </summary> 37 /// <returns></returns> 38 public static X509Certificate2 GetCertificateFromHost() 39 { 40 X509Store store = new X509Store("MY", StoreLocation.CurrentUser); 41 store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); 42 //Put certificates from the store into a collection so user can select one. 43 X509Certificate2Collection fcollection = (X509Certificate2Collection)store.Certificates; 44 //X509Certificate2Collection collection = X509Certificate2UI.SelectFromCollection(fcollection, "Select an X509 Certificate", "Choose a certificate to examine.", X509SelectionFlag.MultiSelection);//彈出框,可以選擇需要的證書 45 X509Certificate2Collection findResult = fcollection.Find(X509FindType.FindBySerialNumber, "BFA9E49C5E44EA914BA64288CA6B8348", false);//有多個重載,可以用不同的方法查詢 46 47 return findResult[0]; 48 } 49 } 50 }