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.
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- using DataAccessBlock;
- using System.Security.Cryptography;
- using System.Configuration;
- using System.Data.SqlClient;
- using Microsoft.SqlServer.Management.Common;
- using Microsoft.SqlServer.Management.Smo;
- using System.IO;
- namespace EnCryptDecrypt {
- public partial class frmMain: Form {
- #region Variables
- for Encryption / Decryption
- private static string Key = "cs techno private ltd1.,";
- private static string sIV = "cstechno";
- private static Encryption.EncryptionAlgorithm EncryptionType = Encryption.EncryptionAlgorithm.TripleDes;#
- endregion
- public frmMain() {
- InitializeComponent();
- }
- private void btnEncrypt_Click(object sender, EventArgs e) {
- if (txtClearText.Text == "") {
- error.SetError(txtClearText, "Enter the text you want to encrypt");
- } else {
- error.Clear();
- string sPlainText = txtClearText.Text.Trim();
- string cipherText = Encrpyt(sPlainText);
- txtCipherText.Text = cipherText;
- btnDecrypt.Enabled = true;
- }
- }
- public static string Encrpyt(string sPlainText) {
- try {
- return DataAccessBlock.DataAccess.Encrpyt(sPlainText, Key, sIV, EncryptionType);
- } catch (Exception ex) {
- throw new Exception("BusinessGroup :: Encrypt ::Error occured.", ex);
- }
- }
- public static string Decrypt(string sCipherText) {
- try {
- return DataAccessBlock.DataAccess.Decrypt(sCipherText, Key, sIV, EncryptionType);
- } catch (Exception ex) {
-
- MessageBox.Show("not an encrypted value");
- return "";
- }
- }
- private void btnDecrypt_Click(object sender, EventArgs e) {
-
- if (txtCipherText.Text == "") {
- error.SetError(txtCipherText, "Enter the text you want to encrypt");
- } else {
- lblPassword.Visible = true;
- string sCipherText = txtCipherText.Text.Trim();
- string decryptedText = Decrypt(sCipherText);
- txtClearText.Text = decryptedText;
- }
- }
- private void frmMain_Load(object sender, EventArgs e) {
- lblMsg.Visible = false;
- }
- private void btnDecrypt1_Click(object sender, EventArgs e) {
- if (txtConString.Text == "") {
- error.SetError(txtConString, "Enter the text you want to encrypt");
- } else {
- string connectionString = txtConString.Text;
- DataTable tables = new DataTable("Tables");
- using(SqlConnection connection = new SqlConnection(connectionString)) {
- using(SqlCommand command = connection.CreateCommand()) {
- command.CommandText = "select Password,UserID from Users";
- connection.Open();
- tables.Load(command.ExecuteReader(CommandBehavior.CloseConnection));
- }
- foreach(DataRow row in tables.Rows) {
- if (row[0] != null) {
- using(SqlConnection connection1 = new SqlConnection(connectionString)) {
- for (int i = 0; i < tables.Rows.Count; i++) {
- string decryptedPwd = Decrypt(tables.Rows[i]["Password"].ToString());
- using(SqlCommand command = connection1.CreateCommand()) {
- command.CommandText = "update users set password='" + decryptedPwd + "' where UserID= '" + tables.Rows[i]["UserID"].ToString() + "' ";
- connection1.Open();
- command.ExecuteNonQuery();
- lblMsg.Visible = true;
- lblMsg.Text = "Congratulations!You have Successfully Decrypted all fields";
- connection1.Close();
- }
- }
- }
- }
- }
- }
- }
- }
- private void btnEncrypt1_Click(object sender, EventArgs e) {
- if (txtConString.Text == "") {
- error.SetError(txtConString, "Enter the text you want to encrypt");
- } else {
- string connectionString = txtConString.Text;
- DataTable tables = new DataTable("Tables");
- using(SqlConnection connection = new SqlConnection(connectionString)) {
- using(SqlCommand command = connection.CreateCommand()) {
- command.CommandText = "select Password,UserID from Users";
- connection.Open();
- tables.Load(command.ExecuteReader(CommandBehavior.CloseConnection));
- }
- foreach(DataRow row in tables.Rows) {
- if (row[0] != null) {
- using(SqlConnection connection1 = new SqlConnection(connectionString)) {
- for (int i = 0; i < tables.Rows.Count; i++) {
- string decryptedPwd = Encrpyt(tables.Rows[i]["Password"].ToString());
- using(SqlCommand command = connection1.CreateCommand()) {
- command.CommandText = "update users set password='" + decryptedPwd + "' where UserID= '" + tables.Rows[i]["UserID"].ToString() + "' ";
-
- connection1.Open();
- command.ExecuteNonQuery();
- lblMsg.Visible = true;
- lblMsg.Text = "Congratulations!You have Successfully Encrpytted all fields";
- connection1.Close();
- }
- }
- }
- }
- }
- }
- }
- }
- private void btnClear_Click(object sender, EventArgs e) {
- error.Clear();
- txtClearText.Visible = true;
- lblPassword.Visible = true;
- txtCipherText.Text = "";
- txtClearText.Text = "";
- txtClearText.Enabled = true;
- }
- private void btnClear1_Click(object sender, EventArgs e) {
- error.Clear();
- txtConString.Text = "";
- cmbTables.Text = "";
- cmbTables.Items.Clear();
- cmbColumns.Text = "";
- lblMsg.Visible = false;
- cmbColumns.Items.Clear();
- }
- private void btnGetTables_Click(object sender, EventArgs e) {
- try {
- if (txtConString.Text == "") {
- error.SetError(txtConString, "Enter the Correct Connectionstring");
- } else {
- string connectionString = txtConString.Text;
- DataTable tables = new DataTable("Tables");
- using(SqlConnection connection = new SqlConnection(connectionString)) {
- using(SqlCommand command = connection.CreateCommand()) {
- command.CommandText = "select table_name as Name from INFORMATION_SCHEMA.Tables where TABLE_TYPE = 'BASE TABLE'";
- connection.Open();
- tables.Load(command.ExecuteReader(CommandBehavior.CloseConnection));
- }
- }
- foreach(DataRow row in tables.Rows) {
- cmbTables.Items.Add(row[0].ToString());
- }
- }
- } catch {
- error.SetError(txtConString, "Enter the Correct Connectionstring");
- }
- }
- private void btnGetColumns_Click(object sender, EventArgs e) {
- if (cmbTables.Text == "") {
- error.SetError(cmbTables, "Select the Correct Column");
- } else {
- string connectionString = txtConString.Text;
- DataTable tables = new DataTable("Tables");
- using(SqlConnection connection = new SqlConnection(connectionString)) {
- using(SqlCommand command = connection.CreateCommand()) {
- command.CommandText = "select column_name as Name from INFORMATION_SCHEMA.Columns where TABLE_NAME = 'Users'";
- connection.Open();
- tables.Load(command.ExecuteReader(CommandBehavior.CloseConnection));
- }
- }
- foreach(DataRow row in tables.Rows) {
- cmbColumns.Items.Add(row[0].ToString());
- }
- }
- }
- private void button1_Click(object sender, EventArgs e) {
- string[] strArConString;
- string strConnectionstring = string.Empty;
- if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
- string strFilevalue;
- strFilevalue = File.ReadAllText(openFileDialog1.FileName);
- strArConString = strFilevalue.Split('<', '>');
- for (int i = 0; i < strArConString.Length; i++) {
- if (strArConString[i] == "ConnectionString") {
- strConnectionstring = strArConString[i + 1];
- break;
- }
- }
- txtConString.Text = strConnectionstring;
- }
- }
- private void txtClearText_TextChanged(object sender, EventArgs e) {}
- }
- }
Step 6: Now include t the CryptorEngine.cs file.
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Security.Cryptography;
- using System.Configuration;
- namespace EnCryptDecrypt {
- public class CryptorEngine {
-
-
-
-
-
-
- public static string Encrypt(string toEncrypt, bool useHashing) {
- byte[] keyArray;
- byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
- System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
-
- string key = (string) settingsReader.GetValue("SecurityKey", typeof(String));
-
- if (useHashing) {
- MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
- keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
- hashmd5.Clear();
- } else keyArray = UTF8Encoding.UTF8.GetBytes(key);
- TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
- tdes.Key = keyArray;
- tdes.Mode = CipherMode.ECB;
- tdes.Padding = PaddingMode.PKCS7;
- ICryptoTransform cTransform = tdes.CreateEncryptor();
- byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
- tdes.Clear();
- return Convert.ToBase64String(resultArray, 0, resultArray.Length);
- }
-
-
-
-
-
-
- public static string Decrypt(string cipherString, bool useHashing) {
- byte[] keyArray;
- byte[] toEncryptArray = Convert.FromBase64String(cipherString);
- System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
-
- string key = (string) settingsReader.GetValue("SecurityKey", typeof(String));
- if (useHashing) {
- MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
- keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
- hashmd5.Clear();
- } else keyArray = UTF8Encoding.UTF8.GetBytes(key);
- TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
- tdes.Key = keyArray;
- tdes.Mode = CipherMode.ECB;
- tdes.Padding = PaddingMode.PKCS7;
- ICryptoTransform cTransform = tdes.CreateDecryptor();
- byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
- tdes.Clear();
- return UTF8Encoding.UTF8.GetString(resultArray);
- }
- }
- }
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.