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.

(120) Comments

Blog Message http://unity.ng/bbnaija-star-bisola-looks-so-beautiful-in-native-attire/

There as certainly a great deal to know about this subject. I really like all of the points you ave made.


Blog Message http://askhealthmd.com

Very informative article.Really thank you! Really Cool.


Blog Message https://healthfactsjournal.com/cbd-oil-for-anxiety/

wow, awesome blog post.Much thanks again. Will read on...


Blog Message https://www.fiverr.com/mahmudulhossain

A big thank you for your blog article.Really thank you! Really Cool.


Blog Message http://homepages.sapo.pt/guestbooks/lrcomercial.com.sapo.pt/guestbook.php?displayBegin=2

Some genuinely nice stuff on this website , I enjoy it.


Blog Message http://www.Khotana.com

I truly appreciate this blog article.Thanks Again. Fantastic.


Blog Message http://cyclingwithme.net/

Real wonderful info can be found on blog.


Blog Message http://www.coccoliomc.it/index.php?option=com_k2&view=itemlist&task=user&id=343925

Thanks , I ave recently been searching for information approximately this subject for a long


Blog Message http://kess.in/findmorehere28882

This particular blog is without a doubt cool and also informative. I have picked up a lot of handy tips out of it. I ad love to go back again and again. Thanks a bunch!


Blog Message https://www.vena.co.il

I visited a lot of website but I believe this one holds something special in it in it


Blog Message http://closestdispensaries.com/

There is evidently a bundle to realize about this. I assume you made certain nice points in features also.


Blog Message https://www.worldinternetfreedom.org

I was recommended this web site by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my trouble. You are amazing! Thanks!


Blog Message http://closestdispensaries.com/

I'а†ve read some just right stuff here. Certainly worth bookmarking for revisiting. I surprise how so much attempt you put to make the sort of excellent informative website.


Blog Message http://quote.insurancetruck.com/saratoga-texas-tx-commercial-truck-insurance-for-agents/

There as certainly a great deal to learn about this topic. I love all of the points you made.


Blog Message https://lividlighting.com.au/

Im grateful for the article post.Really looking forward to read more. Will read on...

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