رمزنگاری و رمزگشایی متن با کلید نامشخص در سی شارپ

شنبه 22 فروردین 1394

در این مقاله میخواهیم یک پیام را رمزکزاری نموده و سپس همان پیام رمزگزاری شده را رمزگشایی کنیم

رمزنگاری و رمزگشایی متن با کلید نامشخص در سی شارپ

رمزنگاری و رمزگشایی متن با کلید نامشخص

در این مقاله میخواهیم یک پیام را رمزکزاری نموده و سپس همان پیام رمزگزاری شده را رمزگشایی کنیم

ایده اصلی این پروژه است برای ذخیره اطلاعات از هکرها میباشد. هنگامی که یک پیام به شما  با استفاده از رمزگذاری ارسال میشود هیچ کس نمی تواند  بدون نرم افزار encrypter و کلید متن را بخواند مثلا شما می خواهید برای ارسال یک پیام پست الکترونیکی است که می تواند توسط بسیاری از مردم (خانواده، دوستان، همکاران و غیره)  خوانده شود. هنگامی که یک پیام به شما ارسال میشود  با استفاده از یک کانال نا امن (ایمیل عمومی سرور، ICQ و غیره)، شما میتوانید از این نرم افزار استفاده کنید.

نیاز به فضانام های زیر داریم:


    using System;  
    using System.Collections.Generic;  
    using System.ComponentModel;  
    using System.Drawing;  
    using System.Text;  
    using System.Windows.Forms;  
    using System.IO;  
    using System.Security.Cryptography;   

دررویداد کلیک دکمه رمزگزاری ابتدا کلید را از ورودی دریافت میکنیم ودرون یک متغیر میریزیم سپس متنی که باید رمزنگاری شود را دریافت کرده و در یک منتغیر ذخیره میکنیم و قبل از رمزگزاری چک میکنیم که هرد متغیر رمز و متن خالی نباشد سپس عمل رمزگزاری را انجام میدهیم در صورت خالی بودن یکی از آنها پیام مناسب نمایش می دهیم.:

     private void btnEncrypt_Click(object sender, EventArgs e)
         {
            key = Convert.ToString(txtKey.Text);
            EnValue = Convert.ToString(txtToEncript.Text);

            if (key != "" && EnValue!="" )
            {
                
                txtResult.Text=EncryptStringAES(EnValue, key);

            }
            else
            {
                
                lblResult.Text = "متن را برای رمزگزاری وارد کنید";
                return;
            }
        }

در رویداد بالا تابعی که عمل رمزگزاری را انجام میدهید دارای دو پارامتر ورودی  متن برای رمزگزاری و کلید می باشد:

      public static string EncryptStringAES(string plainText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentNullException("plainText");
            if (string.IsNullOrEmpty(sharedSecret))
                throw new ArgumentNullException("sharedSecret");

            string outStr = null;                       // Encrypted string to return
            RijndaelManaged aesAlg = null;              // RijndaelManaged object used to encrypt the data.

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create a RijndaelManaged object
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    // prepend the IV
                    msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                    }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            catch (Exception ex)
            {

                Label l1 = new Label();
                l1.ForeColor = Color.Red;
                l1.Text = "کلید مناسب را وارد کنید";
                l1.Show();
                Form1 f = new Form1();
                f.Controls.Add(l1);
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            // Return the encrypted bytes from the memory stream.
            return outStr;
        }

در رویداد کلیک رمزگشایی نیز مقادیر کلید و متن رمزگزاری شده را از ورودی دریافت کرده و در صورت خالی نبودن یکی از آنها عمل رمزگشایی را به صورت زیرانجام میدهیم:

            EnValue = Convert.ToString(txtResult.Text);
               key = Convert.ToString(txtKey.Text);
            

            if (key != "" && EnValue != "")
            {
                txtToEncript.Text = DecryptStringAES(EnValue,key);

            }
            else
            {
                lblResult.Text = "متن را برای رمزگشایی وارد کنید";
                return;
            }

در رویداد رمزگشایی نیز از تابع DecryptStringAES برای این عمل استفاده کردیم که ورودی آن متن رمزگزاری شده و کلید می باشد:

      public static string DecryptStringAES(string cipherText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(cipherText))
                throw new ArgumentNullException("cipherText");
            if (string.IsNullOrEmpty(sharedSecret))
                throw new ArgumentNullException("sharedSecret");

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create the streams used for decryption.                
                byte[] bytes = Convert.FromBase64String(cipherText);
                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    // Create a RijndaelManaged object
                    // with the specified key and IV.
                    aesAlg = new RijndaelManaged();
                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                    // Get the initialization vector from the encrypted stream
                    aesAlg.IV = ReadByteArray(msDecrypt);
                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                Label l = new Label();
                l.ForeColor = Color.Red;
                l.Text = "کلید مناسب را وارد کنید";
                l.Show();
                Form1 f = new Form1();
                f.Controls.Add(l);

            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            return plaintext;
        }

