Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Simple AES Encryption using C#

0.00/5 (No votes)
28 Feb 2019 2  
A short and easy text (file) encryption

Sample Image - maximum width is 600 pixels

Introduction

This is a very simple encryption tool written in C# as a Windows Form project. It uses AES symmetric encryption based on a password provided by the user.

I created the tool because I needed some very simple and fast solution for encryption of textual files, opposed to tools found throughout the Internet that are frequently more comprehensive and complex.

One important note – the tool does not actually encrypt the file itself, but rather the text inside a textual file. The encrypted text can be then saved as another text file.

Solution

The tool consists of a single, simple form, as shown in the picture below:

SimpleEncrypt form

The upperhand textbox is used for the path to a file that we want to encrypt/decrypt. This box is filled using the Browse button that will open an OpenFileDialog. The text file is opened automatically in the RichTextBox below.

The password is entered in the textbox marked „Password“. Clicking on the Encrypt button will cause the text in the RichTextBox to be immediately encrypted, and Decrypt button will decrypt it (return it back to the original).

The decryption of already encrypted files works in a same way – the file is opened via the Browse button and loaded into Richtextbox – then the user needs to enter the password which was used to encrypt the original file (text), and click on Decrypt – and the original text will appear in the RichTextBox.

Also, an arbitrary text can be entered manually into Richtextbox, or the original text can be changed before the encryption.

The current state of the Richtextbox (be it encrypted or decrypted version of the text) can be saved by using the Save as button. You can choose to save it over the existing or to a new file.

The button Delete original is used to delete the original file (that was opened using the Browse button).

Using the Code

The code is basically only in one file, the Form1.cs, and consists of 5 button click handlers. I will describe only the part where the actual encryption and decryption take place.

Encryption

private void Encrypt_Click(object sender, EventArgs e)
     {
         if (textBoxPassword.Text == "") return;
         byte[] bytes = Encoding.Unicode.GetBytes(richTextBox1.Text);
         //Encrypt
         SymmetricAlgorithm crypt = Aes.Create();
         HashAlgorithm hash = MD5.Create();
         crypt.BlockSize = BlockSize;
         crypt.Key = hash.ComputeHash(Encoding.Unicode.GetBytes(textBoxPassword.Text));
         crypt.IV = IV;

         using (MemoryStream memoryStream = new MemoryStream())
         {
             using (CryptoStream cryptoStream =
                new CryptoStream(memoryStream, crypt.CreateEncryptor(), CryptoStreamMode.Write))
             {
                 cryptoStream.Write(bytes, 0, bytes.Length);
             }

             richTextBox1.Text = Convert.ToBase64String(memoryStream.ToArray());
         }
     }

This method initializes AES SymmetricAlgorithm and MD5 HashAlgorithm objects.

The AES object is used to encrypt the text from the Richtextbox (which first has to be converted to byte array).

The MD5 object is used to create an MD5 hash from the provided password, to be able to use it as a symmetrical key, since the AES algorithm uses a 16-byte encryption key (minimum key size for AES is 128 bit) – this will ensure that we shall get a unique (1 : 1) 16 byte representation of the user's password.

IV (Initialization vector) and BlockSize for the AES algorithm are set as fixed values in global variables:

private byte[] IV = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
private int BlockSize = 128;

To do the encryption itself, we must use the CryptoStream object, which uses an Encryptor created using the previously set up Aes symmetric algorithm. The CryptoStream takes the original byte array and sends encrypted bytes into a provided MemoryStream, which we then read and convert into Base64 string, so it could be readable.

The resulting encrypted text is written into the RichTextBox.

Decryption

private void Decrypt_Click(object sender, EventArgs e)
     {
         if (textBoxPassword.Text == "") return;
         //Decrypt
         byte[] bytes = Convert.FromBase64String(richTextBox1.Text);
         SymmetricAlgorithm crypt = Aes.Create();
         HashAlgorithm hash = MD5.Create();
         crypt.Key = hash.ComputeHash(Encoding.Unicode.GetBytes(textBoxPassword.Text));
         crypt.IV = IV;

         using (MemoryStream memoryStream = new MemoryStream(bytes))
         {
             using (CryptoStream cryptoStream =
                new CryptoStream(memoryStream, crypt.CreateDecryptor(), CryptoStreamMode.Read))
             {
                 byte[] decryptedBytes = new byte[bytes.Length];
                 cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length);
                 richTextBox1.Text = Encoding.Unicode.GetString(decryptedBytes);
             }
         }
     }

This method initializes Aes and MD5 objects the same way as Encrypt_Click method, but uses a reverse approach in order to decrypt the input string (byte array).

Since during encryption, we convert the encrypted string into Base64 string, now we need to revert back, so firstly, we convert FromBase64String into a byte array that is subsequently used as the input for the decryptor.

For the CryptoStream, this time, a decryptor object is created. CryptoStream will read the provided MemoryStream, decrypt the byte data and return the decrypted byte array into a provided variable.

Example

Decrypted text Encrypted text

History

  • 28th February, 2019: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here