Advanced Encryption Standard (AES) In C#

This article will teach you about Advanced Encryption Standard (AES) in C #. I think I will start a small series using some cryptography with AES in C #. Cryptography and Encryption are used by most developers who work with enterprise applications, especially if you work in the financial services industry. You can try to decrypt C# examples and aes encrypt C# examples at the end of the article step by step.
 
Cryptography is an interesting subject and the design of this algorithm is very interesting; I do not recommend using an algorithm that you have designed yourself. The algorithm in practice has now been analyzed many times by experts in both private and government industries around the world who are trying to find faults and weaknesses, so you are far better off using this recommended system.
 
The main algorithms fall into two categories: Symmetric encryption and Asymmetric encryption. Symmetric encryption contains algorithms that are based solely on an encryption key. For example, if you encrypt some plaintext with Key1 you get a cipher text out the other end. If you then decrypt the cipher text with the same key (Key1) you will get back to the original plaintext.
 
Asymmetric encryption works by having 2 keys, a public and private key. These keys are mathematically derived from each other. The public key can be used by anyone and the private key has to be kept secret. I will talk about asymmetric encryption and more specifically RSA in another post.
 
For this article I am going to look at the AES symmetric algorithm. AES stands for the Advanced Encryption Standard. This was a competition winner when the National Institute of Standards and Technology ran a contest to replace the already broken DES algorithm.
 
What I will show in this article is a good practical implementation of AES in .NET. We will start with the following interface. The interface contains 2 methods, Encrypt and Decrypt. They methods take cipher text/plaintext and an encryption key. For example: AES_DECRYPT(fieldname, "yourkey")
 
In this tutorial we will practice examples of Decryption and Encryption using inserting and selection methods in Mysql. We will insert data from .Net to Mysql with Encryption and select data from Mysql with decryption.
 
Let’s following the steps for learning about Encryption and Decryption with AES:
  1. Create database in mysql with the name “test” and create a table with the name “title”. See below for an example.

Advanced Encryption Standard (AES) In C#
  1. Create a new application project. In Visual Studio, on the menu click File> New > Project. For more details, see the following menu on the display.
Advanced Encryption Standard (AES) In C#

  1. Then the New Project will appear, as below. 

Advanced Encryption Standard (AES) In C#

  1. Write down the name of the project that will be created on a field name. Specify the directory storage project by accessing the field Location. Next, give the name of the solution in the Solution Name. Then click OK.
Advanced Encryption Standard (AES) In C#

  1. Create a new windows form like the below.

Advanced Encryption Standard (AES) In C#

