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:
- Create database in mysql with the name “test” and create a table with the name “title”. See below for an example.
- 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.
- Then the New Project will appear, as below.
- 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.
- Create a new windows form like the below.
Create a new class for connecting the database and write the following program listing :
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using MySql.Data.MySqlClient;
- using System.Windows.Forms;
- using System.Data;
-
- namespace Ecnryption_Decryption
- {
- class connection
- {
-
- MySql.Data.MySqlClient.MySqlConnection conn;
- string myConnectionString;
- static string host = "localhost";
- static string database = "test";
- static string userDB = "root";
- static string password = "password";
- public static string strProvider = "server=" + host + ";Database=" + database + ";User ID=" + userDB + ";Password=" + password;
-
-
- public bool Open()
- {
- try
- {
- strProvider = "server=" + host + ";Database=" + database + ";User ID=" + userDB + ";Password=" + password;
- conn = new MySqlConnection(strProvider);
- conn.Open();
- return true;
- }
- catch (Exception er)
- {
- MessageBox.Show("Connection Error ! " + er.Message, "Information");
- }
- return false;
- }
-
- public void Close()
- {
- conn.Close();
- conn.Dispose();
- }
-
- public DataSet ExecuteDataSet(string sql)
- {
- try
- {
- DataSet ds = new DataSet();
- MySqlDataAdapter da = new MySqlDataAdapter(sql, conn);
- da.Fill(ds, "result");
- return ds;
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- return null;
- }
-
- public MySqlDataReader ExecuteReader(string sql)
- {
- try
- {
- MySqlDataReader reader;
- MySqlCommand cmd = new MySqlCommand(sql, conn);
- reader = cmd.ExecuteReader();
- return reader;
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- return null;
- }
-
- public int ExecuteNonQuery(string sql)
- {
- try
- {
- int affected;
- MySqlTransaction mytransaction = conn.BeginTransaction();
- MySqlCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- affected = cmd.ExecuteNonQuery();
- mytransaction.Commit();
- return affected;
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- return -1;
- }
- }
- }
In the next step, go back to the windows form and view code to write the following program listing:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using MySql.Data.MySqlClient;
- using System.Data;
- using System.Collections;
-
- namespace Ecnryption_Decryption
- {
- public partial class Form1 : Form
- {
- connection con = new connection();
-
-
- private static ArrayList ListID = new ArrayList();
- private static ArrayList ListName = new ArrayList();
- private static ArrayList Listtitle = new ArrayList();
- private static ArrayList ListAddress = new ArrayList();
-
- public Form1()
- {
- InitializeComponent();
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- GetData();
- updateDatagrid();
- }
-
- private void GetData()
- {
- try
- {
- con.Open();
- 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";
-
-
- MySqlDataReader row;
- row = con.ExecuteReader(query);
- if (row.HasRows)
- {
- while (row.Read())
- {
- ListID.Add(row["id"].ToString());
- ListName.Add(row["name"].ToString());
- Listtitle.Add(row["title"].ToString());
- ListAddress.Add(row["address"].ToString());
- }
- }
- else
- {
- MessageBox.Show("Data not found");
- }
-
- con.Close();
- }
- catch (Exception err)
- {
- MessageBox.Show(err.ToString());
- }
-
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- try
- {
- con.Open();
- 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'))";
- int hasil = con.ExecuteNonQuery(query);
- if (hasil > 0)
- {
- MessageBox.Show("Data has been save Success");
- clearList();
- GetData();
- updateDatagrid();
- }
- else
- {
- MessageBox.Show("Failed to saving data");
- }
-
- con.Close();
- }
- catch (Exception err)
- {
- MessageBox.Show(err.ToString());
- }
- }
-
- private void updateDatagrid()
- {
- dataGridView1.Rows.Clear();
- for (int i = 0; i < ListID.Count; i++)
- {
- DataGridViewRow newRow = new DataGridViewRow();
-
- newRow.CreateCells(dataGridView1);
- newRow.Cells[0].Value = ListID[i];
- newRow.Cells[1].Value = ListName[i];
- newRow.Cells[2].Value = Listtitle[i];
- newRow.Cells[3].Value = ListAddress[i];
- dataGridView1.Rows.Add(newRow);
- }
- }
-
- private void clearList()
- {
- ListID.Clear();
- ListName.Clear();
- Listtitle.Clear();
- ListAddress.Clear();
- }
-
- }
- }
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:
You can see Advanced Encryption Standard (AES) in C# from Github project in
Here.