This tutorial will show you how to write a method that will not only encrypt a string – but decrypt it as well. Written with VS.NET 2008 and VB.NET
This example was created with Visual Studio .NET 2008 but the results can be achieved in 2005 also.

Having the ability to encrypt data is extremely useful, as we often deal with sensitive material. In this tutorial, you will learn how to write a method that will both encrypt and decrypt a string. We will be creating a Windows Form that will allow us to enter a string into a textbox and encrypt it, then decrypt it back to the original string.

The first thing we will do is to create a new project, and add the following controls to the form: Two labels, two textboxes, and two buttons. Each one of these controls is for the encryption, one for the decryption. We will set the visibility of the decryption controls to false – we will make them visible when the encrypt button is clicked.

Once we have our controls in place, we will write our method:

This is a relatively simple string encryption, as it performs an ASCii character swap – it is not intended for highly-sensitive data.
The method parses the string character by character, and adds to the ASCii value of each character. The IF statement checks to see if the string has already been encrypted, as the same method performs both encryption and decryption. If it has already been encrypted, the method reverses the process (subtracts for the ASCii value of each character.

We utilize this method in our Form like so:

When the Encrypt button is clicked, we make visible the decryption controls, and call the encryption method, and assign the returned value to the decrypt textbox. This allows the user to just click the decrypt button to decrypt the string. We also set the original textbox value to nothing.

We can do the same for the decrypt button click, as the method itself will recognize if the string needs to be encrypted or decrypted:

We use the same structure as before, but we hide the decrypt controls again, and assign the method return value to the original textbox – the encrypted string will be decrypted, and the original text shown in the original textbox as before.

The entire code-behind will look something like this:

Download Source Files