Encryption is the process of translating plain text data into something that appears to be random and meaningless. Decryption is the process of translating a random and meaningless data to plain text. Why do we need to use this encryption and decryption processes? In a Client -Server Application, security is a very important factor.

For example, when sending the confidential data such as password between the Client and Server, we need to make sure that the data is secured & protected.

By using this process, we can hide the original data and display some junk data. Based on this, we can provide some security for our data. For this, we are using the encryption and decryption techniques, which are done by using a technique called Cryptography.

Cryptography is the science of writing in the secret code and is an ancient art; the first document made use of cryptography in writing, which dates back to circa 1900 B.C.

Cryptography is necessary, when communicating over any an untrusted medium, which includes just about any network, particularly the Internet.

There are five primary functions of Cryptography which are:

In Cryptography, we start with the unencrypted data, referred to as a plaintext. Plaintext is encrypted into cipher text, which will in turn (usually) be decrypted into a usable plaintext.

The encryption and decryption is based upon the type of Cryptography scheme, being employed and some form of key. For those who like formulas, this process is sometimes written as:

C = Ek(P)
P = Dk(C)

Where P = plaintext, C = cipher text, E = the encryption method, D = the decryption method, and
k = the key.

Now, I am showing you an example Windows Application, which Uses encryption and decryption.

When we input an encrypted password, we will get the decrypted one.

Step 1: Open Visual Studio 2008.

Open Visual Studio

Step 2: Click "New Project" > "Windows" >"Windows Forms Application".
Step 3: Now, click Solution Explorer.

Solution Explorer

Step 4: frmMain.cs page will look like:

page

page

