News
  • Favorite
  • Facebook
  • Twitter
  • LinkedIn

Microsoft Press Pearson Education (InformIT)
Skip Navigation Links
Pearson Education (InformIT)
How to: Encrypt and Decrypt your data with X509 Certificates using C#

Sometimes you want to secure your data with a way that you are the only one that will be able to view these data again. This can be accomplished using X509 Certificate. The X509 Certificate is signed with a private key that uniquely and positively identifies the holder of the certificate. The X509 Certificates can be used in Public Key Infrastructure PKI and SSO.

 

In this article we will create an application that queries and display installed certificates on your machine and encrypt and decrypt entered data with the private key of the certificate.

 

Using the Code:

To create an application that encrypts your data with X509 Certificate follow the following steps:

1.      Create a new windows application using Visual Studio 2005/2008/2010.

2.      Rename Form1 to CertificateForm.

3.      Add a ToolStrip control to the CertificateForm and rename it to CertificateToolStrip.

4.      Add a ToolStripButton to the CertificateToolStrip and rename it to EncryptToolStripButtonand set its Text property to Encrypt.

5.      Add a ToolStripButton to the CertificateToolStrip and rename it to DecryptToolStripButtonand set its Text property to Decrypt.

6.      Add a Label control to the CertificateForm and rename it to PlainLabel and set its Textproperty to Plain Text.

7.      Add a RichTextBox to the CertificateForm under the PlainLabeland rename it to PlainRichTextBox.

8.      Add a Label control to the CertificateFormand rename it to CipherLabel and set its Text property to Cipher Text.

9.      Add a RichTextBox to the CertificateForm under the CipherLabeland rename it to CipherRichTextBox.

10.  The CertificateForm should look like the following Image:

X509Certificate_01

11.  Import the System.Security.Cryptography and System.Security.Cryptography.X509Certificates namespaces using the following statement:

using System.Security.Cryptography;

using System.Security.Cryptography.X509Certificates;

 

12.  The System.Security.Cryptography namespace provides cryptographic services, including secure encoding and decoding of data, as well as many other operations, such as hashing, random number generation, and message authentication.

13.  The System.Security.Cryptography.X509Certificates namespace contains the common language runtime implementation of the Authenticode X.509 v.3 certificate. This certificate is signed with a private key that uniquely and positively identifies the holder of the certificate.

14.  Double click the EncryptToolStripButton to create the Click Event Handler.

15.  Add the following code to the EncryptToolStripButton Click Event Handler:

 

private void EncryptToolStripButton_Click(object sender, EventArgs e)