Create a new class for connecting the database and write the following program listing :
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using MySql.Data.MySqlClient;  
  6. using System.Windows.Forms;  
  7. using System.Data;  
  8.   
  9. namespace Ecnryption_Decryption  
  10. {  
  11.     class connection  
  12.     {  
  13.           
  14.         MySql.Data.MySqlClient.MySqlConnection conn;  
  15.         string myConnectionString;  
  16.         static string host = "localhost";  
  17.         static string database = "test";  
  18.         static string userDB = "root";  
  19.         static string password = "password";  
  20.         public static string strProvider = "server=" + host + ";Database=" + database + ";User ID=" + userDB + ";Password=" + password;  
  21.   
  22.   
  23.         public bool Open()  
  24.         {  
  25.             try  
  26.             {  
  27.                 strProvider = "server=" + host + ";Database=" + database + ";User ID=" + userDB + ";Password=" + password;  
  28.                 conn = new MySqlConnection(strProvider);  
  29.                 conn.Open();  
  30.                 return true;  
  31.             }  
  32.             catch (Exception er)  
  33.             {  
  34.                 MessageBox.Show("Connection Error ! " + er.Message, "Information");  
  35.             }  
  36.             return false;  
  37.         }  
  38.   
  39.         public void Close()  
  40.         {  
  41.             conn.Close();  
  42.             conn.Dispose();  
  43.         }  
  44.   
  45.         public DataSet ExecuteDataSet(string sql)  
  46.         {  
  47.             try  
  48.             {  
  49.                 DataSet ds = new DataSet();  
  50.                 MySqlDataAdapter da = new MySqlDataAdapter(sql, conn);  
  51.                 da.Fill(ds, "result");  
  52.                 return ds;  
  53.             }  
  54.             catch (Exception ex)  
  55.             {  
  56.                 MessageBox.Show(ex.Message);  
  57.             }  
  58.             return null;  
  59.         }  
  60.   
  61.         public MySqlDataReader ExecuteReader(string sql)  
  62.         {  
  63.             try  
  64.             {  
  65.                 MySqlDataReader reader;  
  66.                 MySqlCommand cmd = new MySqlCommand(sql, conn);  
  67.                 reader = cmd.ExecuteReader();  
  68.                 return reader;  
  69.             }  
  70.             catch (Exception ex)  
  71.             {  
  72.                 MessageBox.Show(ex.Message);  
  73.             }  
  74.             return null;  
  75.         }  
  76.   
  77.         public int ExecuteNonQuery(string sql)  
  78.         {  
  79.             try  
  80.             {  
  81.                 int affected;  
  82.                 MySqlTransaction mytransaction = conn.BeginTransaction();  
  83.                 MySqlCommand cmd = conn.CreateCommand();  
  84.                 cmd.CommandText = sql;  
  85.                 affected = cmd.ExecuteNonQuery();  
  86.                 mytransaction.Commit();  
  87.                 return affected;  
  88.             }  
  89.             catch (Exception ex)  
  90.             {  
  91.                 MessageBox.Show(ex.Message);  
  92.             }  
  93.             return -1;  
  94.         }  
  95.     }  

In the next step, go back to the windows form and view code to write the following program listing:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using MySql.Data.MySqlClient;  
  10. using System.Data;  
  11. using System.Collections;  
  12.   
  13. namespace Ecnryption_Decryption  
  14. {  
  15.     public partial class Form1 : Form  
  16.     {  
  17.         connection con = new connection();  
  18.   
  19.         //arraylist to getter and setter data  
  20.         private static ArrayList ListID = new ArrayList();  
  21.         private static ArrayList ListName = new ArrayList();  
  22.         private static ArrayList Listtitle = new ArrayList();  
  23.         private static ArrayList ListAddress = new ArrayList();  
  24.   
  25.         public Form1()  
  26.         {  
  27.             InitializeComponent();  
  28.         }  
  29.   
  30.         private void Form1_Load(object sender, EventArgs e)  
  31.         {  
  32.             GetData();  
  33.             updateDatagrid();  
  34.         }  
  35.   
  36.         private void GetData()  
  37.         {  
  38.             try  
  39.             {  
  40.                 con.Open();  
  41.                 string query = "select id as id,AES_DECRYPT(name,'camellabs.com') as name,AES_DECRYPT(title,'camellabs.com') as title,AES_DECRYPT(address,'camellabs.com') as address from title";  
  42.   
  43.                 //MySqlDataReader row;  
  44.                 MySqlDataReader row;  
  45.                 row = con.ExecuteReader(query);  
  46.                 if (row.HasRows)  
  47.                 {  
  48.                     while (row.Read())  
  49.                     {  
  50.                         ListID.Add(row["id"].ToString());  
  51.                         ListName.Add(row["name"].ToString());  
  52.                         Listtitle.Add(row["title"].ToString());  
  53.                         ListAddress.Add(row["address"].ToString());  
  54.                     }  
  55.                 }  
  56.                 else  
  57.                 {  
  58.                     MessageBox.Show("Data not found");  
  59.                 }  
  60.   
  61.                 con.Close();  
  62.             }  
  63.             catch (Exception err)  
  64.             {  
  65.                 MessageBox.Show(err.ToString());  
  66.             }  
  67.   
  68.         }  
  69.   
  70.         private void button1_Click(object sender, EventArgs e)  
  71.         {  
  72.             try  
  73.             {  
  74.                 con.Open();  
  75.                 string query = "insert into title (name,title,address) values(AES_ENCRYPT('" + textBox1.Text + "','camellabs.com'),AES_ENCRYPT('" + textBox2.Text + "','camellabs.com'),AES_ENCRYPT('" + textBox3.Text + "','camellabs.com'))";  
  76.                 int hasil = con.ExecuteNonQuery(query);  
  77.                 if (hasil > 0)  
  78.                 {  
  79.                     MessageBox.Show("Data has been save Success");  
  80.                     clearList();  
  81.                     GetData();  
  82.                     updateDatagrid();  
  83.                 }  
  84.                 else  
  85.                 {  
  86.                     MessageBox.Show("Failed to saving data");  
  87.                 }  
  88.   
  89.                 con.Close();  
  90.             }  
  91.             catch (Exception err)  
  92.             {  
  93.                 MessageBox.Show(err.ToString());  
  94.             }  
  95.         }  
  96.   
  97.         private void updateDatagrid()  
  98.         {  
  99.             dataGridView1.Rows.Clear();  
  100.             for (int i = 0; i < ListID.Count; i++)  
  101.             {  
  102.                 DataGridViewRow newRow = new DataGridViewRow();  
  103.   
  104.                 newRow.CreateCells(dataGridView1);  
  105.                 newRow.Cells[0].Value = ListID[i];  
  106.                 newRow.Cells[1].Value = ListName[i];  
  107.                 newRow.Cells[2].Value = Listtitle[i];  
  108.                 newRow.Cells[3].Value = ListAddress[i];  
  109.                 dataGridView1.Rows.Add(newRow);  
  110.             }  
  111.         }  
  112.   
  113.         private void clearList()  
  114.         {  
  115.             ListID.Clear();  
  116.             ListName.Clear();  
  117.             Listtitle.Clear();  
  118.             ListAddress.Clear();  
  119.         }  
  120.          
  121.     }  

After you write down the program listings, press the F5 key to run the program and if you're successful connect your database. The result is: 

Advanced Encryption Standard (AES) In C#

Advanced Encryption Standard (AES) In C#
 
You can see Advanced Encryption Standard (AES) in C# from Github project in Here.
 
Thank you for reading this article about Advanced Encryption Standard (AES) in C#, I hope this article is useful for you. Visit My Github about .Net Csharp  here.


Recommended Free Ebook
Similar Articles