Step 5: Now, write the code, given below, in the frmMain.cs page.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using DataAccessBlock;
  9. using System.Security.Cryptography;
  10. using System.Configuration;
  11. using System.Data.SqlClient;
  12. using Microsoft.SqlServer.Management.Common;
  13. using Microsoft.SqlServer.Management.Smo;
  14. using System.IO;
  15. namespace EnCryptDecrypt
  16. {
  17. public partial class frmMain : Form
  18. {
  19. #region Variables for Encryption / Decryption
  20. private static string Key = "cs techno private ltd1.,";
  21. private static string sIV = "cstechno";
  22. private static Encryption.EncryptionAlgorithm EncryptionType = Encryption.EncryptionAlgorithm.TripleDes;
  23. #endregion
  24. public frmMain()
  25. {
  26. InitializeComponent();
  27. }
  28. private void btnEncrypt_Click(object sender, EventArgs e)
  29. {
  30. if (txtClearText.Text == "")
  31. {
  32. error.SetError(txtClearText, "Enter the text you want to encrypt");
  33. }
  34. else
  35. {
  36. error.Clear();
  37. string sPlainText = txtClearText.Text.Trim();
  38. string cipherText = Encrpyt(sPlainText);
  39. txtCipherText.Text = cipherText;
  40. btnDecrypt.Enabled = true;
  41. }
  42. }
  43. public static string Encrpyt(string sPlainText)
  44. {
  45. try
  46. {
  47. return DataAccessBlock.DataAccess.Encrpyt(sPlainText, Key, sIV, EncryptionType);
  48. }
  49. catch (Exception ex)
  50. {
  51. throw new Exception("BusinessGroup :: Encrypt ::Error occured.", ex);
  52. }
  53. }
  54. public static string Decrypt(string sCipherText)
  55. {
  56. try
  57. {
  58. return DataAccessBlock.DataAccess.Decrypt(sCipherText, Key, sIV, EncryptionType);
  59. }
  60. catch (Exception ex)
  61. {
  62. // throw new Exception("BusinessGroup :: Decrypt ::Error occured.", ex);
  63. MessageBox.Show("not an encrypted value");
  64. return "";
  65. }
  66. }
  67. private void btnDecrypt_Click(object sender, EventArgs e)
  68. {
  69. //txtClearText.Enabled = false;
  70. if (txtCipherText.Text == "")
  71. {
  72. error.SetError(txtCipherText, "Enter the text you want to encrypt");
  73. }
  74. else
  75. {
  76. lblPassword.Visible = true;
  77. string sCipherText = txtCipherText.Text.Trim();
  78. string decryptedText = Decrypt(sCipherText);
  79. txtClearText.Text = decryptedText;
  80. }
  81. }
  82. private void frmMain_Load(object sender, EventArgs e)
  83. {
  84. lblMsg.Visible = false;
  85. }
  86. private void btnDecrypt1_Click(object sender, EventArgs e)
  87. {
  88. if (txtConString.Text == "")
  89. {
  90. error.SetError(txtConString, "Enter the text you want to encrypt");
  91. }
  92. else
  93. {
  94. string connectionString = txtConString.Text;
  95. DataTable tables = new DataTable("Tables");
  96. using (SqlConnection connection = new SqlConnection(connectionString))
  97. {
  98. using (SqlCommand command = connection.CreateCommand())
  99. {
  100. command.CommandText = "select Password,UserID from Users";
  101. connection.Open();
  102. tables.Load(command.ExecuteReader(CommandBehavior.CloseConnection));
  103. }
  104. foreach (DataRow row in tables.Rows)
  105. {
  106. if (row[0] != null)
  107. {
  108. using (SqlConnection connection1 = new SqlConnection(connectionString))
  109. {
  110. for (int i = 0; i < tables.Rows.Count; i++)
  111. {
  112. string decryptedPwd = Decrypt(tables.Rows[i]["Password"].ToString());
  113. using (SqlCommand command = connection1.CreateCommand())
  114. {
  115. command.CommandText = "update users set password='" + decryptedPwd + "' where UserID= '" + tables.Rows[i]["UserID"].ToString() + "' ";
  116. connection1.Open();
  117. command.ExecuteNonQuery();
  118. lblMsg.Visible = true;
  119. lblMsg.Text = "Congratulations!You have Successfully Decrypted all fields";
  120. connection1.Close();
  121. }
  122. }
  123. }
  124. }
  125. }
  126. }
  127. }
  128. }
  129. private void btnEncrypt1_Click(object sender, EventArgs e)
  130. {
  131. if (txtConString.Text == "")
  132. {
  133. error.SetError(txtConString, "Enter the text you want to encrypt");
  134. }
  135. else
  136. {
  137. string connectionString = txtConString.Text;
  138. DataTable tables = new DataTable("Tables");
  139. using (SqlConnection connection = new SqlConnection(connectionString))
  140. {
  141. using (SqlCommand command = connection.CreateCommand())
  142. {
  143. command.CommandText = "select Password,UserID from Users";
  144. connection.Open();
  145. tables.Load(command.ExecuteReader(CommandBehavior.CloseConnection));
  146. }
  147. foreach (DataRow row in tables.Rows)
  148. {
  149. if (row[0] != null)
  150. {
  151. using (SqlConnection connection1 = new SqlConnection(connectionString))
  152. {
  153. for (int i = 0; i < tables.Rows.Count; i++)
  154. {
  155. string decryptedPwd = Encrpyt(tables.Rows[i]["Password"].ToString());
  156. using (SqlCommand command = connection1.CreateCommand())
  157. {
  158. command.CommandText = "update users set password='" + decryptedPwd + "' where UserID= '" + tables.Rows[i]["UserID"].ToString() + "' ";
  159. // command.CommandText = "update users set password='" + decryptedPwd + "' where UserID= '" + tables.Rows[i]["UserID"].ToString() + "' and password='" + Encrpyt(password) + "'";
  160. connection1.Open();
  161. command.ExecuteNonQuery();
  162. lblMsg.Visible = true;
  163. lblMsg.Text = "Congratulations!You have Successfully Encrpytted all fields";
  164. connection1.Close();
  165. }
  166. }
  167. }
  168. }
  169. }
  170. }
  171. }
  172. }
  173. private void btnClear_Click(object sender, EventArgs e)
  174. {
  175. error.Clear();
  176. txtClearText.Visible = true;
  177. lblPassword.Visible = true;
  178. txtCipherText.Text = "";
  179. txtClearText.Text = "";
  180. txtClearText.Enabled = true;
  181. }
  182. private void btnClear1_Click(object sender, EventArgs e)
  183. {
  184. error.Clear();
  185. txtConString.Text = "";
  186. cmbTables.Text = "";
  187. cmbTables.Items.Clear();
  188. cmbColumns.Text = "";
  189. lblMsg.Visible = false;
  190. cmbColumns.Items.Clear();
  191. }
  192. private void btnGetTables_Click(object sender, EventArgs e)
  193. {
  194. try
  195. {
  196. if (txtConString.Text == "")
  197. {
  198. error.SetError(txtConString, "Enter the Correct Connectionstring");
  199. }
  200. else
  201. {
  202. string connectionString = txtConString.Text;
  203. DataTable tables = new DataTable("Tables");
  204. using (SqlConnection connection = new SqlConnection(connectionString))
  205. {
  206. using (SqlCommand command = connection.CreateCommand())
  207. {
  208. command.CommandText = "select table_name as Name from INFORMATION_SCHEMA.Tables where TABLE_TYPE = 'BASE TABLE'";
  209. connection.Open();
  210. tables.Load(command.ExecuteReader(CommandBehavior.CloseConnection));
  211. }
  212. }
  213. foreach (DataRow row in tables.Rows)
  214. {
  215. cmbTables.Items.Add(row[0].ToString());
  216. }
  217. }
  218. }
  219. catch
  220. {
  221. error.SetError(txtConString, "Enter the Correct Connectionstring");
  222. }
  223. }
  224. private void btnGetColumns_Click(object sender, EventArgs e)
  225. {
  226. if (cmbTables.Text == "")
  227. {
  228. error.SetError(cmbTables, "Select the Correct Column");
  229. }
  230. else
  231. {
  232. string connectionString = txtConString.Text;
  233. DataTable tables = new DataTable("Tables");
  234. using (SqlConnection connection = new SqlConnection(connectionString))
  235. {
  236. using (SqlCommand command = connection.CreateCommand())
  237. {
  238. command.CommandText = "select column_name as Name from INFORMATION_SCHEMA.Columns where TABLE_NAME = 'Users'";
  239. connection.Open();
  240. tables.Load(command.ExecuteReader(CommandBehavior.CloseConnection));
  241. }
  242. }
  243. foreach (DataRow row in tables.Rows)
  244. {
  245. cmbColumns.Items.Add(row[0].ToString());
  246. }
  247. }
  248. }
  249. private void button1_Click(object sender, EventArgs e)
  250. {
  251. string[] strArConString;
  252. string strConnectionstring = string.Empty;
  253. if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  254. {
  255. string strFilevalue;
  256. strFilevalue= File.ReadAllText(openFileDialog1.FileName);
  257. strArConString = strFilevalue.Split('<','>');
  258. for (int i = 0; i < strArConString.Length; i++)
  259. {
  260. if (strArConString[i] == "ConnectionString")
  261. {
  262. strConnectionstring = strArConString[i + 1];
  263. break;
  264. }
  265. }
  266. txtConString.Text = strConnectionstring;
  267. }
  268. }
  269. private void txtClearText_TextChanged(object sender, EventArgs e)
  270. {
  271. }
  272. }
  273. }
