نحوه استفاده از Encryption و Decryption در ASP.Net
شنبه 6 شهریور 1395در این مقاله ، توضیحاتی در مورد encryption و decryption خواهیم داشت و درباره ی روش های این کار نیز توضیح مختصری را ارائه خواهیم داد . سپس با ارائه یک مثال ، و توضیح آن بصورت مرحله به مرحله روش های رمزگذاری و رمزگشایی را برای شما خواهیم گفت .
Encryption پردازشی است که طی آن یک داده متنی آشکار را به چیزی که random و بی معنی است ، تبدیل میکند . Decryption برعکس عمل Encryption است ، یعنی یک داده random و بی معنی را به یک داده متنی با معنی تبدیل می کند . ما چه نیازی به استفاده از پردازش های Encryption/Decryption داریم ؟ در برنامه های Client-Server امنیت فاکتور خیلی مهمی میباشد .
برای مثال ، زمانی که یک داده محرمانه همانند پسورد را بین Client و Server رد و بدل می کنیم ، ما باید به امنیت و حفاظت از داده مطمئن باشیم .
با استفاده از این پردازش ، ما میتوانیم داده اصلی را مخفی کرده و یکسری داده بی مصرف و آشغال را نمایش دهیم . بر این اساس ، کمی امنیت برای داده خود میتوانیم ایجاد کنیم . برای این کار ما از تکنیک
encryption و decryption استفاده می کنیم ، که این امر با استفاده از تکنیکی به نام Cryptography ، قابل انجام است .
Cryptography یک دانش درمورد نوشتن بصورت رمزی و کدگذاری شده است و این علم قدیمی و کهن می باشد.اولین مقاله ای که توسط Cryptography کدگذاری و نوشته شد،تقریبا بازمیگردد به تاریخ 1900قبل از میلاد مسیح .
در هنگام برقراری ارتباط از هر رسانه غیر قابل اعتماد ، که شامل هر شبکه ای، به ویژه اینترنت میشود ، Cryptography لازم و ضروری است .
در اینجا پنج تابع ابتدایی از Cryptography را داریم :
• Privacy/confidentiality : تضمین این امر که هیچکس غیر از شخص دریافت کننده مورد نظر ، توانایی خواندن پیام را ندارد .
• Authentication : روند اثبات هویت فرد
• Integrity : اطمینان گیرنده از این امر که ، پیامی که دریافت کرده است به هیچ وجه تفاوتی با پیام اصلی ندارد .
• Non-repudiation : مکانیزمی برای اینکه بفهمیم که شخص فرستنده واقعا این پیام را فرستاده است .
• Key exchange : روشی که کلید رمزنگاری بین فرستنده و گیرنده به اشتراک گذاشته میشود .
در Cryptography ، ما با داده های unencrypted ، به عنوان یک متن با معنی (Plaintext) ، شروع می کنیم . Plaintext با تبدیل به متن cipher رمزگذاری می شود . و برای رمزگشایی به یک Plaintext معمولی تبدیل می شود .
رمزگذاری و رمزگشایی بر اساس نوع ترفند Cryptography است .
(C = Ek(P
(P = Dk(C
که در آن ، P = plaintext, C = cipher text,
E = the encryption method,
D = the decryption method, and
k = the key می باشد .
حال ما ، یک مثال Windows Application را که از رمزگذاری و رمزگشایی استفاده کرده است ، نشان می دهیم .
زمانی که ما یک Password را رمزنگاری می کنیم ، یک رمزگشایی شده هم دریافت خواهیم کرد .
مرحله اول : visual studio را باز کنید .

مرحله دو : "New Project" > "Windows" >"Windows Forms Application"
مرحله سوم : حال ، روی Solution Explorer کلیک کنید .

مرحله چهارم : frmMain.cs شبیه زیر خواهد بود .


مرحله پنجم : حال ، کدهایی که در زیر داده شده است را در frmMain.cs قرار دهید .
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)
{
// throw new Exception("BusinessGroup :: Decrypt ::Error occured.", ex);
MessageBox.Show("not an encrypted value");
return "";
}
}
private void btnDecrypt_Click(object sender, EventArgs e)
{
//txtClearText.Enabled = false;
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() + "' ";
// command.CommandText = "update users set password='" + decryptedPwd + "' where UserID= '" + tables.Rows[i]["UserID"].ToString() + "' and password='" + Encrpyt(password) + "'";
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)
{
}
}
}
مرحله ششم : فایل CryptorEngine.cs .
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Configuration;
namespace EnCryptDecrypt
{
public class CryptorEngine
{
/// <summary>
/// Encrypt a string using dual encryption method. Return a encrypted cipher Text
/// </summary>
/// <param name="toEncrypt">string to be encrypted</param>
/// <param name="useHashing">use hashing? send to for extra secirity</param>
/// <returns></returns>
public static string Encrypt(string toEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
// Get the key from config file
string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
//System.Windows.Forms.MessageBox.Show(key);
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);
}
/// <summary>
/// DeCrypt a string using dual encryption method. Return a DeCrypted clear string
/// </summary>
/// <param name="cipherString">encrypted string</param>
/// <param name="useHashing">Did you use hashing to encrypt this data? pass true is yes</param>
/// <returns></returns>
public static string Decrypt(string cipherString, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = Convert.FromBase64String(cipherString);
System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
//Get your key from config file to open the lock!
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);
}
}
}
مرحله هفتم : حال ، در خروجی خواهیم داشت :
اینجا ، ما مقدار “Rc3xvx8c7GM=” را تحت عنوان پسورد رمزگذاری شده وارد میکنیم و دکمه decrypt را میزنیم .

ما پسورد رمزگشایی شده را تحت عنوان "a" دریافت خواهیم کرد .

ما همچنی توانایی decrypt/encrypt داده های یک database را با هر connection string که داده شود ، داریم .

- ASP.net
- 4k بازدید
- 4 تشکر