C#建立數位憑證並匯出為pfx,並使用pfx進行非對稱加解密

來源:互聯網
上載者:User

標籤:oid   download   att   btn   adb   cert   pre   write   pts   

本文來源程式下載:http://download.csdn.net/source/2444494

 

我的項目當中,考慮到安全性,需要為每個用戶端分發一個數位憑證,同時使用數位憑證中的公私密金鑰來進行資料的加解密。為了完成這個安全模組,特寫了如下一個DEMO程式,該DEMO程式包含的功能有:

1:調用.NET2.0的MAKECERT建立含有私密金鑰的數位憑證,並儲存到個人認證區;

2:將該認證匯出為pfx檔案,並為其指定一個用來開啟pfx檔案的password;

3:讀取pfx檔案,匯出pfx中公開金鑰和私密金鑰;

4:用pfx認證中的公開金鑰進行資料的加密,用私密金鑰進行資料的解密;

系統介面:

 

代碼如下:

/// <summary>          /// 將認證從憑證存放區區匯出,並儲存為pfx檔案,同時為pfx檔案指定開啟的密碼          /// 本函數同時也示範如何用公開金鑰進行加密,私密金鑰進行解密          /// </summary>          /// <param name="sender"></param>          /// <param name="e"></param>          private void btn_toPfxFile_Click(object sender, EventArgs e)          {              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 == "CN=luminji")                  {                      Debug.Print(string.Format("certificate name: {0}", x509.Subject));                      byte[] pfxByte = x509.Export(X509ContentType.Pfx, "123");                      using (FileStream  fileStream = new FileStream("luminji.pfx", 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())                              {                                  Debug.Print("Error writing data.");                                  return;                              }                          }                          fileStream.Close();                          Debug.Print("The data was written to {0} " +                              "and verified.", fileStream.Name);                      }                      string myname = "my name is luminji! and i love huzhonghua!";                      string enStr = this.RSAEncrypt(x509.PublicKey.Key.ToXmlString(false), myname);                      MessageBox.Show("密文是:" + enStr);                      string deStr = this.RSADecrypt(x509.PrivateKey.ToXmlString(true), enStr);                      MessageBox.Show("明文是:" + deStr);                  }              }              store.Close();              store = null;              storecollection = null;          }          /// <summary>          /// 建立還有私密金鑰的認證          /// </summary>          /// <param name="sender"></param>          /// <param name="e"></param>          private void btn_createPfx_Click(object sender, EventArgs e)          {              string MakeCert = "C://Program Files//Microsoft Visual Studio 8//SDK//v2.0//Bin//makecert.exe";              string x509Name = "CN=luminji";              string param = " -pe -ss my -n /"" + x509Name + "/" " ;              Process p = Process.Start(MakeCert, param);              p.WaitForExit();              p.Close();              MessageBox.Show("over");          }          /// <summary>          /// 從pfx檔案讀取認證資訊          /// </summary>          /// <param name="sender"></param>          /// <param name="e"></param>          private void btn_readFromPfxFile(object sender, EventArgs e)          {              X509Certificate2 pc = new X509Certificate2("luminji.pfx", "123");              MessageBox.Show("name:" + pc.SubjectName.Name);              MessageBox.Show("public:" + pc.PublicKey.ToString());              MessageBox.Show("private:" + pc.PrivateKey.ToString());              pc = null;          }          /// <summary>          /// RSA解密          /// </summary>          /// <param name="xmlPrivateKey"></param>          /// <param name="m_strDecryptString"></param>          /// <returns></returns>          public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString)          {              RSACryptoServiceProvider provider = new RSACryptoServiceProvider();              provider.FromXmlString(xmlPrivateKey);              byte[] rgb = Convert.FromBase64String(m_strDecryptString);              byte[] bytes = provider.Decrypt(rgb, false);              return new UnicodeEncoding().GetString(bytes);          }          /// <summary>          /// RSA加密          /// </summary>          /// <param name="xmlPublicKey"></param>          /// <param name="m_strEncryptString"></param>          /// <returns></returns>          public string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)          {              RSACryptoServiceProvider provider = new RSACryptoServiceProvider();              provider.FromXmlString(xmlPublicKey);              byte[] bytes = new UnicodeEncoding().GetBytes(m_strEncryptString);              return Convert.ToBase64String(provider.Encrypt(bytes, false));          }  

  上文是一個樣本程式,一個完整的認證工具類如下:

