C # Create a digital certificate and export it as a PFX and use PFX for asymmetric plus decryption

Source: Internet
Author: User
Tags pfx file

This article source program download: http://download.csdn.net/source/2444494

In my project, with security in mind, you need to distribute a digital certificate for each client while using the public private key in the digital certificate to decrypt the data. In order to complete this security module, a close-up of the following demo program, the demo program contains the features are:

1: Call. NET2.0 MakeCert creates a digital certificate containing the private key and stores it in the personal certificate area;

2: Export the certificate as a PFX file and assign it a password to open the PFX file;

3: Read the PFX file, export the public key and private key in PFX;

4: Encrypt the data with the public key in the PFX certificate, and decrypt the data with the private key;

System interface:

The code is as follows:

<summary>////Export the certificate from the certificate store and store it as a PFX file, while specifying an open password for the PFX file///This function also demonstrates how to encrypt with the public key, the private key is decrypted//          </summary>//<param name= "sender" ></param>//<param name= "E" ></param> private void Btn_topfxfile_click (object sender, EventArgs e) {X509store store = new x509st              Ore (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]! = F                                   Ilestream.readbyte ()) {Debug.Print ("Error writing data.");                              Return                          }} filestream.close ();                      Debug.Print ("The data is 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 ("Ciphertext is:" + enstr); String destr = this. Rsadecrypt (X509.                      Privatekey.toxmlstring (True), enstr);                  MessageBox.Show ("Clear text is:" + destr); }} store.              Close ();              store = null;          Storecollection = null; }///<summary>//Create a certificate with private key///</summary>//<param name= "Sender" &G t;</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//ma              Kecert.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>///Read certificate information from PFX file///</summary>//<param name= "sender "></param>//<param name=" E "></param> private void Btn_readfrompfxfile (object sen              Der, 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 decryption//</summary>/<param name= "Xmlprivatekey "></param>//<param name=" m_strdecryptstring "></param>//<returns></re Turns> Public STring Rsadecrypt (String xmlprivatekey, String m_strdecryptstring) {RSACryptoServiceProvider provide              R = new RSACryptoServiceProvider (); Provider.              Fromxmlstring (Xmlprivatekey);              byte[] RGB = convert.frombase64string (m_strdecryptstring); byte[] bytes = provider.              Decrypt (RGB, false); return new UnicodeEncoding ().          GetString (bytes); }//<summary>//RSA encryption//</summary>//<param name= "Xmlpublickey" ></param>//<param name= "m_strencryptstring" ></param>//<returns></ret Urns> public string Rsaencrypt (string Xmlpublickey, String m_strencryptstring) {Rsacryp              Toserviceprovider Provider = new RSACryptoServiceProvider (); Provider.              Fromxmlstring (Xmlpublickey); byte[] bytes = new UnicodeEncoding ().              GetBytes (m_strencryptstring); Return Convert.tobasE64string (provider.          Encrypt (bytes, false));   }

The

Above is a sample program, and a complete certificate tool class is as follows:

public sealed class Datacertificate {#region Generate a certificate///<summary>//According to the specified certificate title and Makece          RT Full Path Generation certificate (contains public and private keys and saved in my store)///</summary>//<param name= "Subjectname" ></param> <param name= "Makecertpath" ></param>///<returns></returns> public STA TIC bool Createcertwithprivatekey (string subjectname, String makecertpath) {subjectname = "cn=" + S              Ubjectname;              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.crea                  Tecertwithprivatekey ");              return false;          } return true;         } #endregion  #region file Import/export///<summary>///from the personal my area of the Windows certificate store to find a certificate subject to Subjectname,///and export it as a PFX file, Specify a password for both//and remove the certificate from the personal area (if Isdelfromstor is true)///</summary>//<param name= "Subjec Tname "> Certificate subject, not including cn=</param>//<param name=" pfxfilename ">pfx file name </param>//<par          AM name= "password" >pfx file password </param>///<param Name= "Isdelfromstore" > whether to remove from storage </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 x5Storecollection) {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, and 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]! = F Ilestream.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>//from the personal my area of the Windows certificate store, find the certificate subject to Subjectname,///and export as a CER file (that is, only the public key is included) </summary>//<param name= "subjectname" ></param>//<param name= "Cerfilena Me "></param>///<returns></returns> public static bool Exporttocerfile (String subj  Ectname, 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, and 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]! = F Ilestream.readbyte ()) {Logrecord.puterrorlog ("Export CER er                                  Ror while verify the CERT file! "," exporttocerfile ");                                  Filestream.close ();                              return false;                      }} filestream.close (); }}} store.              Close ();              store = null;              Storecollection = null;          return true; #endregion #region Get information from the certificate//<summary>         The certificate entity is obtained according to the private key certificate, and the entity can be decrypted according to its public key and private key.//Add decryption function use Dencrypt rsacryption class//</summary>          <param name= "Pfxfilename" ></param>///<param name= "password" ></param>               <returns></returns> public static X509Certificate2 Getcertificatefrompfxfile (String pfxfilename, string password) {try {return new X509Certificate2 (PFX              FileName, password, x509keystorageflags.exportable); } catch (Exception e) {logrecord.puterrorlog ("Get certificate from PFX" + PFXF                  Ilename + "Error:" + e.tostring (), "getcertificatefrompfxfile");              return null; }}///<summary>///to the store for certificates///</summary>//<param name= "Subjectname" ></param>//<returns></returns> public static X509Certificate2 getcertificatefromstore (String subjectname) {Subjectna              me = "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>///Based on public key certificate, return certificate entity///</summary>//<param name= "Cerpa TH "></param> public static X509Certificate2 Getcertfromcerfile (string cerpath) {T         ry {         return new X509Certificate2 (Cerpath); } catch (Exception e) {Logrecord.puterrorlog (e.tostring (), "Datacertificate.lo                  Adstudentpublickey ");              return null;   }} #endregion}

  

C # Create a digital certificate and export it as a PFX and use PFX for asymmetric plus decryption

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.