從自簽名證書匯出pfx和cer證書

FrankYou發表於2015-09-16

完整程式碼:

  1 public sealed class DataCertificate
  2     {
  3         #region 生成證書
  4         /// <summary>   
  5         /// 根據指定的證書名和makecert全路徑生成證書(包含公鑰和私鑰,並儲存在MY儲存區)   
  6         /// </summary>   
  7         /// <param name="subjectName"></param>   
  8         /// <param name="makecertPath"></param>   
  9         /// <returns></returns>   
 10         public static bool CreateCertWithPrivateKey(string subjectName, string makecertPath)
 11         {
 12             subjectName = "CN=" + subjectName;
 13             string param = " -pe -ss my -n \"" + subjectName + "\" ";
 14             try
 15             {
 16                 Process p = Process.Start(makecertPath, param);
 17                 p.WaitForExit();
 18                 p.Close();
 19             }
 20             catch (Exception e)
 21             {
 22                 return false;
 23             }
 24             return true;
 25         }
 26         #endregion
 27 
 28         #region 檔案匯入匯出
 29         /// <summary>   
 30         /// 從WINDOWS證書儲存區的個人MY區找到主題為subjectName的證書,   
 31         /// 並匯出為pfx檔案,同時為其指定一個密碼   
 32         /// 並將證書從個人區刪除(如果isDelFromstor為true)   
 33         /// </summary>   
 34         /// <param name="subjectName">證書主題,不包含CN=</param>   
 35         /// <param name="pfxFileName">pfx檔名</param>   
 36         /// <param name="password">pfx檔案密碼</param>   
 37         /// <param name="isDelFromStore">是否從儲存區刪除</param>   
 38         /// <returns></returns>   
 39         public static bool ExportToPfxFile(string subjectName, string pfxFileName,
 40             string password, bool isDelFromStore)
 41         {
 42             subjectName = "CN=" + subjectName;
 43             X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
 44             store.Open(OpenFlags.ReadWrite);
 45             X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates;
 46             foreach (X509Certificate2 x509 in storecollection)
 47             {
 48                 if (x509.Subject == subjectName)
 49                 {
 50                     Debug.Print(string.Format("certificate name: {0}", x509.Subject));
 51 
 52                     byte[] pfxByte = x509.Export(X509ContentType.Pfx, password);
 53                     using (FileStream fileStream = new FileStream(pfxFileName, FileMode.Create))
 54                     {
 55                         // Write the data to the file, byte by byte.   
 56                         for (int i = 0; i < pfxByte.Length; i++)
 57                             fileStream.WriteByte(pfxByte[i]);
 58                         // Set the stream position to the beginning of the file.   
 59                         fileStream.Seek(0, SeekOrigin.Begin);
 60                         // Read and verify the data.   
 61                         for (int i = 0; i < fileStream.Length; i++)
 62                         {
 63                             if (pfxByte[i] != fileStream.ReadByte())
 64                             {
 65                                 fileStream.Close();
 66                                 return false;
 67                             }
 68                         }
 69                         fileStream.Close();
 70                     }
 71                     if (isDelFromStore == true)
 72                         store.Remove(x509);
 73                 }
 74             }
 75             store.Close();
 76             return true;
 77         }
 78         /// <summary>   
 79         /// 從WINDOWS證書儲存區的個人MY區找到主題為subjectName的證書,   
 80         /// 並匯出為CER檔案(即,只含公鑰的)   
 81         /// </summary>   
 82         /// <param name="subjectName"></param>   
 83         /// <param name="cerFileName"></param>   
 84         /// <returns></returns>   
 85         public static bool ExportToCerFile(string subjectName, string cerFileName)
 86         {
 87             subjectName = "CN=" + subjectName;
 88             X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
 89             store.Open(OpenFlags.ReadWrite);
 90             X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates;
 91             foreach (X509Certificate2 x509 in storecollection)
 92             {
 93                 if (x509.Subject == subjectName)
 94                 {
 95                     Debug.Print(string.Format("certificate name: {0}", x509.Subject));
 96                     //byte[] pfxByte = x509.Export(X509ContentType.Pfx, password);   
 97                     byte[] cerByte = x509.Export(X509ContentType.Cert);
 98                     using (FileStream fileStream = new FileStream(cerFileName, FileMode.Create))
 99                     {
100                         // Write the data to the file, byte by byte.   
101                         for (int i = 0; i < cerByte.Length; i++)
102                             fileStream.WriteByte(cerByte[i]);
103                         // Set the stream position to the beginning of the file.   
104                         fileStream.Seek(0, SeekOrigin.Begin);
105                         // Read and verify the data.   
106                         for (int i = 0; i < fileStream.Length; i++)
107                         {
108                             if (cerByte[i] != fileStream.ReadByte())
109                             {
110                                 fileStream.Close();
111                                 return false;
112                             }
113                         }
114                         fileStream.Close();
115                     }
116                 }
117             }
118             store.Close();
119             store = null;
120             storecollection = null;
121             return true;
122         }
123         #endregion
124 
125         #region 從證書中獲取資訊
126         /// <summary>   
127         /// 根據私鑰證書得到證書實體,得到實體後可以根據其公鑰和私鑰進行加解密   
128         /// 加解密函式使用DEncrypt的RSACryption類   
129         /// </summary>   
130         /// <param name="pfxFileName"></param>   
131         /// <param name="password"></param>   
132         /// <returns></returns>   
133         public static X509Certificate2 GetCertificateFromPfxFile(string pfxFileName,
134             string password)
135         {
136             try
137             {
138                 return new X509Certificate2(pfxFileName, password, X509KeyStorageFlags.Exportable);
139             }
140             catch (Exception e)
141             {
142                 return null;
143             }
144         }
145         /// <summary>   
146         /// 到儲存區獲取證書   
147         /// </summary>   
148         /// <param name="subjectName"></param>   
149         /// <returns></returns>   
150         public static X509Certificate2 GetCertificateFromStore(string subjectName)
151         {
152             subjectName = "CN=" + subjectName;
153             X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
154             store.Open(OpenFlags.ReadWrite);
155             X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates;
156             foreach (X509Certificate2 x509 in storecollection)
157             {
158                 if (x509.Subject == subjectName)
159                 {
160                     return x509;
161                 }
162             }
163             store.Close();
164             store = null;
165             storecollection = null;
166             return null;
167         }
168         /// <summary>   
169         /// 根據公鑰證書,返回證書實體   
170         /// </summary>   
171         /// <param name="cerPath"></param>   
172         public static X509Certificate2 GetCertFromCerFile(string cerPath)
173         {
174             try
175             {
176                 return new X509Certificate2(cerPath);
177             }
178             catch (Exception e)
179             {
180                 return null;
181             }
182         }
183         #endregion
184     }

 

相關文章