HomeNikola Knezevic

In this article

Banner

AES Encryption in .NET

07 May 2026
4 min

Special Thanks to Our Sponsors:

Hypereal AI Logo

Generate images, videos and avatars on demand with HypeReal AI.

It's a serverless platform that gives you 1 API with 50+ models.

Switch between Flux, Sora, Kling and others with one parameter.

If you want to experiment, grab the free tokens and test it yourself:

👉 Learn more

Sponsor Newsletter

Protecting sensitive data is crucial. User information, API keys, passwords and other confidential data should never be stored in plain text.

Even with strong security measures in place, data breaches can still happen. In those situations, encryption becomes the last line of defense. If an attacker gains access to the database, encrypted values remain unreadable without the correct decryption key.

By encrypting sensitive fields, we add an additional layer of protection and significantly reduce the risk of exposing critical information.

Encryption

Encryption is the process of converting readable data into an unreadable format so that only authorized users with the correct key can access the original information.

There are two main types of encryption:

  • Symmetric encryption
  • Asymmetric encryption

Symmetric encryption uses the same key for both encryption and decryption, making it fast and efficient for protecting large amounts of data.

Asymmetric encryption uses a pair of keys. Public key for encryption and a private key for decryption, it's commonly used in secure communication protocols.

AES in .NET

AES (Advanced Encryption Standard) is one of the most commonly used symmetric encryption algorithms.

AES Diagram

It supports multiple key sizes, including 128-bit, 192-bit and 256-bit keys, with AES-256 providing the highest level of security commonly used today.

In .NET, AES encryption is available through the System.Security.Cryptography namespace, which provides secure and optimized implementations of modern cryptographic algorithms:

csharp
using System.Security.Cryptography;

namespace AesEncryption.Api.Crypto;

public static class Encryption
{
    public const int KeySize = 256;
    public const int BlockSize = 128;

    public static string Decrypt(EncryptionResult payload)
    {
        var key = Convert.FromBase64String(payload.Key);
        var (iv, cipher) = payload.GetIvAndCipher();

        using var aes = Aes.Create();
        aes.KeySize = KeySize;
        aes.BlockSize = BlockSize;
        aes.Key = key;
        aes.IV = iv;

        return DecryptData(aes, cipher);
    }

    private static string DecryptData(Aes aes, byte[] cipher)
    {
        using var decryptor = aes.CreateDecryptor();
        using var memoryStream = new MemoryStream(cipher);
        using var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
        using var streamReader = new StreamReader(cryptoStream);

        return streamReader.ReadToEnd();
    }

    public static EncryptionResult Encrypt(string plainText)
    {
        using var aes = Aes.Create();
        aes.KeySize = KeySize;
        aes.BlockSize = BlockSize;

        aes.GenerateKey();
        aes.GenerateIV();

        return EncryptionResult.Create(
            EncryptData(plainText, aes),
            aes.IV,
            Convert.ToBase64String(aes.Key));
    }

    private static byte[] EncryptData(string plainText, Aes aes)
    {
        using var memoryStream = new MemoryStream();
        using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write, leaveOpen: true))
        using (var streamWriter = new StreamWriter(cryptoStream, leaveOpen: true))
        {
            streamWriter.Write(plainText);
        }

        return memoryStream.ToArray();
    }
}

The KeySize is set to 256, meaning AES-256 encryption is used, while BlockSize is set to 128, which is the standard AES block size.

The key is used to encrypt and decrypt the data, while the IV adds randomness to ensure that the same plaintext does not produce the same encrypted output every time.

The EncryptData method performs the actual encryption process by creating an encryptor from the AES instance and writing the plaintext to a CryptoStream.

For decryption, the process works in reverse. The Base64 encoded key is converted back into bytes. The AES instance is recreated using the same key and IV and DecryptData method creates a decryptor which transparently decrypts the data and returns the original plaintext value.

Conclusion

AES is one of the most reliable and widely adopted encryption algorithms available today.

Adding encryption to critical fields can significantly improve application security and reduce the impact of potential data breaches.

If you want to check out examples I created, you can find the source code here:

Source Code

I hope you enjoyed it, subscribe and get a notification when a new blog is up!

Subscribe

Stay tuned for valuable insights every Thursday morning.