blog-details

Trong bài viết trước, mình đã có bài viết hướng dẫn mã hóa AES bằng ngôn ngữ C#, trong bài này này sẽ viết bằng ngôn ngữ C# và lưu thành tập tin file.

Như chúng ta biết thuật toán AES là thuật toán mã hóa 2 chiều đối xứng (tức là chúng ta có thể giải mã được thông qua một key khi chúng ta mã hóa).

Có Dưới đây là giao diện demo của ứng dụng mã hóa file sử dụng thuật toán AES:

eas_app_demo

Bước 1: Đầu tiên các bạn tạo cho mình một class AES.cs với source code C# như sau

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AES_File
{
    public  class AES
    {
       
        [DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
        public static extern bool ZeroMemory(IntPtr Destination, int Length);
        public static byte[] GenerateRandomSalt()
        {
            byte[] data = new byte[32];

            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                for (int i = 0; i < 10; i++)
                {                  
                    rng.GetBytes(data);
                }
            }

            return data;
        }

   
        public  void FileEncrypt(string inputFile, string password)
        {
            byte[] salt = GenerateRandomSalt();
          
            FileStream fsCrypt = new FileStream(inputFile + ".aes", FileMode.Create);
          
            byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
          
            RijndaelManaged AES = new RijndaelManaged();
            AES.KeySize = 256;
            AES.BlockSize = 128;
            AES.Padding = PaddingMode.PKCS7;           
            var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
            AES.Key = key.GetBytes(AES.KeySize / 8);
            AES.IV = key.GetBytes(AES.BlockSize / 8);

           
            AES.Mode = CipherMode.CFB;
           
            fsCrypt.Write(salt, 0, salt.Length);

            CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateEncryptor(), CryptoStreamMode.Write);

            FileStream fsIn = new FileStream(inputFile, FileMode.Open);
            
            byte[] buffer = new byte[1048576];
            int read;

            try
            {
                while ((read = fsIn.Read(buffer, 0, buffer.Length)) > 0)
                {
                    Application.DoEvents(); 
                    cs.Write(buffer, 0, read);
                }
               
                fsIn.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
            finally
            {
                cs.Close();
                fsCrypt.Close();
            }
        }

    
        public  void FileDecrypt(string inputFile, string outputFile, string password)
        {
            byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
            byte[] salt = new byte[32];

            FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
            fsCrypt.Read(salt, 0, salt.Length);

            RijndaelManaged AES = new RijndaelManaged();
            AES.KeySize = 256;
            AES.BlockSize = 128;
            var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
            AES.Key = key.GetBytes(AES.KeySize / 8);
            AES.IV = key.GetBytes(AES.BlockSize / 8);
            AES.Padding = PaddingMode.PKCS7;
            AES.Mode = CipherMode.CFB;

            CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read);

            FileStream fsOut = new FileStream(outputFile, FileMode.Create);

            int read;
            byte[] buffer = new byte[1048576];

            try
            {
                while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
                {
                    Application.DoEvents();
                    fsOut.Write(buffer, 0, read);
                }
            }
            catch (CryptographicException ex_CryptographicException)
            {
                Console.WriteLine("CryptographicException error: " + ex_CryptographicException.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }

            try
            {
                cs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error by closing CryptoStream: " + ex.Message);
            }
            finally
            {
                fsOut.Close();
                fsCrypt.Close();
            }
        }
    }
}

Bước 2: Trong form form1.cs, chúng ta sẽ viết các hàm cho các button.

Viết sự kiện cho nút chọn file

private void btn_browser_Click(object sender, EventArgs e)
{
    var dlg = new OpenFileDialog();
    if(dlg.ShowDialog() == DialogResult.OK)
    {
        txt_input.Text = dlg.FileName;
    }
}

Sự kiện cho nút mã hóa (Encrypt AES C#)

private void btn_encrypt_Click(object sender, EventArgs e)
{
    string password = "atcsmart.com";
    
    GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned);            
    AES.FileEncrypt(txt_input.Text, password);
   
    AES.ZeroMemory(gch.AddrOfPinnedObject(), password.Length * 2);
    gch.Free();
   
    Console.WriteLine("The given password is surely nothing: " + password);
}

 

Sự kiện cho nút giải mã (Decrypt AES C#)

private void btn_decrypt_Click(object sender, EventArgs e)
{
    string password = "atcsmart.com";
   
    GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned);
   
    AES.FileDecrypt(txt_input.Text + ".aes", txt_input.Text, password);

   
    AES.ZeroMemory(gch.AddrOfPinnedObject(), password.Length * 2);
    gch.Free();                       
    Console.WriteLine("The given password is surely nothing: " + password);
}

Kết quả demo ứng dụng sau khi mã hóa file.

mahoa_aes_csharp

Cám ơn các bạn đã ghé thăm web mình. hãy gửi lời cảm nhận bên dưới nhé.

Chúc các bạn thành công!

 

Free Down Ads –  Tải về

Đánh giá bài viết