What Is Encryption/Decryption And How It Is Used In ASP.NET

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:

  • Privacy/confidentiality: Ensuring that no one can read the message, except the intended receiver.
  • Authentication: The process of proving one's identity.
  • Integrity: Assuring the receiver that the received message has not been altered in any way from the original.
  • Non-repudiation: A mechanism to prove that the sender really sent this message.
  • Key exchange: The method by which crypto keys are shared between the sender and receiver.

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

 

Up Next
    Ebook Download
    View all
    Learn
    View all