Implement AES-256 Encryption and Decryption in C#: A Beginner-Friendly Guide

Introduction

In this guide, we will explore how to implement AES-256 encryption and decryption in C# using the System.Security.Cryptography namespace. AES (Advanced Encryption Standard) is a widely used encryption algorithm that provides rob…


This content originally appeared on DEV Community and was authored by David Au Yeung

Introduction

In this guide, we will explore how to implement AES-256 encryption and decryption in C# using the System.Security.Cryptography namespace. AES (Advanced Encryption Standard) is a widely used encryption algorithm that provides robust security for sensitive data.

With just a few lines of code, you can encrypt and decrypt strings, making this approach ideal for securing application secrets, protecting user data, and more.

Let’s dive into the implementation step by step!

Step 1: Create the EncryptionHelper Class

We'll start by creating a reusable utility class called EncryptionHelper. This class will handle both encryption and decryption processes.

The helper leverages environment variables to securely store the encryption key and initialization vector (IV), ensuring that sensitive information is not hardcoded into the application.

Here’s the code for the EncryptionHelper class:

using System.Security.Cryptography;
using System.Text;

namespace MyPlaygroundApp.Utils
{
    public class EncryptionHelper
    {
        // Environment variable names
        private const string KeyEnvVar = "MY_ENCRYPTION_KEY";
        private const string IVEnvVar = "MY_ENCRYPTION_IV";

        private static byte[] Key => GetKeyOrIV(KeyEnvVar, 32);
        private static byte[] IV => GetKeyOrIV(IVEnvVar, 16);

        private static byte[] GetKeyOrIV(string envVar, int requiredLength)
        {
            var value = Environment.GetEnvironmentVariable(envVar);
            if (string.IsNullOrWhiteSpace(value) || value.Length != requiredLength)
            {
                throw new InvalidOperationException(
                    $"Environment variable '{envVar}' must be set and exactly {requiredLength} characters long.");
            }
            return Encoding.UTF8.GetBytes(value);
        }

        /// <summary>
        /// Encrypts the input string using AES-256.
        /// </summary>
        public static string Encrypt(string plainText)
        {
            if (string.IsNullOrEmpty(plainText))
                return string.Empty;

            using var aes = Aes.Create();
            aes.Key = Key;
            aes.IV = IV;

            using var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
            using var ms = new MemoryStream();
            using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
            using (var sw = new StreamWriter(cs))
            {
                sw.Write(plainText);
            }
            return Convert.ToBase64String(ms.ToArray());
        }

        /// <summary>
        /// Decrypts the input string using AES-256.
        /// </summary>
        public static string Decrypt(string cipherText)
        {
            if (string.IsNullOrEmpty(cipherText))
                return string.Empty;

            using var aes = Aes.Create();
            aes.Key = Key;
            aes.IV = IV;

            using var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
            using var ms = new MemoryStream(Convert.FromBase64String(cipherText));
            using var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
            using var sr = new StreamReader(cs);
            return sr.ReadToEnd();
        }
    }
}

Step 2: Set Up Environment Variables

To keep encryption keys secure, we’ll use environment variables for the key and IV.

Key: Must be exactly 32 characters long (256 bits).
IV: Must be exactly 16 characters long (128 bits).

Set these environment variables by adding them to your system or .env file:

MY_ENCRYPTION_KEY=YOUR_32_CHARACTER_KEY_HERE  
MY_ENCRYPTION_IV=YOUR_16_CHARACTER_IV_HERE  

You can set it in different ways depending on your operating system:

On Windows (Command Prompt or PowerShell):

setx MY_ENCRYPTION_KEY "1a2b3c4d5e6f7g8h9i0jklmnopqrstuv"

On macOS or Linux:

export MY_ENCRYPTION_KEY="1a2b3c4d5e6f7g8h9i0jklmnopqrstuv"

Similarly, ensure that the MY_ENCRYPTION_IV variable is set and is exactly 16 characters long:

On Windows (Command Prompt or PowerShell):

setx MY_ENCRYPTION_IV "abcd1234efgh5678"

