- [DEVEXPRESS] Đặt mật khẩu và bỏ mật khẩu tập tin file PDF
- [C#] Thêm ứng dụng vào Taskbar sử dụng SharpShell DeskBand
- [C#] Hướng dẫn thêm text vào hình ảnh icon winform
- [C#] Chia sẽ tổng hợp source code đồ án về Csharp
- [C#] Hướng dẫn viết ứng dụng quay màn hình video winform, Screen Recorder
- [C#] Hướng dẫn sử dụng thư viện Input Simulator để làm việc với Keyboard, Mouse Virtual
- [DEVEXPRESS] Hướng dẫn tích Filter Contain khi click chuột phải vào cell selection trên Gridview
- [C#] Tra cứu mã số thuế cá nhân bằng CMND hoặc CCCD
- [C#] Convert hình ảnh image thành Blurhash sử dụng trong loading image winform
- [POWERSHELL] Script sao lưu backup và nén database sqlserver
- [C#] Giới thiệu thư viện Autofac Dependency Injection
- [C#] Hướng dẫn tạo Windows Services đơn giản Winform
- [C#] Một click chuột điều khiển máy tính từ xa sử dụng Ultraviewer
- Hướng dẫn đóng gói phần mềm sử dụng Powershell biên dịch script thành file exe
- [C#] Hướng dẫn sử dụng Task Dialog trên NET 5
- [C#] Hướng dẫn xem lịch sử các trang web đã truy cập trên Chrome Browser
- [C#] Hướng dẫn lấy thông tin Your ID và Password của Ultraviewer Winform
- [C#] Hướng dẫn lấy thông tin Your ID và Password của Teamviewer Winform
- [C#] Hướng dẫn build code động xuất file exe trên Winform
- [C#] Điều khiển ứng dụng từ xa và rất xa với Telegram Bot Winform
[C#] Hướng dẫn mã hóa file sử dụng thuật toán AES 256 bit
Xin chào các bạn bài viết hôm nay mình sẽ hướng dẫn các bạn cách mã hóa sử dụng thuật toán AES 256 bit để mã hóa file và giải mã trong lập trình C#.
[C#] Encrypt and Decrypt File with AES 256 bit Algorithm
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ữ VB.NET, 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).
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:
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 = "https://laptrinhvb.net";
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 = "https://laptrinhvb.net";
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.
Chúc các bạn thành công!