C # Digital Certificate Programming Summary __ Programming

Source: Internet
Author: User
Tags base64 decrypt int size readfile readline password protection asymmetric encryption pfx file
. How to operate digital certificate in net

. NET provides us with two main classes for manipulating digital certificates, divided into:
System.Security.Cryptography.X509Certificates.X509Certificate2 class, each instance of this class can represent a certificate;
System.Security.Cryptography.X509Certificates.X509Store class, you can add/remove/get an operation on a certificate that is saved in a computer security zone.

In addition, we can use the System.Security.Cryptography.X509Certificates.X509Certificate2UI class to display the Certificate message dialog box, which is in IE in the certificate Viewer of the. NE implementation.

Generate certificate
Before we introduce the use of the above class, we have to have a digital certificate, to obtain a digital certificate there are three ways, one is to apply from the CA, the second is to build their own server publishing certificates, the third is to use Makecert.exe to generate a certificate file. Here we use Makecert.exe to generate a certificate file for testing. Start the VS2010 command line, enter the corresponding parameter, and generate a certificate file named Testcertificates. As shown in Figure 6-28.

Generate certificate

Figure 6-28 Generating certificates

Makecert.exe parameters The reader can view help, which only explains the parameters in Figure 6-28.

Parameter description:

-SR CurrentUser: Specifies the certificate store location for the topic. Location can be CurrentUser (default) or LocalMachine

-SS Mytestcontainer: Specifies the certificate store name for the subject, where the output certificate is stored.

-N Cn=testcert: Specifies the certificate name of the subject. This name must conform to the X.500 standard. The easiest way to do this is to specify the name in double quotes and prefix cn=; for example, "Cn=myname".

-sky Exchange: Specifies the issuer's key type, which must be signature, Exchange, or an integer representing the provider type. By default, you can pass in 1 to exchange the key, and incoming 2 to represent the signing key.

-pe: Marks the generated private key as exportable. This allows the private key to be included in the certificate.

The generated key file was saved in the Mytestcontainer we specified, but where to view our certificate. Windows does not have a direct access to the admin certificate, but we can add it ourselves in the MMC console.

As shown in Figure 6-29, we can view certificate management for two accounts, and I can see the certificate TestCert under Mytestcontainer in my account.

View and manage certificates in an MMC console

Figure 6-29 Viewing and managing certificates in an MMC console

Of course, we can also save the certificate file as a file, as shown in Figure 6-30.

To save a certificate as a file

Figure 6-30 Saving a certificate as a file

Open e disk to see the generated certificate file. As shown in Figure 6-31.

The generated certificate file

Figure 6-31 the certificate file generated

When you save a certificate as a file, we have three choices:

A certificate with a private key is

#12 by the public key cryptography standards, PKCS#12 standard definition, contains the form of a certificate in the binary format of both a and private key, with a PFX as the name of the certificate file suffix. The
binary-encoded certificate Certificate

has no private key, DER-encoded certificate file in binary format, and a CER as the name of the certificate file suffix. The
Base64-encoded Certificate

certificate does not have a private key, a BASE64 encoded certificate file, and a CER as the name of the certificate file suffix.

Right-click the local certificate file and we can see the installation option to install the certificate file into the certificate store. You can also perform an export task on the Certificate Management Console of MMC to export the certificate of a store to a file. This is no longer demonstrated, and the reader can practice it on its own.

Programming Operation Certificate

We can manipulate the local certificate file and the certificate in the store programmatically. As an example of the Test.cer file we just saved in E disk, we explained how to read the local certificate file and add it to the store. Look at code listing 6-17 first.