On macOS or Linux:

export MY_ENCRYPTION_IV="abcd1234efgh5678"

Step 3: Restart Your IDE or Terminal

Environment variables may not take effect in an already running program. Restart your IDE (e.g., Visual Studio) or terminal, and rerun your project.

Step 4: Use the Helper Class in Your Application

Now that we’ve built the helper class, let’s use it to encrypt and decrypt a sample string.

Here’s the client code in your Program.cs:

using MyPlaygroundApp.Utils;

class Program
{
    static void Main(string[] args)
    {
        string plainText = "I am David, I love dev.to!";
        Console.WriteLine($"Original Text: {plainText}");

        // Encrypt the text
        string encryptedText = EncryptionHelper.Encrypt(plainText);
        Console.WriteLine($"Encrypted Text: {encryptedText}");

        // Decrypt the text
        string decryptedText = EncryptionHelper.Decrypt(encryptedText);
        Console.WriteLine($"Decrypted Text: {decryptedText}");
    }
}

Step 5: Run and Test the Code

Build and run your project:

dotnet run

You should see the following output:

Your Challenge: Try Azure Key Vault

Instead of using environment variables to store your encryption key and IV, try using Azure Key Vault. Azure Key Vault is a cloud service that securely stores and accesses keys, secrets, and certificates.

Benefits of using Azure Key Vault:

  • Centralized key management.
  • Enhanced security with HSM-backed keys.
  • Automated key rotation.

To get started, check out the Azure Key Vault documentation:
Azure Key Vault

Summary

In this guide, we:

  • Built an EncryptionHelper class to handle AES-256 encryption and decryption.
  • Used environment variables to securely store the encryption key and IV.
  • Demonstrated how to encrypt and decrypt strings in C#.

With this setup, you can easily extend the helper to encrypt files, secure API tokens, or protect sensitive application data.

References

System.Security.Cryptography

Love C#!


This content originally appeared on DEV Community and was authored by David Au Yeung


Print Share Comment Cite Upload Translate Updates
APA

David Au Yeung | Sciencx (2025-08-21T19:00:01+00:00) Implement AES-256 Encryption and Decryption in C#: A Beginner-Friendly Guide. Retrieved from https://www.scien.cx/2025/08/21/implement-aes-256-encryption-and-decryption-in-c-a-beginner-friendly-guide/

MLA
" » Implement AES-256 Encryption and Decryption in C#: A Beginner-Friendly Guide." David Au Yeung | Sciencx - Thursday August 21, 2025, https://www.scien.cx/2025/08/21/implement-aes-256-encryption-and-decryption-in-c-a-beginner-friendly-guide/
HARVARD
David Au Yeung | Sciencx Thursday August 21, 2025 » Implement AES-256 Encryption and Decryption in C#: A Beginner-Friendly Guide., viewed ,<https://www.scien.cx/2025/08/21/implement-aes-256-encryption-and-decryption-in-c-a-beginner-friendly-guide/>
VANCOUVER
David Au Yeung | Sciencx - » Implement AES-256 Encryption and Decryption in C#: A Beginner-Friendly Guide. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/08/21/implement-aes-256-encryption-and-decryption-in-c-a-beginner-friendly-guide/
CHICAGO
" » Implement AES-256 Encryption and Decryption in C#: A Beginner-Friendly Guide." David Au Yeung | Sciencx - Accessed . https://www.scien.cx/2025/08/21/implement-aes-256-encryption-and-decryption-in-c-a-beginner-friendly-guide/
IEEE
" » Implement AES-256 Encryption and Decryption in C#: A Beginner-Friendly Guide." David Au Yeung | Sciencx [Online]. Available: https://www.scien.cx/2025/08/21/implement-aes-256-encryption-and-decryption-in-c-a-beginner-friendly-guide/. [Accessed: ]
rf:citation
» Implement AES-256 Encryption and Decryption in C#: A Beginner-Friendly Guide | David Au Yeung | Sciencx | https://www.scien.cx/2025/08/21/implement-aes-256-encryption-and-decryption-in-c-a-beginner-friendly-guide/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.