Encryption Decryption Software

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 random and meaningless data to plain text. Why we need to use this Encryption and decryption processes, because 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 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 Decryption techniques which is done by using a technique Called Cryptography.

Cryptography is the science of writing in secret code and is an ancient art; the first documented use of cryptography in writing dates back to circa 1900 B.C.Cryptography is necessary when communicating over any 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 sender and receiver.

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

The encryption and decryption is based upon the type of cryptography scheme being employed and some form of key. For those that 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.

         

Step 2: Then click on "New Project" > "Windows" >"Windows Forms Application".

Step 3: Now click on Solution Explorer.

Step 4: frmMain.cs page will look like this,

              

Step 5: Now write the code as 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.     public partial class frmMain: Form {  
  17.       #region Variables  
  18.         for Encryption / Decryption  
  19.         private static string Key = "cs techno private ltd1.,";  
  20.         private static string sIV = "cstechno";  
  21.         private static Encryption.EncryptionAlgorithm EncryptionType = Encryption.EncryptionAlgorithm.TripleDes;#  
  22.         endregion  
  23.         public frmMain() {  
  24.             InitializeComponent();  
  25.         }  
  26.         private void btnEncrypt_Click(object sender, EventArgs e) {  
  27.             if (txtClearText.Text == "") {  
  28.                 error.SetError(txtClearText, "Enter the text you want to encrypt");  
  29.             } else {  
  30.                 error.Clear();  
  31.                 string sPlainText = txtClearText.Text.Trim();  
  32.                 string cipherText = Encrpyt(sPlainText);  
  33.                 txtCipherText.Text = cipherText;  
  34.                 btnDecrypt.Enabled = true;  
  35.             }  
  36.         }  
  37.         public static string Encrpyt(string sPlainText) {  
  38.             try {  
  39.                 return DataAccessBlock.DataAccess.Encrpyt(sPlainText, Key, sIV, EncryptionType);  
  40.             } catch (Exception ex) {  
  41.                 throw new Exception("BusinessGroup :: Encrypt ::Error occured.", ex);  
  42.             }  
  43.         }  
  44.         public static string Decrypt(string sCipherText) {  
  45.             try {  
  46.                 return DataAccessBlock.DataAccess.Decrypt(sCipherText, Key, sIV, EncryptionType);  
  47.             } catch (Exception ex) {  
  48.                 // throw new Exception("BusinessGroup :: Decrypt ::Error occured.", ex);  
  49.                 MessageBox.Show("not an encrypted value");  
  50.                 return "";  
  51.             }  
  52.         }  
  53.         private void btnDecrypt_Click(object sender, EventArgs e) {  
  54.             //txtClearText.Enabled = false;  
  55.             if (txtCipherText.Text == "") {  
  56.                 error.SetError(txtCipherText, "Enter the text you want to encrypt");  
  57.             } else {  
  58.                 lblPassword.Visible = true;  
  59.                 string sCipherText = txtCipherText.Text.Trim();  
  60.                 string decryptedText = Decrypt(sCipherText);  
  61.                 txtClearText.Text = decryptedText;  
  62.             }  
  63.         }  
  64.         private void frmMain_Load(object sender, EventArgs e) {  
  65.             lblMsg.Visible = false;  
  66.         }  
  67.         private void btnDecrypt1_Click(object sender, EventArgs e) {  
  68.             if (txtConString.Text == "") {  
  69.                 error.SetError(txtConString, "Enter the text you want to encrypt");  
  70.             } else {  
  71.                 string connectionString = txtConString.Text;  
  72.                 DataTable tables = new DataTable("Tables");  
  73.                 using(SqlConnection connection = new SqlConnection(connectionString)) {  
  74.                     using(SqlCommand command = connection.CreateCommand()) {  
  75.                         command.CommandText = "select Password,UserID from Users";  
  76.                         connection.Open();  
  77.                         tables.Load(command.ExecuteReader(CommandBehavior.CloseConnection));  
  78.                     }  
  79.                     foreach(DataRow row in tables.Rows) {  
  80.                         if (row[0] != null) {  
  81.                             using(SqlConnection connection1 = new SqlConnection(connectionString)) {  
  82.                                 for (int i = 0; i < tables.Rows.Count; i++) {  
  83.                                     string decryptedPwd = Decrypt(tables.Rows[i]["Password"].ToString());  
  84.                                     using(SqlCommand command = connection1.CreateCommand()) {  
  85.                                         command.CommandText = "update users set password='" + decryptedPwd + "' where UserID= '" + tables.Rows[i]["UserID"].ToString() + "' ";  
  86.                                         connection1.Open();  
  87.                                         command.ExecuteNonQuery();  
  88.                                         lblMsg.Visible = true;  
  89.                                         lblMsg.Text = "Congratulations!You have Successfully Decrypted all fields";  
  90.                                         connection1.Close();  
  91.                                     }  
  92.                                 }  
  93.                             }  
  94.                         }  
  95.                     }  
  96.                 }  
  97.             }  
  98.         }  
  99.         private void btnEncrypt1_Click(object sender, EventArgs e) {  
  100.             if (txtConString.Text == "") {  
  101.                 error.SetError(txtConString, "Enter the text you want to encrypt");  
  102.             } else {  
  103.                 string connectionString = txtConString.Text;  
  104.                 DataTable tables = new DataTable("Tables");  
  105.                 using(SqlConnection connection = new SqlConnection(connectionString)) {  
  106.                     using(SqlCommand command = connection.CreateCommand()) {  
  107.                         command.CommandText = "select Password,UserID from Users";  
  108.                         connection.Open();  
  109.                         tables.Load(command.ExecuteReader(CommandBehavior.CloseConnection));  
  110.                     }  
  111.                     foreach(DataRow row in tables.Rows) {  
  112.                         if (row[0] != null) {  
  113.                             using(SqlConnection connection1 = new SqlConnection(connectionString)) {  
  114.                                 for (int i = 0; i < tables.Rows.Count; i++) {  
  115.                                     string decryptedPwd = Encrpyt(tables.Rows[i]["Password"].ToString());  
  116.                                     using(SqlCommand command = connection1.CreateCommand()) {  
  117.                                         command.CommandText = "update users set password='" + decryptedPwd + "' where UserID= '" + tables.Rows[i]["UserID"].ToString() + "' ";  
  118.                                         // command.CommandText = "update users set password='" + decryptedPwd + "' where UserID= '" + tables.Rows[i]["UserID"].ToString() + "' and password='" + Encrpyt(password) + "'";  
  119.                                         connection1.Open();  
  120.                                         command.ExecuteNonQuery();  
  121.                                         lblMsg.Visible = true;  
  122.                                         lblMsg.Text = "Congratulations!You have Successfully Encrpytted all fields";  
  123.                                         connection1.Close();  
  124.                                     }  
  125.                                 }  
  126.                             }  
  127.                         }  
  128.                     }  
  129.                 }  
  130.             }  
  131.         }  
  132.         private void btnClear_Click(object sender, EventArgs e) {  
  133.             error.Clear();  
  134.             txtClearText.Visible = true;  
  135.             lblPassword.Visible = true;  
  136.             txtCipherText.Text = "";  
  137.             txtClearText.Text = "";  
  138.             txtClearText.Enabled = true;  
  139.         }  
  140.         private void btnClear1_Click(object sender, EventArgs e) {  
  141.             error.Clear();  
  142.             txtConString.Text = "";  
  143.             cmbTables.Text = "";  
  144.             cmbTables.Items.Clear();  
  145.             cmbColumns.Text = "";  
  146.             lblMsg.Visible = false;  
  147.             cmbColumns.Items.Clear();  
  148.         }  
  149.         private void btnGetTables_Click(object sender, EventArgs e) {  
  150.             try {  
  151.                 if (txtConString.Text == "") {  
  152.                     error.SetError(txtConString, "Enter the Correct Connectionstring");  
  153.                 } else {  
  154.                     string connectionString = txtConString.Text;  
  155.                     DataTable tables = new DataTable("Tables");  
  156.                     using(SqlConnection connection = new SqlConnection(connectionString)) {  
  157.                         using(SqlCommand command = connection.CreateCommand()) {  
  158.                             command.CommandText = "select table_name as Name from INFORMATION_SCHEMA.Tables where TABLE_TYPE = 'BASE TABLE'";  
  159.                             connection.Open();  
  160.                             tables.Load(command.ExecuteReader(CommandBehavior.CloseConnection));  
  161.                         }  
  162.                     }  
  163.                     foreach(DataRow row in tables.Rows) {  
  164.                         cmbTables.Items.Add(row[0].ToString());  
  165.                     }  
  166.                 }  
  167.             } catch {  
  168.                 error.SetError(txtConString, "Enter the Correct Connectionstring");  
  169.             }  
  170.         }  
  171.         private void btnGetColumns_Click(object sender, EventArgs e) {  
  172.             if (cmbTables.Text == "") {  
  173.                 error.SetError(cmbTables, "Select the Correct Column");  
  174.             } else {  
  175.                 string connectionString = txtConString.Text;  
  176.                 DataTable tables = new DataTable("Tables");  
  177.                 using(SqlConnection connection = new SqlConnection(connectionString)) {  
  178.                     using(SqlCommand command = connection.CreateCommand()) {  
  179.                         command.CommandText = "select column_name as Name from INFORMATION_SCHEMA.Columns where TABLE_NAME = 'Users'";  
  180.                         connection.Open();  
  181.                         tables.Load(command.ExecuteReader(CommandBehavior.CloseConnection));  
  182.                     }  
  183.                 }  
  184.                 foreach(DataRow row in tables.Rows) {  
  185.                     cmbColumns.Items.Add(row[0].ToString());  
  186.                 }  
  187.             }  
  188.         }  
  189.         private void button1_Click(object sender, EventArgs e) {  
  190.             string[] strArConString;  
  191.             string strConnectionstring = string.Empty;  
  192.             if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {  
  193.                 string strFilevalue;  
  194.                 strFilevalue = File.ReadAllText(openFileDialog1.FileName);  
  195.                 strArConString = strFilevalue.Split('<''>');  
  196.                 for (int i = 0; i < strArConString.Length; i++) {  
  197.                     if (strArConString[i] == "ConnectionString") {  
  198.                         strConnectionstring = strArConString[i + 1];  
  199.                         break;  
  200.                     }  
  201.                 }  
  202.                 txtConString.Text = strConnectionstring;  
  203.             }  
  204.         }  
  205.         private void txtClearText_TextChanged(object sender, EventArgs e) {}  
  206.     }  
  207. }  

