1. 程式人生 > >使用X509Certificate2類操作證書檔案

使用X509Certificate2類操作證書檔案

public class CertHelper
    {

        string pfxPath = @"E:\開發輔助專案\cert\taisuyuanqing.pfx";
        string cerPath = @"E:\開發輔助專案\cert\taisuyuanqing.cer";

        #region *從檔案中讀取公鑰和私鑰

        #region +從檔案中讀取公鑰
        /// <summary>
        /// 從檔案中讀取公鑰
        /// </summary>
        ///
<returns></returns> public string GetPlulicKey() { try { X509Certificate2 x509 = new X509Certificate2(cerPath); return x509.PublicKey.Key.ToXmlString(false); } catch (Exception ex) {
return string.Empty; } } #endregion #region +從私鑰檔案中讀取私鑰 /// <summary> /// 從私鑰檔案中讀取私鑰 /// </summary> public void GetPrivateKey() { try { X509Certificate2 x509 = new X509Certificate2(pfxPath, "
123456", X509KeyStorageFlags.Exportable); var publicKey = x509.PublicKey.Key.ToXmlString(false); var privateKey = x509.PrivateKey.ToXmlString(true); var str = "逍遙帝君 15210253 xiaoyaodijun"; var result = RSAHelper.RSAEncrypt(publicKey, str); var content = RSAHelper.RSADecrypt(privateKey, result); } catch (Exception) { throw; } } #endregion #endregion #region + 從證書庫中獲取證書 /// <summary> /// 從證書庫中獲取證書 /// </summary> /// <param name="subjectName">證書名字</param> /// <returns></returns> public X509Certificate2 GetCertificateFromStore(string subjectName) { try { subjectName = "CN=" + subjectName; X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates; foreach (X509Certificate2 x509 in storecollection) { if (x509.Subject == subjectName) { return x509; } } store.Close(); store = null; storecollection = null; return null; } catch (Exception) { throw; } } #endregion #region *匯出證書檔案 #region +從證書庫中匯出私鑰檔案 /// <summary> /// 從WINDOWS證書儲存區的個人MY區找到主題為subjectName的證書, /// 並匯出為pfx檔案,同時為其指定一個密碼 /// 並將證書從個人區刪除(如果isDelFromstor為true) /// </summary> /// <param name="subjectName">證書主題,不包含CN=</param> /// <param name="pfxFileName">pfx檔名</param> /// <param name="password">pfx檔案密碼</param> /// <param name="isDelFromStore">是否從儲存區刪除</param> /// <returns></returns> public static bool ExportToPfxFile(string subjectName, string pfxFileName, string password, bool isDelFromStore) { subjectName = "CN=" + subjectName; X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates; foreach (X509Certificate2 x509 in storecollection) { if (x509.Subject == subjectName) { byte[] pfxByte = x509.Export(X509ContentType.Pfx, password); using (FileStream fileStream = new FileStream(pfxFileName, FileMode.Create)) { // Write the data to the file, byte by byte. for (int i = 0; i < pfxByte.Length; i++) fileStream.WriteByte(pfxByte[i]); // Set the stream position to the beginning of the file. fileStream.Seek(0, SeekOrigin.Begin); // Read and verify the data. for (int i = 0; i < fileStream.Length; i++) { if (pfxByte[i] != fileStream.ReadByte()) { fileStream.Close(); return false; } } fileStream.Close(); } if (isDelFromStore == true) store.Remove(x509); } } store.Close(); store = null; storecollection = null; return true; } #endregion #region + 從證書庫中匯出公鑰檔案 /// <summary> /// 從證書庫中匯出公鑰檔案 /// </summary> /// <param name="subjectName">證書名字</param> /// <param name="cerFileName">存放公鑰的檔案路徑</param> public void ExportToCerFile(string subjectName, string cerFileName) { try { subjectName = "CN=" + subjectName; X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates; foreach (X509Certificate2 x509 in storecollection) { if (x509.Subject != subjectName) continue; byte[] cerByte = x509.Export(X509ContentType.Cert); using (FileStream fileStream = new FileStream(cerFileName, FileMode.Create)) { // Write the data to the file, byte by byte. for (int i = 0; i < cerByte.Length; i++) fileStream.WriteByte(cerByte[i]); // Set the stream position to the beginning of the file. fileStream.Seek(0, SeekOrigin.Begin); // Read and verify the data. for (int i = 0; i < fileStream.Length; i++) { if (cerByte[i] != fileStream.ReadByte()) { fileStream.Close(); } } fileStream.Close(); } } } catch (Exception) { throw; } } #endregion #endregion #region + 從證書庫中獲取私鑰和公鑰 /// <summary> /// 從證書庫中獲取私鑰和公鑰 /// </summary> /// <param name="subjectName"></param> /// <param name="password"></param> /// <returns></returns> public string GetPrivateKeyFromStore(string subjectName, string password) { try { subjectName = "CN=" + subjectName; //CurrentUser=當前使用者 LocalMachine=本地計算機 X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates; foreach (X509Certificate2 x509 in storecollection) { if (x509.Subject != subjectName) continue; x509.Export(X509ContentType.Pfx, password); var privateKey = x509.PrivateKey.ToXmlString(true); var publicKey = x509.PublicKey.Key.ToXmlString(false); var str = "逍遙帝君 15210253 xiaoyaodijun"; var result = RSAHelper.RSAEncrypt(publicKey, str); var content = RSAHelper.RSADecrypt(privateKey, result); } return ""; } catch (Exception) { return ""; } } #endregion