To encrypt and decrypt files using AES in C#, you can use the
Aes class from the System.Security.Cryptography namespace. Below is a practical example demonstrating both encryption and decryption of files.
1. AES File Encryption in C#
Encrypt a file
using System;
using System.IO;
using System.Security.Cryptography;
public class AesFileEncryption
{
public static void EncryptFile(string inputFile, string outputFile, byte[] key, byte[] iv)
{
using FileStream inputStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read);
using FileStream outputStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
using Aes aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
using CryptoStream cryptoStream = new CryptoStream(outputStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
inputStream.CopyTo(cryptoStream);
}
}
2. AES File Decryption in C#
Decrypt a file
public class AesFileDecryption
{
public static void DecryptFile(string inputFile, string outputFile, byte[] key, byte[] iv)
{
using FileStream inputStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read);
using FileStream outputStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
using Aes aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
using CryptoStream cryptoStream = new CryptoStream(inputStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
cryptoStream.CopyTo(outputStream);
}
}
3. Generate AES Key and IV
using Aes aes = Aes.Create();
byte[] key = aes.Key;
byte[] iv = aes.IV;
// Save these securely; they are required for both encryption and decryption
Important: Always securely store your AES Key and
IV. Never hardcode them in production apps.
Summary
Task
Method
Encrypt
AesFileEncryption.EncryptFile
Decrypt
AesFileDecryption.DecryptFile
Key/IV Gen
Aes.Create()
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To encrypt and decrypt files using AES in C#, you can use the
Aesclass from theSystem.Security.Cryptographynamespace. Below is a practical example demonstrating both encryption and decryption of files.1. AES File Encryption in C#
Encrypt a file
2. AES File Decryption in C#
Decrypt a file
3. Generate AES Key and IV
Summary
AesFileEncryption.EncryptFileAesFileDecryption.DecryptFileAes.Create()