Create Encrypted AES Files and Decrypt AES Encrypted Files in C#

Introduction

Data security is a critical concern in today's digital world. Encrypting sensitive information is a fundamental practice to protect it from unauthorized access. In this step-by-step guide, we'll walk you through how to create encrypted AES files and decrypt them using C#, a versatile and widely-used programming language.

Prerequisites

Before we dive into the encryption and decryption processes, make sure you have the following prerequisites in place:

  1. Visual Studio or Visual Studio Code: You'll need a development environment to write and run your C# code.

  2. C# Knowledge: Basic familiarity with C# programming is essential for following along with this guide.

Part 1. Creating Encrypted AES Files
 

Step 1. Create a New C# Project

Open Visual Studio or Visual Studio Code and create a new C# console application project. You can do this by selecting "File" -> "New" -> "Project" and choosing "Console App (.NET Core)" or a similar option.

Step 2. Include Necessary Libraries

In your C# project, include the System.Security.Cryptography namespace to use the AES encryption classes. Add the following using statement to your program:

using System.Security.Cryptography;

Step 3. Encrypt Data and Write to File

Now, let's write code to encrypt your data and save it to an encrypted file.

static void Main(string[] args)
{
    string key = Generate256BitKey(); // Store the key for the Decrypt
    Console.WriteLine("Key is "+key);
    string originalText = "This is the text to be encrypted."; // Encrypt the text
    byte[] encryptedBytes = EncryptStringToBytes_Aes(originalText, key);
    File.WriteAllBytes("encryptedFile.aes", encryptedBytes);
    Console.WriteLine("Encrypted Text Done");
    // Find the encryptedFile.aes in bin folder
}

private static string Generate256BitKey()
{
    using (Aes aesAlg = Aes.Create())
    {
        aesAlg.KeySize = 256; // Set the key size to 256 bits
        aesAlg.GenerateKey(); // Generate a random 256-bit key
        return Convert.ToBase64String(aesAlg.Key);
    }
}

private static byte[] EncryptStringToBytes_Aes(string plainText, string key)
{
    byte[] encrypted;

    using (Aes aesAlg = Aes.Create())
    {
        aesAlg.Key = Convert.FromBase64String(key);
        aesAlg.IV = new byte[aesAlg.BlockSize / 8]; // IV should be the same size as the block size
        aesAlg.Mode = CipherMode.CBC; // Set the mode to CBC
        aesAlg.Padding = PaddingMode.PKCS7; // Use PKCS7 padding

        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
            {
                swEncrypt.Write(plainText);
            }
            encrypted = msEncrypt.ToArray();
        }
    }

    return encrypted;
}

Part 2 Decrypting AES Encrypted Files
 

Step 1. Create a New C# Project

Open a new instance of Visual Studio or Visual Studio Code and create a new C# console application project, just as you did in Part 1.

Step 2. Include Necessary Libraries

Include the System.Security.Cryptography namespace in your new project as well.

using System.Security.Cryptography;

Step 3. Decrypt the AES-Encrypted File

Now, let's write code to decrypt the AES-encrypted file.

static void Main(string[] args)
{
    string key = "";// use the same key which is used in encrypt
    byte[] encryptedBytes = File.ReadAllBytes("encryptedFile.aes");
    // Decrypt the encrypted text
    string decryptedText = DecryptStringFromBytes_Aes(encryptedBytes, key);
    Console.WriteLine("CecryptedText is "+ decryptedText);
}
private static string DecryptStringFromBytes_Aes(byte[] cipherText, string key)
{
    string plaintext = null;

    using (Aes aesAlg = Aes.Create())
    {
        aesAlg.Key = Convert.FromBase64String(key);
        aesAlg.IV = new byte[aesAlg.BlockSize / 8]; // IV should be the same size as the block size
        aesAlg.Mode = CipherMode.CBC; // Set the mode to CBC
        aesAlg.Padding = PaddingMode.PKCS7; // Use PKCS7 padding

        ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

        using (MemoryStream msDecrypt = new MemoryStream(cipherText))
        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
        {
            plaintext = srDecrypt.ReadToEnd();
        }
    }
    return plaintext;
}

Conclusion

Creating encrypted AES files and decrypting them in C# is a crucial skill for data security. This step-by-step guide has provided you with the tools and knowledge to protect your sensitive information. Always remember to keep your encryption key secure, as it is the key to unlocking your encrypted data. With the right practices, you can ensure that your data remains confidential and secure from unauthorized access.


Similar Articles