Code Listing 6-17 manipulating a local certificate file

    Class Opercert {internal static byte[] ReadFile (string fileName) {FileStream f = new Filestr  
    EAM (FileName, FileMode.Open, FileAccess.Read);  
    int size = (int) f.length;  
    byte[] data = new Byte[size];  
    Size = f.read (data, 0, size);  
    F.close ();  
    return data;  
    The static void Main (string[] args) {try {x509certificate2 x509 = new X509Certificate2 ();  
    byte[] RawData = ReadFile (@ "E:\test.cer"); X509.  
    Import (RawData); Console.WriteLine ("{0}subject: {1}{0}", Environment.NewLine, X509.)  
    Subject); Console.WriteLine ("{0}issuer: {1}{0}", Environment.NewLine, X509.)  
    Issuer); Console.WriteLine ("{0}version: {1}{0}", Environment.NewLine, X509.)  
    Version); Console.WriteLine ("{0}valid Date: {1}{0}", Environment.NewLine, X509.)  
    Notbefore); Console.WriteLine ("{0}expiry Date: {1}{0}", Environment.NewLine, X509.)  
    Notafter); Console.WriteLine ("{0}thumbprint: {1}{0}", Environment.NewLine, X509.Thumbprint); Console.WriteLine ("{0}serial number: {1}{0}", Environment.NewLine, X509.)  
    SerialNumber); Console.WriteLine ("{0}friendly Name: {1}{0}", Environment.NewLine, X509.)  
    PublicKey.Oid.FriendlyName); Console.WriteLine ("{0}public Key Format: {1}{0}", Environment.NewLine, X509.)  
    PublicKey.EncodedKeyValue.Format (true)); Console.WriteLine ("{0}raw Data Length: {1}{0}", Environment.NewLine, X509.)  
    Rawdata.length); Console.WriteLine ("{0}certificate to String: {1}{0}", Environment.NewLine, X509.)  
    ToString (true)); Console.WriteLine ("{0}certificate to XML String: {1}{0}", Environment.NewLine, X509.)  
    PublicKey.Key.ToXmlString (false));  
    X509store store = new X509store (); Store.  
    Open (openflags.maxallowed); Store.  
    ADD (X509); Store.  
    Close ();  
    catch (Exception e) {Console.WriteLine ("Error:" +e.message);  }  
    }  
    }

Code Listing 6-17 shows how to read a local certificate file. Static method ReadFile is used to read the certificate file from the local disk into the byte array. The main operations are in the main method. X509Certificate2 x509 = new X509Certificate2 () Initializes an instance of the X509Certificate2 class with an parameterless constructor x509. Then we use X509. The import (RAWDATA) statement imports a byte array into the current certificate instance. Next is the information to output the certificate.

After the information is output, let's look at the following four lines of code:

    X509store store = new X509store ();  
    Store. Open (openflags.maxallowed);  
    Store. ADD (X509);  
    

First we initialize an instance store of the X509store class, and then use the Open method to open the store and add the certificate read above to the store.

X509CERTIFICATE2 provides 14 constructors for us to use, not one of them. We can also import the local certificate file directly through the constructor of the X509Certificate2 class, using the way shown in Listing 6-18.

