Welcome to Ultra Developers.

the company that developes your success

Read Blog


How to: Encrypt and Decrypt your data with X509 Certificates using C#

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 EncryptToolStripButton and set its Text property to Encrypt.
  5. Add a ToolStripButton to the CertificateToolStrip and rename it to DecryptToolStripButton and set its Text property to Decrypt.
  6. Add a Label control to the CertificateForm and rename it to PlainLabel and set its Text property to Plain Text.
  7. Add a RichTextBox to the CertificateForm under the PlainLabel and rename it to PlainRichTextBox.
  8. Add a Label control to the CertificateForm and rename it to CipherLabel and set its Text property to Cipher Text.
  9. Add a RichTextBox to the CertificateForm under the CipherLabel and rename it to CipherRichTextBox.
  10. The CertificateForm should look like the following Image:

X509 Certificate

  1. Import the System.Security.Cryptography and System.Security.Cryptography.X509Certificates namespaces using the following statement:
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
  1. 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.
  2. 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.
  3. Double click the EncryptToolStripButton to create the Click Event Handler.
  4. 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);
    }
}
  1. In the above code:
    • 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.
    • Then we open the store with these options ReadOnly and OpenExistingOnly. The OpenFlags enumeration specifies the way to open the X.509 certificate store.
    • We create an instance of X509Certificate2Collection and name it certCollection that defines a collection that stores X509Certificate objects. We fill this collection with the certificates in the store we open earlier.
    • 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 X509FindType enumeration specifies the type of value the X509Certificate2Collection.Find method searches for.
    • We create an instance of X509Certificate2Collection and name it selectedcollection that will store the selected X509 Certificates from the X509Certificate2UI Dialog. The X509Certificate2UI displays user interface dialogs that allow users to select and view X.509 certificates.
    • We check if the user selects an X509 Certificate from the dialog or not.
    • Then we create an instance of the X509Certificate2. This represents an X509 certificate. And assign it to the certificate that the users selects from the X509Certificate2UI
    • We display some of the selected certificate data such as Subject, Issuer, Serial Number, and Friendly Name.
    • We call the certificate Verify method that performs a X.509 chain validation using basic validation policy.
    • 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).
    • We cast the X509 Certificate Private Key to rsaEncryptor.
    • We create a byte array that will store the encrypted data.
    • We call the RSACryptoServiceProvider Encrypt method and pass to it the binary representation of the Text in PlainRichTextBox. We use UTF8 encoding.
    • Then we convert the encrypted data to a base 64 string and display it in the CipherRichTextBox.
  2. Double click the DecryptToolStripButton to create the Click Event Handler.
  3. 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);
    }
}
  1. In the above code:
    • The code in the Decrypt button is the same as the Encrypt button except for the decryption process.
    • 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).
    • We cast the X509 Certificate Private Key to rsaEncryptor.
    • We create a byte array that will store the decrypted data.
    • 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.
    • Then we convert the decrypted data to a UTF8 string using UTF8 encoding and display it in the PlainRichTextBox.

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

  1. Build and run the application.
  2. Type any string in the PlainRichTextBox and click Encrypt button this will display the list of certificates installed in the current user as in the following image:

X509 Certificate

X509 Certificate

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

X509 Certificate

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

Similar Posts