enc_dec_x509_net

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 toCertificateToolStrip.

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

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

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

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

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

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

10. The CertificateForm should look like the following Image:

11. Import the System.Security.Cryptography andSystem.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 andOpenExistingOnly. The OpenFlagsenumeration specifies the way to open the X.509 certificate store.

c. We create an instance of X509Certificate2Collectionand name itcertCollection 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 itfoundCollection 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 itselectedcollection that will store the selected X509 Certificates from theX509Certificate2UI 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 itrsaEncryptor. 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 theCipherRichTextBox.

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 itrsaEncryptor. 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:

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

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

Source: http://www.makhaly.net/Blog/21