Export PFX and CER certificates from a self-signed certificate

Source: Internet
Author: User
Tags foreach bool pfx file

Full code:

public sealed class Datacertificate {#region Generate a certificate///<summary>//According to the specified certificate title and Makecer   
        T 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> P Ublic static bool Createcertwithprivatekey (string subjectname, String makecertpath) {subjectname = "C
            n= "+ subjectname;
            string param = "-pe-ss my-n \" "+ Subjectname +" \ ";
                try {Process p = process.start (Makecertpath, param);
                p.WaitForExit ();
            P.close ();
            } catch (Exception e) {return false;
        } return true; #endregion #region File Import/export///<summary>////from the personal my area of the Windows certificate store to find the topic Subjectnam   
 E's certificate,       and export to a PFX file, assign it a password at the same time///and remove the certificate from the personal area (if Isdelfromstor is true)///</summary> <param name= "Subjectname" > Certificate subject, not including cn=</param>//<param name= "pfxfilename" >pfx file name </p aram>//<param name= "password" >pfx file password </param>///<param Name= "Isdelfromstore" & gt; Whether to remove from storage </param>///<returns></returns> public static bool Exporttopfxfile (str  ing 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, 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]! = Fil
                                Estream.readbyte ()) {filestream.close ();
  return false;                          }} filestream.close (); } if (Isdelfromstore = = True) store.
                Remove (X509); }} store.
            Close ();
        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= " Cerfilename "></param>///<returns></returns> public static bool Exporttocerfil
            E (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, 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]! = Filestream.readbyte ()) {
                                Filestream.close ();
                            return false;
                    }} filestream.close (); }}} store.
            Close ();
            store = null;
            Storecollection = null;
        return true; #endregion #region Obtain the information from the certificate///<summary>///or the certificate entity according to the private key certificate, the entity can be added according to its public key and private key. Cryptographic///decryption functions use Dencrypt's rsacryption class//</summary>//<param name= "Pfxfilename" & gt;</param>//<param name= "password" ></param>///<returns></returns&gt   
        ;
            public static X509Certificate2 Getcertificatefrompfxfile (string pfxfilename, string password) {
  Try          {return new X509Certificate2 (pfxfilename, password, x509keystorageflags.exportable);
            } catch (Exception e) {return null; }}///<summary>///to the store for certificates///</summary>//<param N Ame= "Subjectname" ></param>///<returns></returns> public static X509certificat
            E2 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>///certificate entities are returned according to the public key certificate///</summary>//<param name= "
            Cerpath "></param> public static X509Certificate2 Getcertfromcerfile (string cerpath) {
            try {return new X509Certificate2 (Cerpath);
            } catch (Exception e) {return null; }} #endregion}

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.