manipulating digital certificates in. NET __.net

Source: Internet
Author: User
Tags base64 int size readfile pfx file

. 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 dialog box for certificate messages, which is the. NET implementation of the certificate Viewer in IE.

The following code pops up a selection dialog box for the user to select, and a dialog box that pops up the details of the certificate.

            X509store store = new X509store (Storename.root, storelocation.localmachine);   
            Store. Open (Openflags.readonly | openflags.openexistingonly);   
            X509Certificate2Collection certs = x509certificate2ui.selectfromcollection (store. Certificates, "Certificates", "Please select certificate to use", x509selectionflag.singleselection);
            X509certificate2ui.displaycertificate (Certs[0]);
            Console.WriteLine (Certs[0]);


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

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. Start  run mmc and open an empty MMC console. On the Console menu, file  Add/Remove snap-in  Add button  Select "Certificate"  add  Select "My user account"  close  OK on the Console menu, file  Add/Remove snap-in  Add button  Select "Certificate"  add  Select "Computer account"  close  OK

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

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

There is no private key in the certificate, the DER encoded binary format certificate file, with a CER as the name of the certificate file suffix. BASE64-encoded certificates

There is no private key in the certificate, a certificate file in the BASE64 encoding format, 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 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 (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);

Store. Close ();

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",//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)

{

Compare the name of the certificate to the certificate Mytestcert you want to export, and locate the certificate that you want to export

if (Myx509certificate2.subject = = "Cn=testcert")

{

Certificate exported to byte[], password protect password for private key

byte[] Certbyte = Myx509certificate2.export (x509contenttype.pfx, "password");

To write a certificate's byte stream to a 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 ();

Code Listing 6-19 first declares the instance store for the X509store class, using the

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.