Step 6: Now, include the CryptorEngine.cs file.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Security.Cryptography;
  5. using System.Configuration;
  6. namespace EnCryptDecrypt
  7. {
  8. public class CryptorEngine
  9. {
  10. /// <summary>
  11. /// Encrypt a string using dual encryption method. Return a encrypted cipher Text
  12. /// </summary>
  13. /// <param name="toEncrypt">string to be encrypted</param>
  14. /// <param name="useHashing">use hashing? send to for extra secirity</param>
  15. /// <returns></returns>
  16. public static string Encrypt(string toEncrypt, bool useHashing)
  17. {
  18. byte[] keyArray;
  19. byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
  20. System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
  21. // Get the key from config file
  22. string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
  23. //System.Windows.Forms.MessageBox.Show(key);
  24. if (useHashing)
  25. {
  26. MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
  27. keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
  28. hashmd5.Clear();
  29. }
  30. else
  31. keyArray = UTF8Encoding.UTF8.GetBytes(key);
  32. TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
  33. tdes.Key = keyArray;
  34. tdes.Mode = CipherMode.ECB;
  35. tdes.Padding = PaddingMode.PKCS7;
  36. ICryptoTransform cTransform = tdes.CreateEncryptor();
  37. byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
  38. tdes.Clear();
  39. return Convert.ToBase64String(resultArray, 0, resultArray.Length);
  40. }
  41. /// <summary>
  42. /// DeCrypt a string using dual encryption method. Return a DeCrypted clear string
  43. /// </summary>
  44. /// <param name="cipherString">encrypted string</param>
  45. /// <param name="useHashing">Did you use hashing to encrypt this data? pass true is yes</param>
  46. /// <returns></returns>
  47. public static string Decrypt(string cipherString, bool useHashing)
  48. {
  49. byte[] keyArray;
  50. byte[] toEncryptArray = Convert.FromBase64String(cipherString);
  51. System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
  52. //Get your key from config file to open the lock!
  53. string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
  54. if (useHashing)
  55. {
  56. MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
  57. keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
  58. hashmd5.Clear();
  59. }
  60. else
  61. keyArray = UTF8Encoding.UTF8.GetBytes(key);
  62. TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
  63. tdes.Key = keyArray;
  64. tdes.Mode = CipherMode.ECB;
  65. tdes.Padding = PaddingMode.PKCS7;
  66. ICryptoTransform cTransform = tdes.CreateDecryptor();
  67. byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
  68. tdes.Clear();
  69. return UTF8Encoding.UTF8.GetString(resultArray);
  70. }
  71. }
  72. }
Step 7

Output: Now, the output is:

Here, we enter an encrypted password “Rc3xvx8c7GM=” and click Decrypt button.

Decrypt

We will get the decrypted password as “a”.

decrypted password

We can also decrypt/encrypt the column of a database for any given connection string.

Database