public sealed class DataCertificate      {          #region 產生認證          /// <summary>          /// 根據指定的認證名和makecert全路徑產生認證(包含公開金鑰和私密金鑰,並儲存在MY儲存區)          /// </summary>          /// <param name="subjectName"></param>          /// <param name="makecertPath"></param>          /// <returns></returns>          public static bool CreateCertWithPrivateKey(string subjectName, string makecertPath)          {              subjectName = "CN=" + subjectName;              string param = " -pe -ss my -n /"" + subjectName + "/" ";              try              {                  Process p = Process.Start(makecertPath, param);                  p.WaitForExit();                  p.Close();              }              catch (Exception e)              {                  LogRecord.putErrorLog(e.ToString(), "DataCerficate.CreateCertWithPrivateKey");                  return false;              }              return true;          }          #endregion           #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)                  {                      Debug.Print(string.Format("certificate name: {0}", x509.Subject));                        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())                              {                                  LogRecord.putErrorLog("Export pfx error while verify the pfx file!", "ExportToPfxFile");                                  fileStream.Close();                                  return false;                              }                          }                          fileStream.Close();                      }                      if( isDelFromStore == true)                          store.Remove(x509);                  }              }              store.Close();              store = null;              storecollection = null;              return true;          }          /// <summary>          /// 從WINDOWS憑證存放區區的個人MY區找到主題為subjectName的認證,          /// 並匯出為CER檔案(即,只含公開金鑰的)          /// </summary>          /// <param name="subjectName"></param>          /// <param name="cerFileName"></param>          /// <returns></returns>          public static bool ExportToCerFile(string subjectName, string cerFileName)          {              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)                  {                      Debug.Print(string.Format("certificate name: {0}", x509.Subject));                      //byte[] pfxByte = x509.Export(X509ContentType.Pfx, password);                      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())                              {                                  LogRecord.putErrorLog("Export CER error while verify the CERT file!", "ExportToCERFile");                                  fileStream.Close();                                  return false;                              }                          }                          fileStream.Close();                      }                  }              }              store.Close();              store = null;              storecollection = null;              return true;          }          #endregion           #region 從認證中擷取資訊          /// <summary>          /// 根據私密金鑰認證得到認證實體,得到實體後可以根據其公開金鑰和私密金鑰進行加解密          /// 加解密函數使用DEncrypt的RSACryption類          /// </summary>          /// <param name="pfxFileName"></param>          /// <param name="password"></param>          /// <returns></returns>          public static X509Certificate2 GetCertificateFromPfxFile(string pfxFileName,              string password)          {              try              {                  return new X509Certificate2(pfxFileName, password, X509KeyStorageFlags.Exportable);              }              catch (Exception e)              {                  LogRecord.putErrorLog("get certificate from pfx" + pfxFileName + " error:" + e.ToString(),                      "GetCertificateFromPfxFile");                  return null;              }          }          /// <summary>          /// 到儲存區擷取認證          /// </summary>          /// <param name="subjectName"></param>          /// <returns></returns>          public static X509Certificate2 GetCertificateFromStore(string subjectName)          {              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;          }          /// <summary>          /// 根據密鑰憑證,返回認證實體          /// </summary>          /// <param name="cerPath"></param>          public static X509Certificate2 GetCertFromCerFile(string cerPath)          {              try              {                  return new X509Certificate2(cerPath);              }              catch (Exception e)              {                  LogRecord.putErrorLog(e.ToString(), "DataCertificate.LoadStudentPublicKey");                  return null;              }                      }          #endregion             }  

  

C#建立數位憑證並匯出為pfx,並使用pfx進行非對稱加解密

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.