پس کد کامل فرم ما به شکل زیر میباشد :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;

namespace Encrypter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string key, EnValue;
        
        private void Form1_Load(object sender, EventArgs e)
        {

            txtKey.Text = "o7x8y6";
        }

        private void btnEncrypt_Click(object sender, EventArgs e)
         {
            key = Convert.ToString(txtKey.Text);
            EnValue = Convert.ToString(txtToEncript.Text);

            if (key != "" && EnValue!="" )
            {
                
                txtResult.Text=EncryptStringAES(EnValue, key);

            }
            else
            {
                
                lblResult.Text = "متن را برای رمزگزاری وارد کنید";
                return;
            }
        }

        private void btnDecript_Click(object sender, EventArgs e)
        {
               EnValue = Convert.ToString(txtResult.Text);
               key = Convert.ToString(txtKey.Text);
            

            if (key != "" && EnValue != "")
            {
                txtToEncript.Text = DecryptStringAES(EnValue,key);

            }
            else
            {
                lblResult.Text = "متن را برای رمزگشایی وارد کنید";
                return;
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private static byte[] _salt = Encoding.ASCII.GetBytes("o6806642kbM7c5");

        /// <summary>
        /// Encrypt the given string using AES.  The string can be decrypted using 
        /// DecryptStringAES().  The sharedSecret parameters must match.
        /// </summary>
        /// <param name="plainText">The text to encrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
        public static string EncryptStringAES(string plainText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentNullException("plainText");
            if (string.IsNullOrEmpty(sharedSecret))
                throw new ArgumentNullException("sharedSecret");

            string outStr = null;                       // Encrypted string to return
            RijndaelManaged aesAlg = null;              // RijndaelManaged object used to encrypt the data.

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create a RijndaelManaged object
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    // prepend the IV
                    msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                    }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            catch (Exception ex)
            {

                Label l1 = new Label();
                l1.ForeColor = Color.Red;
                l1.Text = "کلید مناسب را وارد کنید";
                l1.Show();
                Form1 f = new Form1();
                f.Controls.Add(l1);
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            // Return the encrypted bytes from the memory stream.
            return outStr;
        }

        /// <summary>
        /// Decrypt the given string.  Assumes the string was encrypted using 
        /// EncryptStringAES(), using an identical sharedSecret.
        /// </summary>
        /// <param name="cipherText">The text to decrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
        public static string DecryptStringAES(string cipherText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(cipherText))
                throw new ArgumentNullException("cipherText");
            if (string.IsNullOrEmpty(sharedSecret))
                throw new ArgumentNullException("sharedSecret");

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create the streams used for decryption.                
                byte[] bytes = Convert.FromBase64String(cipherText);
                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    // Create a RijndaelManaged object
                    // with the specified key and IV.
                    aesAlg = new RijndaelManaged();
                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                    // Get the initialization vector from the encrypted stream
                    aesAlg.IV = ReadByteArray(msDecrypt);
                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                Label l = new Label();
                l.ForeColor = Color.Red;
                l.Text = "کلید مناسب را وارد کنید";
                l.Show();
                Form1 f = new Form1();
                f.Controls.Add(l);

            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            return plaintext;
        }

        private static byte[] ReadByteArray(Stream s)
        {
            byte[] rawLength = new byte[sizeof(int)];
            if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
            {
                throw new SystemException("آرایه بایت شامل فرمت صحیح نمی باشد");
            }

            byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
            if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
            {
                throw new SystemException("آرایه بایت به درستی خوانده نشده است");
            }

            return buffer;
        }

        private void btnCpyEncrt_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(txtResult.Text);
        }

    
    }
}

 

فایل های ضمیمه

برنامه نویسان

نویسنده 3355 مقاله در برنامه نویسان
  • C#.net
  • 4k بازدید
  • 8 تشکر

کاربرانی که از نویسنده این مقاله تشکر کرده اند

در صورتی که در رابطه با این مقاله سوالی دارید، در تاپیک های انجمن مطرح کنید