This article will learn about Advanced Encryption Standard (AES) in C#. I thought I would start a little series into using some of cryptography with AES in C#. Cryptography and Encryption is something part that most developers working with enterprise applications will come across, in especially if you work in the financial services industry. You can try aes decrypt c# example and aes encrypt c# example in end the article with step by step.
Cryptography is a fascinating subject and design of these algorithms is very interesting, don’t recommend using an algorithm that you have designed yourself. Algorithms in practice now have been through lots of analysis by experts both in private industries and governments all around the world trying to find faults and weaknesses, so you are much better to using these recommended systems.
The main algorithms fall include 2 categories, There are 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 example Decrypt and Encrypt with inserting,selection methods in Mysql. We will insert data from .Net to Mysql with Encryption and selecting data from Mysql with decryption.
Let’s following this step for know about Encryption and Decryption with AES:
- Create database in mysql with name “test” and create table with name “title” ,look the below for 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 will appear the window New Project like the look 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 connection database and write the following program listing :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
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; } } } |
- Next step, Back to windows form and view code to write the following program listing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
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(); //arraylist to getter and setter data 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; 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 successfull connect your database the result is :
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 in Here