{

    try

    {

        X509Store store = new X509Store(StoreLocation.CurrentUser);

        store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

        X509Certificate2Collection certCollection = (X509Certificate2Collection)store.Certificates;

        X509Certificate2Collection foundCollection = (X509Certificate2Collection)certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);

        X509Certificate2Collection selectedcollection = X509Certificate2UI.SelectFromCollection(foundCollection,

            "Select a Certificate.", "Select a Certificate from the following list to get information on that certificate", X509SelectionFlag.SingleSelection);

 

        if (selectedcollection.Count > 0)

        {

            X509Certificate2 cert = selectedcollection[0];

 

            string certificateData = "Subject: " + cert.Subject + Environment.NewLine + "IssuerName: " + cert.Issuer

                    + "\nSerialNumber: " + cert.SerialNumber + "\nFriendlyName:\n"+ cert.FriendlyName;

 

            MessageBox.Show(certificateData, "Certificate Data",

               MessageBoxButtons.OK, MessageBoxIcon.Information);

 

            if (cert.Verify())

            {

               MessageBox.Show(cert.Subject + " is a valid certificate.", cert.FriendlyName,

                   MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

            else

            {

               MessageBox.Show(cert.Subject + " is not a valid certificate.", cert.FriendlyName,

                   MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

 

            RSACryptoServiceProvider rsaEncryptor = (RSACryptoServiceProvider)cert.PrivateKey;

            byte[] cipherData = rsaEncryptor.Encrypt(Encoding.UTF8.GetBytes(PlainRichTextBox.Text), true);

            CipherRichTextBox.Text = Convert.ToBase64String(cipherData);

        }

    }

    catch (CryptographicException ex)

    {

        MessageBox.Show(ex.Message, ex.GetType().ToString(),

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    catch (Exception ex)

    {

        MessageBox.Show(ex.Message, ex.GetType().ToString(),

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

}

 

a.      We create an instance of the X509Store class. This represents an X.509 store, which is a physical store where certificates are persisted and managed. We set the store location that exists in the current windows user that the application runs under.

b.     Then we open the store with these options ReadOnly and OpenExistingOnly. The OpenFlagsenumeration specifies the way to open the X.509 certificate store.

c.      We create an instance of X509Certificate2Collectionand name it certCollection that defines a collection that stores X509Certificate objects. We fill this collection with the certificates in the store we open earlier.

d.     We create another instance of X509Certificate2Collection and name it foundCollection that will store the found X509 Certificates with our search criteria. We fill this collection with X509 Certificates that are not expired in our store. The X509FindTypeenumeration specifies the type of value the X509Certificate2Collection.Find method searches for.

e.     We create an instance of X509Certificate2Collectionand name it selectedcollection that will store the selected X509 Certificates from the X509Certificate2UI Dialog. The X509Certificate2UIdisplays user interface dialogs that allow users to select and view X.509 certificates.

f.       We check if the user selects an X509 Certificate from the dialog or not.

g.      Then we create an instance of the X509Certificate2. This represents an X.509 certificate. And  assign it to the certificate that the users selects from the X509Certificate2UI

h.     We display some of the selected certificate data such as Subject, Issuer, Serial Number, and Friendly Name.

i.        We call the certificate Verify method that performs a X.509 chain validation using basic validation policy.

j.       We then create an instance of the RSACryptoServiceProvider and name it rsaEncryptor. This will be used to perform asymmetric encryption and decryption using the implementation of the RSA algorithm provided by the cryptographic service provider (CSP).

k.      We cast the X509 Certificate Private Key to rsaEncryptor.

l.        We create a byte array that will store the encrypted data.

m.   We call the RSACryptoServiceProvider Encrypt method and pass to it the binary representation of the Text in PlainRichTextBox. We use UTF8 encoding.

n.     Then we convert the encrypted data to a base 64 string and display it in the CipherRichTextBox.

 

16.  Double click the DecryptToolStripButton to create the Click Event Handler.

17.  Add the following code to the DecryptToolStripButton Click Event Handler:

private void DecryptToolStripButton_Click(object sender, EventArgs e)

{

    try

    {

        X509Store store = new X509Store(StoreLocation.CurrentUser);

        store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

        X509Certificate2Collection certCollection = (X509Certificate2Collection)store.Certificates;

        X509Certificate2Collection foundCollection = (X509Certificate2Collection)certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);

        X509Certificate2Collection selectedcollection = X509Certificate2UI.SelectFromCollection(foundCollection,

            "Select a Certificate.", "Select a Certificate from the following list to get information on that certificate", X509SelectionFlag.SingleSelection);

 

        if (selectedcollection.Count > 0)

        {

            X509Certificate2 cert = selectedcollection[0];

 

            string certificateData = "Subject: " + cert.Subject + Environment.NewLine + "IssuerName: " + cert.Issuer

                    + "\nSerialNumber: " + cert.SerialNumber + "\nFriendlyName:\n"+ cert.FriendlyName;

 

            MessageBox.Show(certificateData, "Certificate Data",

               MessageBoxButtons.OK, MessageBoxIcon.Information);

 

            if (cert.Verify())

            {

               MessageBox.Show(cert.Subject + " is a valid certificate.", cert.FriendlyName,

                   MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

            else

            {

               MessageBox.Show(cert.Subject + " is not a valid certificate.", cert.FriendlyName,

                    MessageBoxButtons.OK,MessageBoxIcon.Error);

            }

 

            RSACryptoServiceProvider rsaEncryptor = (RSACryptoServiceProvider)cert.PrivateKey;

            byte[] plainData = rsaEncryptor.Decrypt(Convert.FromBase64String(CipherRichTextBox.Text), true);

            PlainRichTextBox.Text = Encoding.UTF8.GetString(plainData);

        }

    }

    catch (CryptographicException ex)

    {

        MessageBox.Show(ex.Message, ex.GetType().ToString(),

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    catch (Exception ex)

    {

        MessageBox.Show(ex.Message, ex.GetType().ToString(),

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

}

 

a.      The code in the Decrypt button is the same as the Encrypt button except for the decryption process.

b.     We create an instance of the RSACryptoServiceProvider and name it rsaEncryptor. This will be used to perform asymmetric encryption and decryption using the implementation of the RSA algorithm provided by the cryptographic service provider (CSP).

c.      We cast the X509 Certificate Private Key to rsaEncryptor.

d.     We create a byte array that will store the decrypted data.

e.     We call the RSACryptoServiceProvider Decrypt method and pass to it the binary representation of the Text in CipherRichTextBox. As in the encrypt method we convert the encrypted data to base 64 string we then restore the base64 string to binary representation using the Convert class FromBase64String method.

f.       Then we convert the decrypted data to a UTF8 string using UTF8 encoding and display it in the PlainRichTextBox.

 

18.  Note:In decryption process you should follow the reverse steps of the encryption process.

19.  Build and run the application.

20.  Type any string in the PlainRichTextBoxand click Encrypt button this will display the list of certificates installed in the current user as in the following image:

X509Certificate_01
X509Certificate_01

21.   Clear the PlainRichTextBox and click Decrypt this will decrypt the Text in CipherRichTextBox and display the original text in PlainRichTextBox

X509Certificate_01

Now you have an application that Encrypt and Decrypt your data with X509 Certificates.

(83) Comments

Blog Message amoxil canada

nice site http://antibioticanada.com amoxil


Blog Message amoxil canada

thank you http://antibioticanada.com antibiotic for uti


Blog Message order levitra

comment3, http://buyprednisonepharm.bid/ prednisone side effects, 866, http://buylevitrapharm.bid/ levitra side effects, 64016, http://buycialispharm.bid/ Cialis, gvjfh,


Blog Message best place to buy viagra online

comment1, http://buykamagrapharm.bid/ kamagra oral jelly amazon, %P, http://buylevitrapharm.bid/ levitra online, 4099, http://buycialispharm.bid/ cialis sale, gqdyl,


Blog Message Cialis

comment3, http://buyviagrapharm.bid/ buy real viagra online, prfao, http://buylevitrapharm.bid/ levitra 20 mg reviews, >:],


Blog Message kamagra oral jelly cvs

comment5, http://buyviagrapharm.bid/ buy viagra online, =]], http://buykamagrapharm.bid/ order kamagra, sdarin,


Blog Message cytotec

comment6, http://cytotecon.review/ buy cytotec, guyqdn,


Blog Message bargain cialis

comment6, http://canadapharm.review/ canadian pharmacy online, :-]]],


Blog Message generic viagra

comment5, http://tadalafil365.bid/ order Cialis, =-(((,


Blog Message buy viagra

comment1, http://canadapharm.review/ canadian online pharmacy, gmf,


Blog Message cialis coupon

comment5, http://silden24.com/ viagra online, :((,


Blog Message buy cialis

comment2, http://tadal24.com/ Cialis, 45634,


Blog Message bargain cialis

comment4, http://silden24.com/ buy viagra without doctor prescription, %(,


Blog Message bargain cialis

comment6, http://tadal24.com/ http://tadal24.com, 793292,


Blog Message buy cialis generic tadalafil

comment6, http://buyviagra24ph.com buy viagra canada, eem,

First Previous 1 2 3 4 5 6 Next Last 
Rating
Name
Email
Comment