. NET, including how to generate a certificate, program a certificate, and create a issuer certificate.
. NET provides two main classes for us to operate digital certificates:
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 certificates stored in the computer Security zone.
In addition, you can use the System. Security. Cryptography. X509Certificates. X509Certificate2UI class to display the certificate message dialog box, which is the. NE Implementation of the certificate viewer in IE.
Generate Certificate
Secret to generate a certificate file. Now we use makecert.exe to generate a certificate file for testing. Start the command line of VS2010 and enter the corresponding parameter to generate a certificate file named TestCertificates. See Figure 6-28
Figure 6-28 generate a certificate
For more information about the parameters of makecert.exe, see <G id = "1"> parameters </G>.
Parameter description:
-Sr CurrentUser: Specifies the certificate storage location for the topic. Location can be currentuser (default) or localmachine
-Ss MyTestContainer: Specifies the certificate storage name of the topic. The output certificate is stored there.
-N CN = TestCert: Specifies the Certificate Name of the topic. This name must comply with X.500 standards. The simplest way is to specify this name in double quotes with the prefix CN =; for example, "CN = myName ".
-Sky exchange: Specifies the issuer's key type, which must be signature, exchange, or an integer that represents the provider type. By default, 1 indicates the exchange key, and 2 indicates the signature key.
-Pe: Mark the generated private key as exported. In this way, the private key can be included in the certificate.
The generated key file is saved in the MyTestContainer we specified, but where can we view our certificate? Windows does not provide a direct Certificate Management Portal for us, but we can add it on the MMC console.
Start running MMC and open an empty MMC console.
In the console menu, select "certificate" add and select "My User Account" in the Add/delete Management Unit button to close OK
In the console menu, select "certificate" Add or select "Computer Account" to add/delete a management unit.
6-29, we can view the Certificate Management of the two accounts. In my account, we can see the certificate TestCert under MyTestContainer.
Figure 6-29 view and manage certificates on the MMC console
Of course, you can save the Certificate file as a file, as shown in Figure 6-30.
Figure 6-30 Save the certificate as a file
Open the E disk and you will see the generated Certificate file. 6-31.
Figure 6-31 generated Certificate file
When saving a certificate as a file, we have three options:
Certificates with private keys are defined by the Public Key Cryptography Standards #12 and PKCS #12 standard. Certificates with private keys are in the binary format of Public keys and private keys. pfx is used as the suffix of the Certificate file.
There is no private key in the certificate of binary encoding. The certificate file of DER encoding binary format is suffixed with cer.
Base64-encoded certificates do not contain private keys. Certificates in BASE64 format are also suffixed with cer.
Right-click the Local Certificate file and we can see the installation options. You can install the Certificate file in the certificate storage area. You can also execute the export task on the Certificate Management Platform of MMC to export the certificate of the storage area as a file. We will not describe it here. You can practice it on your own.
Programming operation certificate
We can operate the Local Certificate file and the certificate in the storage area through programming. Take the test. cer file saved on the E disk as an example to explain how to read the local certificate file and add it to the storage area. First look at the code list 6-17.
Code List 6-17
Class opercert {internal static byte [] readfile (string filename) {filestream F = new filestream (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;} static void main (string [] ARGs) {try {x509certificate2 X509 = new x509certificate2 (); byte [] rawdata = readfile (@ "E: \ test. CER "); x509.import (Rawda Ta); 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 (EXC Eption e) {console. writeline ("error:" + E. Message) ;}} code list 6-17 demonstrate how to read local certificate files. The static method readfile is used to read the Certificate file from the local disk to the byte array. The main operations are in the main method. X509certificate2 X509 = new x509certificate2 (): Use a parameter-free constructor to initialize the X509 instance of the x509certificate2 class. Then we use the x509.import (rawdata) statement to import the byte array to the current certificate instance. Next, output the certificate information.
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); store. Close ();
First, we Initialize an X509Store instance store, then Open the storage area using the Open method, and add the certificate read above to the storage area.
X509Certificate2 provides a total of 14 constructors for our use. We will not describe them here. You can also use the constructor of the X509Certificate2 class to directly import the Local Certificate file, as shown in code list 6-18.
Code List 6-18 Use constructors to import certificate files
X509Certificate2 myX509Certificate2 = new X509Certificate2 (@ "e: \ MyTestCert. pfx ", // certificate path" password ", // certificate private key protection password X509KeyStorageFlags. exportable // indicates that the private key of this certificate can be exported later );
Code List 6-18 shows how to import a certificate with a private key to protect the password. The X509KeyStorageFlags enumeration is used to identify where the private key of the X.509 Certificate is exported and how it is exported. The description of the enumerated members is 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's storage area instead of the local computer storage area. Both the specified key of the certificate and the private key are stored in the current user's storage zone.
MachineKeySet
The private key is stored in the local computer storage area instead of the current user storage area.
Exportable
The imported key is marked as exported.
UserProtected
Notify the User Key to be accessed through a dialog box or other methods. The specified behavior is defined by the encryption service provider (CSP.
Persistkeyset
The key associated with the pfx file is saved when you import the certificate.
In this case, you can use the code listing 6-19 to operate the certificates in the bucket.
Code List 6-19 perform operations on certificates in the bucket
X509store store = new x509store (storename. my, storelocation. currentuser); store. open (openflags. readonly); // round-robin of all certificates in the storage area foreach (x509certificate2 myx509certificate2 in store. certificates) {// compare the Certificate Name with mytestcert, and find the certificate to export if (myx509certificate2. subject = "cn = testcert") {// export the certificate to byte []. The password is the private key to protect the password byte [] certbyte = myx509certificate2. export (x509contenttype. pfx, "password"); // write the certificate byte stream 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 ();
In code list 6-19, the instance store of the X509Store class is declared first, and two constructor parameters are used. The first parameter is the name of the storage container. The StoreName enumeration can only enumerate the default storage zone name of the system. The second parameter is StoreLocation enumeration, used to identify whether the local certificate or the current user certificate. The Export container certificate uses the Export method. The first parameter X509ContentType. Pfx indicates the pfx certificate containing the private key to be exported. The second parameter is the private key protection password. If you want to export a cer certificate that does not contain the private key, the first parameter uses X509ContentType. Cert to export it as a cer certificate that does not contain the private key, so you do not need a password.
Create a issuer Certificate
The issuer certificate is a certificate file that verifies the reliability of the issuer and protects the issuer's signature. We can obtain this document from the certificate authority. For program testing, we can use cert2spc.exe to generate a issuer certificate. Start the program from the command line, as shown in Figure 6-32.
Figure 6-32 generate the SPC File
6-32. We use cert2spc.exe to generate a issuer certificate with the test. cer parameter as the target tset. spc. If multiple certificate files exist, we can use them as parameters to generate a uniform issuer certificate separated by spaces.
Sign a file using a certificate
The signing tool (SignTool.exe) is a command line tool used to digitally sign the file and verify the signature in the file or timestamp file. We can sign cab files, dll files, or other files. when accessing these files from the Internet, we need to install and verify the certificate. The detailed description of this tool can be found on MSDN.