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

Source: Internet
Author: User
Tags decrypt pfx file

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:

01.///<summary> 02.        Export the certificate from the certificate store and store it as a PFX file while specifying the open password 03 for the PFX file.        This function also demonstrates how to encrypt with the public key and decrypt the private key by 04.        </summary> 05.        <param name= "Sender" ></param> 06.        <param name= "E" ></param> 07.        private void Btn_topfxfile_click (object sender, EventArgs e) 08.   {X509store store = new X509store (storename.my, Storelocation.currentuser); Store.   Open (Openflags.readwrite); X509Certificate2Collection storecollection = (x509certificate2collection) store.   certificates;            13. foreach (X509Certificate2 x509 in storecollection). {. if (x509.                Subject = = "Cn=luminji") 15. {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)) 19.   {.//Write The data to the file, byte by byte.                            for (int i = 0; i < pfxbyte.length; i++) 22.   Filestream.writebyte (Pfxbyte[i]);   .//Set The stream position to the beginning of the file.   Filestream.seek (0, Seekorigin.begin);   //Read and verify the data.                        (int i = 0; i < filestream.length; i++) 27.                            {Pfxbyte[i]! = Filestream.readbyte ()) 29.   {Debug.Print ("Error writing data.");   -Return;                        32.} 33.                        } 34.   Filestream.close (); Debug.Print ("The DATA was written to {0} "+ 36.   "and verified.", Filestream.name);                    37.} 38. 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); The. String destr = this. Rsadecrypt (X509.   Privatekey.toxmlstring (True), enstr);   MessageBox.Show ("Clear text is:" + destr);            43.} 44.            } 45. Store.   Close ();   . store = null;   Storecollection = null;        48.} 49.        <summary> 50.        Create a certificate that also has a private key 51.        </summary> 52.        <param name= "Sender" ></param> 53.        <param name= "E" ></param> 54.        private void Btn_createpfx_click (object sender, EventArgs e) 55.          {56.  String MakeCert = "C:\\Program Files\\Microsoft Visual Studio 8\\sdk\\v2.0\\bin\\makecert.exe";   X509name. String = "Cn=luminji";   . String param = "-pe-ss my-n \" "+ X509name +" \ ";   A. Process p = process.start (MakeCert, param);   p.WaitForExit ();   P.close ();   MessageBox.Show ("over");        63.} 64.        <summary> 65.        Read certificate information from PFX file 66.        </summary> 67.        <param name= "Sender" ></param> 68.        <param name= "E" ></param> 69.        private void Btn_readfrompfxfile (object sender, EventArgs e) 70.   {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 ());    75.        PC = NULL;        76.} 77.        <summary> 78.        RSA decryption 79.        </summary> 80.        <param name= "Xmlprivatekey" ></param> 81.        <param name= "m_strdecryptstring" ></param> 82.        <returns></returns> 83.        public string Rsadecrypt (string Xmlprivatekey, String m_strdecryptstring) 84.   {RSACryptoServiceProvider Provider = new RSACryptoServiceProvider (); Provider.   Fromxmlstring (Xmlprivatekey);   byte[] RGB = convert.frombase64string (m_strdecryptstring); byte[] bytes = provider.   Decrypt (RGB, false); . return new UnicodeEncoding ().   GetString (bytes);        90.} 91.        <summary> 92.        RSA encryption 93.        </summary> 94.        <param name= "Xmlpublickey" ></param> 95. <param name= "M_strencryptstring" ></param> 96.        <returns></returns> 97.        public string Rsaencrypt (string Xmlpublickey, String m_strencryptstring) 98.   {RSACryptoServiceProvider Provider = new RSACryptoServiceProvider (); Provider.   Fromxmlstring (Xmlpublickey); 101. byte[] bytes = new UnicodeEncoding ().   GetBytes (m_strencryptstring); 102. Return convert.tobase64string (provider.   Encrypt (bytes, false));   103.}

The above is an example program, and a complete certificate tool class is as follows:

