Click here to Skip to main content
15,885,366 members
Articles / Programming Languages / C#
Article

Simple AES Encryption using C#

Rate me:
Please Sign up or sign in to vote.
3.65/5 (12 votes)
28 Feb 2019Public Domain3 min read 85K   3.7K   8   3
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

C#
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:

C#
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

C#
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, along with any associated source code and files, is licensed under A Public Domain dedication


Written By
User Interface Analyst Raiffeisenbank Austria
Croatia Croatia
I acquired Masters degree in computing science at the Faculty of Electrical Engineering and Computing in Zagreb, Croatia in 2009. Following my studies, I got a job in a Croatian branch of Austrian-based CEE Raiffeisen Bank as an MIS (Management information system) analyst.
I have been working there since 2010, as an IT expert within the Controlling department, maintaining the Oracle's OFSA system, underlying interfaces and databases.
Throughout that time, I have worked with several different technologies, which include SQL & PL/SQL (mostly), postgres, Cognos BI, Apparo, Datastage, ODI, Jenkins, Qlik, ...
I am doing a lot of automation with scripting in batch / shell and VBscript (mostly) - data analysis and processing, automated DB imports and exports, Jenkins automation etc.
Privately, I was mostly doing Windows Forms and Console app tools in Visual Studio, C#.

Comments and Discussions

 
QuestionMD5 ... Pin
Richard MacCutchan2-Mar-19 1:24
mveRichard MacCutchan2-Mar-19 1:24 
Questionmd5 collision Pin
evlncrn82-Mar-19 1:20
evlncrn82-Mar-19 1:20 
"ensure that we shall get a unique (1 : 1) 16 byte representation of the user's password."

isnt quite accurate, and with the potential for md5 collisions (diff passwords generating the same hash) the unique claim is wrong
QuestionNice, simple tutorial. Pin
SteveHolle28-Feb-19 3:32
SteveHolle28-Feb-19 3:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.