AES Encryption stands for Advanced Encryption Standard it's a symmetric encryption algorithm. To secure data, this is one of the ways to encrypt data and save it in an Excel sheet. "System. Security. Cryptography" Namespace will be used for encrypting the data and the FileStream class is used for read and write operations for Excel or CSV files.
Input File Example
Name |
SSS |
Age |
23 |
DOB |
MM-DD-YY |
Code example
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
string originalFile = "your_file.csv";
string encryptedFile = "encrypted_file.enc";
string password = "your_secure_password";
// Encrypt the file
EncryptFile(originalFile, encryptedFile, password);
Console.WriteLine("File encrypted.");
// Decrypt the file
string decryptedFile = "decrypted_file.csv"; // Define decrypted file path
DecryptFile(encryptedFile, decryptedFile, password);
Console.WriteLine("File decrypted.");
}
static void EncryptFile(string inputFile, string outputFile, string password)
{
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(password.PadRight(32).Substring(0, 32));
aes.IV = new byte[16]; // Use a zero IV for simplicity (not recommended for production)
using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create))
{
using (CryptoStream cs = new CryptoStream(fsOutput, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
using (FileStream fsInput = new FileStream(inputFile, FileMode.Open))
{
fsInput.CopyTo(cs);
}
}
}
}
}
static void DecryptFile(string inputFile, string outputFile, string password)
{
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(password.PadRight(32).Substring(0, 32));
aes.IV = new byte[16];
using (FileStream fsInput = new FileStream(inputFile, FileMode.Open))
{
using (CryptoStream cs = new CryptoStream(fsInput, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create))
{
cs.CopyTo(fsOutput);
}
}
}
}
}
}
Output
Decryption Code Example
static void DecryptFile(string inputFile, string outputFile, string password)
{
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(password.PadRight(32).Substring(0, 32));
aes.IV = new byte[16];
using (FileStream fsInput = new FileStream(inputFile, FileMode.Open))
{
using (CryptoStream cs = new CryptoStream(fsInput, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create))
{
cs.CopyTo(fsOutput);
}
}
}
}
}