Step 6: Now include t 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.     public class CryptorEngine {  
  8.         /// <summary>  
  9.         /// Encrypt a string using dual encryption method. Return a encrypted cipher Text  
  10.         /// </summary>  
  11.         /// <param name="toEncrypt">string to be encrypted</param>  
  12.         /// <param name="useHashing">use hashing? send to for extra secirity</param>  
  13.         /// <returns></returns>  
  14.         public static string Encrypt(string toEncrypt, bool useHashing) {  
  15.                 byte[] keyArray;  
  16.                 byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);  
  17.                 System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();  
  18.                 // Get the key from config file  
  19.                 string key = (string) settingsReader.GetValue("SecurityKey"typeof(String));  
  20.                 //System.Windows.Forms.MessageBox.Show(key);  
  21.                 if (useHashing) {  
  22.                     MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();  
  23.                     keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));  
  24.                     hashmd5.Clear();  
  25.                 } else keyArray = UTF8Encoding.UTF8.GetBytes(key);  
  26.                 TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();  
  27.                 tdes.Key = keyArray;  
  28.                 tdes.Mode = CipherMode.ECB;  
  29.                 tdes.Padding = PaddingMode.PKCS7;  
  30.                 ICryptoTransform cTransform = tdes.CreateEncryptor();  
  31.                 byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);  
  32.                 tdes.Clear();  
  33.                 return Convert.ToBase64String(resultArray, 0, resultArray.Length);  
  34.             }  
  35.             /// <summary>  
  36.             /// DeCrypt a string using dual encryption method. Return a DeCrypted clear string  
  37.             /// </summary>  
  38.             /// <param name="cipherString">encrypted string</param>  
  39.             /// <param name="useHashing">Did you use hashing to encrypt this data? pass true is yes</param>  
  40.             /// <returns></returns>  
  41.         public static string Decrypt(string cipherString, bool useHashing) {  
  42.             byte[] keyArray;  
  43.             byte[] toEncryptArray = Convert.FromBase64String(cipherString);  
  44.             System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();  
  45.             //Get your key from config file to open the lock!  
  46.             string key = (string) settingsReader.GetValue("SecurityKey"typeof(String));  
  47.             if (useHashing) {  
  48.                 MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();  
  49.                 keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));  
  50.                 hashmd5.Clear();  
  51.             } else keyArray = UTF8Encoding.UTF8.GetBytes(key);  
  52.             TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();  
  53.             tdes.Key = keyArray;  
  54.             tdes.Mode = CipherMode.ECB;  
  55.             tdes.Padding = PaddingMode.PKCS7;  
  56.             ICryptoTransform cTransform = tdes.CreateDecryptor();  
  57.             byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);  
  58.             tdes.Clear();  
  59.             return UTF8Encoding.UTF8.GetString(resultArray);  
  60.         }  
  61.     }  
  62. }  

Step 7:

Output: Now the output is:

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

  

We will get the decrypted password as “a”

  

We can also Decrypt/encrypt the Column of a Database for any given Connection string.