01.public sealed class Datacertificate 02.        {04. #region Generate Certificate.        <summary> 05.        Generates a certificate based on the specified certificate title and MakeCert full path (contains the public and private keys and is saved in the My store) 06.        </summary> 07.        <param name= "Subjectname" ></param> 08.        <param name= "Makecertpath" ></param> 09.        <returns></returns> 10.        public static bool Createcertwithprivatekey (string subjectname, String makecertpath) 11.   {subjectname = "cn=" + subjectname;   string param = "-pe-ss my-n \" "+ Subjectname +" \ ";            Try 15.   {. Process p = process.start (Makecertpath, param);   p.WaitForExit ();   P.close ();            19.} 20.            catch (Exception e) 21.   {Logrecord.puterrorlog (e.tostring (), "Datacerficate.createcertwithprivatekey"); Retur.n false;            24.} 25.   return true;        26.} 27. #endregion 28.        Import and Export 30. #region file.        <summary> 31.        From the personal my area of the Windows certificate store, locate the certificate subject to Subjectname, 32.        and export it as a PFX file, specifying a password of 33.        and remove the certificate from the personal area (if Isdelfromstor is true) 34.        </summary> 35.        <param name= "Subjectname" > Certificate subject, cn=</param> 36 not included.        <param name= "pfxfilename" >pfx file name </param> 37.        <param name= "password" >pfx file password </param> 38.        <param name= "Isdelfromstore" > whether to remove </param> 39 from the storage area.        <returns></returns> 40.            public static bool Exporttopfxfile (string subjectname, String pfxfilename, 41.        string password, bool Isdelfromstore) 42.   {subjectname = "cn=" + subjectname;   X509store store = new X509store (storename.my, Storelocation.currentuser); A. Store.Open (Openflags.readwrite); X509Certificate2Collection storecollection = (x509certificate2collection) store.   certificates;            48. foreach (X509Certificate2 x509 in storecollection). {. if (x509.                Subject = = subjectname) 50. {Wuyi Debug.Print (string. Format ("certificate name: {0}", X509.   Subject));                    52.53. byte[] Pfxbyte = x509.   Export (x509contenttype.pfx, password);                    The. using (FileStream FileStream = new FileStream (Pfxfilename, FileMode.Create)) 55.   {*.//Write The data to the file, byte by byte.                            for (int i = 0; i < pfxbyte.length; i++) 58.   Filestream.writebyte (Pfxbyte[i]);   The.//Set The stream position to the beginning of the file.   Filestream.seek (0, Seekorigin.begin);               61.         Read and verify the data.                        for (int i = 0; i < filestream.length; i++) 63.                            {Pfxbyte[i]! = Filestream.readbyte ()) 65. {Logrecord.puterrorlog ("Export PFX error while verify the PFX file!", "Exporttopfxfi   Le ");   Filestream.close ();   . return false;                        69.} 70.                        } 71.   Filestream.close ();                    72.} 73.                        if (Isdelfromstore = = True) 74. Store.   Remove (X509);            75.} 76.            } 77. Store.   Close ();   . store = null;   Storecollection = null;   return true;        81.} 82.        <summary> 83. Find the subject as sub from the personal my area of the Windows certificate storeJectname's certificate, 84.        and exported as a CER file (that is, only the public key is included) 85.        </summary> 86.        <param name= "Subjectname" ></param> 87.        <param name= "Cerfilename" ></param> 88.        <returns></returns> 89.        public static bool Exporttocerfile (string subjectname, String cerfilename) 90.   {subjectname = "cn=" + subjectname;   X509store store = new X509store (storename.my, Storelocation.currentuser); The. Store.   Open (Openflags.readwrite); 94. X509Certificate2Collection storecollection = (x509certificate2collection) store.   certificates;            96. foreach (X509Certificate2 x509 in storecollection). {X509.                Subject = = subjectname) 98. {Debug.Print (String. Format ("certificate name: {0}", X509.   Subject)); //byte[] Pfxbyte = x509. Export (X509CONTENTTYPE.PFX,password); 101. byte[] Cerbyte = x509.   Export (X509contenttype.cert);                    102. Using (FileStream FileStream = new FileStream (Cerfilename, FileMode.Create)) 103.   {104.//Write The data to the file, byte by byte.                            for (int i = 0; i < cerbyte.length; i++) 106.   Filestream.writebyte (Cerbyte[i]);   107.//Set The stream position to the beginning of the file.   108. Filestream.seek (0, Seekorigin.begin);   109.//Read and verify the data.                        for (int i = 0; i < filestream.length; i++) 111.                            {Cerbyte[i]! = Filestream.readbyte ()) 113. {Logrecord.puterrorlog ("Export CER error while verify the CERT file!", "Exporttocer  File "); Filestream.close ();   A. return false;                        117.} 118.                        } 119.   Filestream.close ();                120.} 121.            } 122.            } 123. Store.   Close ();   124. store = null;   Storecollection = null;   126. return true;        127.} 128. #endregion 129.        #region get information from the certificate 131.        <summary> 132.        The certificate entity is obtained according to the private key certificate, and the entity can be added and decrypted according to its public key and private key 133.        The Add decryption function uses Dencrypt's Rsacryption class 134.        </summary> 135.        <param name= "Pfxfilename" ></param> 136.        <param name= "Password" ></param> 137.        <returns></returns> 138.            public static X509Certificate2 Getcertificatefrompfxfile (String pfxfilename, 139.        string password) 140.  { 141. Try 142.   {143. Return new X509Certificate2 (pfxfilename, password, x509keystorageflags.exportable);            144.} 145.            catch (Exception e) 146.                    {147. Logrecord.puterrorlog ("Get certificate from PFX" + Pfxfilename + "error:" + e.tostring (), 148.   "Getcertificatefrompfxfile");   149. return null;        150.} 151.        } 152.        <summary> 153.        Obtain the certificate 154 from the storage area.        </summary> 155.        <param name= "Subjectname" ></param> 156.        <returns></returns> 157.        public static X509Certificate2 Getcertificatefromstore (String subjectname) 158.   {159. Subjectname = "cn=" + subjectname;   X509store store = new X509store (storename.my, Storelocation.currentuser); 161. Store.   Open (Openflags.readwrite); 162. X509ceRtificate2collection storecollection = (x509certificate2collection) store.   certificates;            163. foreach (X509Certificate2 x509 in storecollection) 164. {165. if (X509.                Subject = = subjectname) 166.   {167. return x509;            168.} 169.            } 170. Store.   Close ();   171. store = null;   172. storecollection = null;   173. return null;        174.} 175.        <summary> 176.        Returns the certificate entity 177, based on the public key certificate.        </summary> 178.        <param name= "Cerpath" ></param> 179.        public static X509Certificate2 Getcertfromcerfile (string cerpath) 180.            {181. Try 182.   {183. Return new X509Certificate2 (Cerpath);            184.} 185.            catch (Exception e) 186. {187. Logrecord.puterrorlog (E.tostring (), "datacertificAte.   Loadstudentpublickey ");   188. return NULL;        189.} 190.        } 191.    #endregion 192.   }

C # Create a digital certificate and export it as a PFX and use PFX for asymmetric 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.