How to Encrypt and Decrypt files using AES encryption algorithm in C#

By FoxLearn 7/16/2024 9:26:02 AM   25.22K
Encrypting and decrypting files using AES encryption in a C# Windows Forms application involves several steps.

Here’s a step-by-step guide you how to encrypt and decrypt files using AES in C#.

Advanced Encryption Standard

The Advanced Encryption Standard (AES), also known by its original name Rijndael is a specification for the encryption of electronic data established by the U.S. government to protect classified information and is implemented in software and hardware throughout the world to encrypt sensitive data.

How to encrypt and decrypt a text file in c#

First of all, We will design a simple UI allows you to select the file, then encrypt and decrypt by using AES 256 bit encryption in C#.

encrypt and decrypt files in c#

In this c# example, i show you how to encrypt and decrypt a text file in c# .net. You can also, select any file from your disk to encrypt and decrypt files with password.

Adding a click event handler to the Browse button allows you to select the file, then display file name in the TextBox control.

private void btnBrowse_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "All files|*.*" })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
            txtFileName.Text = ofd.FileName;
    }
}

Next, declare the ZeroMemory method to remove the key from memory after use for security.

[DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
public static extern bool ZeroMemory(IntPtr Destination, int Length);

and don't forget to include the namespace below to your winform.

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;

Next, Create the GenerateSalt method to generate the salt that will be used to encrypt your file.

public static byte[] GenerateSalt()
{
    byte[] data = new byte[32];
    using (RNGCryptoServiceProvider rgnCryptoServiceProvider = new RNGCryptoServiceProvider())
    {
        rgnCryptoServiceProvider.GetBytes(data);
    }
    return data;
}

Create the FileEncrypt method allows you to use c# encrypt file with password.

// c# file ecrypt
private void FileEncrypt(string inputFile, string password)
{
    byte[] salt = GenerateSalt();
    byte[] passwords = Encoding.UTF8.GetBytes(password);
    RijndaelManaged AES = new RijndaelManaged();
    AES.KeySize = 256;//aes 256 bit encryption c#
    AES.BlockSize = 128;//aes 128 bit encryption c#
    AES.Padding = PaddingMode.PKCS7;
    var key = new Rfc2898DeriveBytes(passwords, salt, 50000);
    AES.Key = key.GetBytes(AES.KeySize / 8);
    AES.IV = key.GetBytes(AES.BlockSize / 8);
    AES.Mode = CipherMode.CFB;
    using (FileStream fsCrypt = new FileStream(inputFile + ".aes", FileMode.Create))
    {
        fsCrypt.Write(salt, 0, salt.Length);
        using (CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateEncryptor(), CryptoStreamMode.Write))
        {
            using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
            {
                byte[] buffer = new byte[1048576];
                int read;
                while ((read = fsIn.Read(buffer, 0, buffer.Length)) > 0)
                {
                    cs.Write(buffer, 0, read);
                }
            }
        }
    }
}

You need to generate random salt, then create your output file. You need to convert the password string into a byte arrray, then set the Rijndael symmetric encryption algorithm.

Finally, Write salt to the begining of the output file, so in this case can be random every time. Don't forget to create a buffer to allocate in the memory and not the whole file.

Create the FileDecrypt method allows you to decrypt files from the encrypted files with a password.

// c# file decrypt
private void FileDecrypt(string inputFileName, string outputFileName, string password)
{
    byte[] passwords = Encoding.UTF8.GetBytes(password);
    byte[] salt = new byte[32];
    using (FileStream fsCrypt = new FileStream(inputFileName, FileMode.Open))
    {
        fsCrypt.Read(salt, 0, salt.Length);
        RijndaelManaged AES = new RijndaelManaged();
        AES.KeySize = 256;//aes 256 bit encryption c#
        AES.BlockSize = 128;//aes 128 bit encryption c#
        var key = new Rfc2898DeriveBytes(passwords, salt, 50000);
        AES.Key = key.GetBytes(AES.KeySize / 8);
        AES.IV = key.GetBytes(AES.BlockSize / 8);
        AES.Padding = PaddingMode.PKCS7;
        AES.Mode = CipherMode.CFB;
        using (CryptoStream cryptoStream = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read))
        {
            using (FileStream fsOut = new FileStream(outputFileName, FileMode.Create))
            {
                int read;
                byte[] buffer = new byte[1048576];
                while ((read = cryptoStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    fsOut.Write(buffer, 0, read);
                }
            }
        }
    }
}

Adding a click event handler to the Encrypt button allows you to encrypt files using the AES algorithm.

private void btnEncrypt_Click(object sender, EventArgs e)
{
    string password = "foxlearn.com";
    GCHandle gCHandle = GCHandle.Alloc(password, GCHandleType.Pinned);
    FileEncrypt(txtFileName.Text, password);
    ZeroMemory(gCHandle.AddrOfPinnedObject(), password.Length * 2);
    gCHandle.Free();
}

Adding a click event handler to the Decrypt button allows you to decrypt files from encrypted files using the AES 256 bit Encryption C#.

private void btnDecrypt_Click(object sender, EventArgs e)
{
    string password = "foxlearn.com";
    GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned);
    FileDecrypt(txtFileName.Text + ".aes", txtFileName.Text, password);
    ZeroMemory(gch.AddrOfPinnedObject(), password.Length * 2);
    gch.Free();
}

Use GCHandle to additional security Pin the password of your files.

Don't forget to call the ZeroMemory method to increase the security of the decryption, remove the used password from the memory when using c# aes 256 file encryption example.