Code listing 6-18 importing certificate files using constructors

    X509Certificate2 myx509certificate2 = new X509Certificate2 (  
    @ "e:\MyTestCert.pfx",//certificate path  
    "password",// The certificate's private key protection password  
    x509keystorageflags.exportable//indicates that the private key of this certificate can also be exported later  
    

Code Listing 6-18 shows how to import a certificate with a private key protection password. The X509keystorageflags enumeration is used to identify where and how the private key for the X.509 certificate is exported. The member descriptions for this enumeration are shown in table 6-1.

Table 6-1 X509keystorageflags Enumeration Description

Member name

Description

Defaultkeyset

Use the default key set. The user key set is usually the default value.

Userkeyset

The private key is stored in the current user store instead of the local computer store. Even if the certificate specifies that the key should be stored in the local computer store, the private key is also stored in the current user store.

MachineKeySet

The private key is stored in the local computer store instead of the current user store.

Exportable

The imported key is marked as exportable.

userprotected

Notifies the user that the key is accessed through a dialog box or other method. The cryptographic service provider (CSP) used defines the exact behavior.

Persistkeyset

The key associated with the PFX file is saved when the certificate is imported.

So how do you manipulate the certificates in the store, you can use the way code listing 6-19.

Code Listing 6-19 The certificate in the operations store

 X509store store = new X509store (storename.my, Storelocation.currentuser); Store.  
    Open (openflags.readonly); Poll all certificates in the store foreach (X509Certificate2 myx509certificate2 in store.  
    Certificates) {//Mytestcert the name of the certificate compared to the certificate to be exported, find the certificate to export (Myx509certificate2.subject = "Cn=testcert") {//certificate exported to byte[], password protection password for private key byte[] Certbyte = Myx509certificate2.export (x509contenttype.pfx, "password  
    ");  
    Writes a byte stream of a certificate to the certificate file FileStream fstream = new FileStream (@ "C:\Samples\PartnerAEncryptMsg\MyTestCert_Exp.pfx",  
    FileMode.Create, FileAccess.Write);  
    Fstream.write (certbyte, 0, certbyte.length);  
    Fstream.close (); } store. Close (); 

Listing 6-19 first declares the instance store for the X509store class, using the two-parameter constructor, the first parameter is the name of the storage container, and the Storename enumeration can only enumerate the system default store names. The second parameter is the Storelocation enumeration, which identifies whether it is a native certificate or a current user certificate. Exporting a container certificate uses the Export method. The first parameter, x509contenttype.pfx, represents the form of a PFX certificate to be exported as a private key, and the second parameter is the private key protection password. If you are exporting a CER certificate that does not contain a private key, the first parameter uses X509contenttype.cert to indicate that you are exporting a CER certificate that does not contain a private key, and you do not need a password.

Create Publisher Certificate

A publisher certificate is a certificate file that verifies the reliability of the publisher and protects the signature of the certificate publisher. We can get the file from the certification authority. As a program test, we can use Cert2spc.exe to generate the publisher certificate. Start the program from the command line, as shown in Figure 6-32.

Generating an SPC file

Figure 6-32 Generating the SPC file

As shown in Figure 6-32, we use Cert2spc.exe to generate the publisher certificate for the Test.cer as a parameter, and if there are more than one certificate file, you can generate a uniform publisher certificate as a space-separated argument.

To sign a file with a certificate

The signing Tool (SignTool.exe) is a command-line tool used to digitally sign a file and verify the signature in a file or timestamp file. We can sign CAB files, DLL files, or other files, and we need to install and verify certificates when we access these files from the Internet. The tool details how the reader can be found on MSDN and I'm not going to repeat it. Use the X509Certificate2 class in C # to get the name information of a digital certificate issuer and holder

In the. NET Framework, there is a class named X509Certificate2 that allows you to easily obtain information such as the serial number in the X.509 format digital certificate, the expiration date, the expiration date, and so on. A detailed description of the class can be found on the MSDN Web site.
In the properties of the class, the two pairs of issuer and issuername, Subject, and subjectname look more like each other, and are easily confusing. Here's how to do this:

1 The type of the issuer and Subject attributes is string, which allows you to obtain the distinguished Name of both the certificate issuer and the certificate holder, respectively. Distinguished Name is usually a string similar to the following form: "Cn=myname, o=myorg, Ou=myorgunit, C=us"
This string is used internally as a delimiter (note that the comma in English is not a comma in Chinese), where CN represents Common Name,o on behalf of the organization, OU on behalf of the Organization, and C for the name of the country.

2 The types of issuername and Subjectname attributes are System.Security.Cryptography.X509Certificates.X500DistinguishedName, and note that it is not string. The X500distinguishedname has three properties, respectively: Name, Oid, and RawData. You can also get distinguished name by using the Name property. That
The values of X509certificate2.issuer and X509Certificate2.IssuerName.Name are equal;
The values of X509certificate2.subject and X509Certificate2.SubjectName.Name are equal.

For the distinguished name of a certificate issuer or holder, the part that is often used is the Common name, which is the content behind cn=. However, the. NET Framework does not directly provide a way to extract Common name from distinguished name. Because the interior of the distinguished name is used to separate parts of different meanings, you can use, as a delimiter, to split distinguished Name into multiple substrings, and then find the cn= in the substring, and find the later part of cn= to extract it, so You can get the value of Common Name. The specific implementation code is as follows:

Using System; Namespace EXTRACTCNFROMDN {class Program {public static string Extractcommonnamefromdn (String Distinguis Hedname) {if (String.IsNullOrEmpty (distinguishedname)) {throw new Argume
            Ntnullexception ("distinguishedname"); String strcommonname = String.
            Empty;
            BOOL Bfoundsubstr = false;
            String strstartsubstr = "cn=";
            Char[] Chdelimiterchars = {', '};
            string[] NameArray = Distinguishedname.split (chdelimiterchars);
            int inamelength; for (int i = 0; i < namearray.length i++) {inamelength = Namearray[i].
                Length; if (Inamelength > 3) {if String.Compare (Strstartsubstr, namearray[i). Substring (0, 3), true) = = 0) {strcommonname = Namearray[i].
                 Substring (3, (iNameLength-3));       Bfoundsubstr = true;
                    Break }} if (Bfoundsubstr = false) Strcommonname = string.
            Empty;
        return strcommonname;
            }/*************************************************/static void Main (string[] args) { String strDN = "cn= tester, e=test@abc.com, s= Shanghai, C=CN"; /* Note that this is not a comma/string strcn = string in Chinese.


            Empty;
            try {strcn = EXTRACTCOMMONNAMEFROMDN (strDN); catch (ArgumentNullException e) {Console.WriteLine ("Error message: {0}", e.mess
                Age);
                Console.ReadLine ();
            Return
            } Console.WriteLine ("Distinguished name: {0}", strDN);
            Console.WriteLine ("Common name: {0}", STRCN);
            Console.ReadLine ();
        Return }
    }
}
C # Creates a digital certificate and exports it as a PFX and uses a PFX for asymmetric encryption and decryption

In my project, with security in mind, you need to distribute a digital certificate for each client and use the public key in the digital certificate to decrypt the data. In order to complete this security module, the following features a demo program, the demo program contains:

1: Call. The NET2.0 MakeCert creates a digital certificate that contains a private key and stores it in a personal certificate area;
2: Export the certificate as a PFX file, and assign it a password to open the PFX file;
3: Read PFX file, export the public key and private key in PFX;
4: Use the public key in the PFX certificate to encrypt the data and decrypt the data with the private key;

System interface:

The code is as follows:

<summary>///Exports the certificate from the certificate store and stores it as a PFX file, while specifying an open password for the PFX file///This function also demonstrates how to encrypt with a public key and decrypt the private key </summary>///<param name= "sender" ></param>///<param name= "E" ></ param> private void Btn_topfxfile_click (object sender, EventArgs e) {X509store St   
            Ore = 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, in 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 D   
                                Ata. ");   
                            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 that also has a private key///</summary>///<param name= "s Ender "></param>///<param name=" E "></param> private void Btn_createpfx_click (o Bject sender, EventArgs e) {string makecert = "C:\\Program Files\\Microsoft Visual Studio 8\\SD   
            K\\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>///reads certificate information from a PFX file///</summary>///<param Name = "Sender" ></param>///<param name= "E" ></param> private void Btn_readfrompfxfil E (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 decryption///</summary>///<param name= "XMLPRivatekey "></param>///<param name=" m_strdecryptstring "></param>///<retur   
            Ns></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 encryption///</summary>///<param name= "Xmlpu Blickey "></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));  
 }

This is an example program, and a complete certificate tools class is as follows:

public sealed class Datacertificate {#region Generate certificate///<summary>///According to the specified certificate name and MakeCert Full path generation certificate (contains public and private keys and saved in my store)///</summary>///<param name= "Subjectname" ></pa   
        ram>///<param name= "Makecertpath" ></param>///<returns></returns> public static bool Createcertwithprivatekey (string subjectname, String makecertpath) {su   
            Bjectname = "cn=" + subjectname;   
            string param = "-pe-ss my-n \" "+ Subjectname +" "";   
                try {Process p = process.start (Makecertpath, param);   
                p.WaitForExit ();   
            P.close (); The catch (Exception e) {Logrecord.puterrorlog (e.tostring ()), Datacerficat   
                E.createcertwithprivatekey ");   
            return false; } return True #endregion #region File Import Export///<summary>///Find the subject as sub from the personal my area of the Windows certificate store   
         Jectname's certificate,
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.