IC Improve Code Recipes

Recipe 7.2 · C#

Encrypting Data with AES-GCM

Problem

Some data must be readable by the application but not by someone holding a copy of the database: bank account numbers, national IDs, API credentials for a customer's integration. The legacy helpers use AES in CBC or ECB mode with a fixed IV and no integrity check, so identical values produce identical ciphertext, and an attacker can flip bits without detection.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not this: hard-coded key, fixed IV, no tamper detection.
private static readonly byte[] Key =
    Encoding.ASCII.GetBytes("MySecretKey12345");
private static readonly byte[] IV = new byte[16];

public static string Encrypt(string text)
{
    using (var aes = new RijndaelManaged { Key = Key, IV = IV })
    using (var enc = aes.CreateEncryptor())
    {
        byte[] input = Encoding.UTF8.GetBytes(text);
        byte[] output = enc.TransformFinalBlock(input, 0, input.Length);
        return Convert.ToBase64String(output);
    }
}

The improved recipe

Use AesGcm, an authenticated cipher, with a 256-bit key from a secret store, a fresh random nonce for every message, and a versioned output format that carries the nonce and tag.

C#
using System;
using System.Security.Cryptography;
using System.Text;

namespace ImproveCode.Security;

/// <summary>AES-256-GCM. Output: version (1) | nonce (12) |
/// tag (16) | ciphertext.</summary>
public sealed class AesGcmEncryptor
{
    private const byte Version = 1;
    private const int KeySize = 32;
    private const int NonceSize = 12;
    private const int TagSize = 16;
    private const int HeaderSize = 1 + NonceSize + TagSize;

    private readonly byte[] _key;

    public AesGcmEncryptor(byte[] key)
    {
        ArgumentNullException.ThrowIfNull(key);
        if (key.Length != KeySize)
        {
            throw new ArgumentException(
                "The key must be 32 bytes (256 bits).", nameof(key));
        }

        _key = (byte[])key.Clone();
    }

    public static byte[] GenerateKey() =>
        RandomNumberGenerator.GetBytes(KeySize);

    public byte[] Encrypt(
        ReadOnlySpan<byte> plaintext,
        ReadOnlySpan<byte> associatedData = default)
    {
        byte[] output = new byte[HeaderSize + plaintext.Length];
        output[0] = Version;

        Span<byte> nonce = output.AsSpan(1, NonceSize);
        Span<byte> tag = output.AsSpan(1 + NonceSize, TagSize);
        Span<byte> ciphertext = output.AsSpan(HeaderSize);

        RandomNumberGenerator.Fill(nonce);

        using var aes = new AesGcm(_key, TagSize);
        aes.Encrypt(nonce, plaintext, ciphertext, tag, associatedData);
        return output;
    }

    public byte[] Decrypt(
        ReadOnlySpan<byte> payload,
        ReadOnlySpan<byte> associatedData = default)
    {
        if (payload.Length < HeaderSize || payload[0] != Version)
        {
            throw new CryptographicException(
                "The payload is truncated or has an unknown version.");
        }

        ReadOnlySpan<byte> nonce = payload.Slice(1, NonceSize);
        ReadOnlySpan<byte> tag = payload.Slice(1 + NonceSize, TagSize);
        ReadOnlySpan<byte> ciphertext = payload[HeaderSize..];

        byte[] plaintext = new byte[ciphertext.Length];

        using var aes = new AesGcm(_key, TagSize);
        // Throws AuthenticationTagMismatchException if tampered.
        aes.Decrypt(nonce, ciphertext, tag, plaintext, associatedData);
        return plaintext;
    }

    public string EncryptString(string plaintext, string context)
    {
        ArgumentNullException.ThrowIfNull(plaintext);
        byte[] result = Encrypt(
            Encoding.UTF8.GetBytes(plaintext),
            Encoding.UTF8.GetBytes(context));
        return Convert.ToBase64String(result);
    }

    public string DecryptString(string payload, string context)
    {
        ArgumentNullException.ThrowIfNull(payload);
        byte[] plaintext = Decrypt(
            Convert.FromBase64String(payload),
            Encoding.UTF8.GetBytes(context));
        return Encoding.UTF8.GetString(plaintext);
    }
}

Usage, binding each value to the row it belongs to:

C#
byte[] key = Convert.FromBase64String(
    builder.Configuration["Encryption:Key"]
    ?? throw new InvalidOperationException("Missing key."));
var encryptor = new AesGcmEncryptor(key);

string stored = encryptor.EncryptString(
    accountNumber, context: $"Customer:{customerId}:BankAccount");

How it works

GCM is authenticated encryption. Besides the ciphertext it produces a 16-byte tag computed over the ciphertext and the associated data. Decrypt recomputes the tag and throws AuthenticationTagMismatchException (a CryptographicException) if a single bit of the payload, the key or the associated data differs. CBC without a separate MAC gives you no such check.

The nonce must never repeat for the same key, because a repeated nonce in GCM leaks the XOR of the two plaintexts and lets an attacker forge tags. Twelve random bytes from RandomNumberGenerator per message make a collision vanishingly unlikely for any realistic volume. The nonce isn't secret, so it travels at the front of the payload, followed by the tag.

The version byte costs nothing and saves a painful migration later. If you ever change algorithm or layout, new payloads get version 2, and Decrypt can still read version 1.

The context string is associated data: authenticated but not encrypted or stored. Binding the ciphertext to Customer:42:BankAccount means an attacker with write access to the table can't copy customer 42's encrypted account number into their own row; decryption fails because the context doesn't match.

A new AesGcm object per call keeps the class thread-safe without locks. Creating one is cheap compared to the database round trip around it.

Variations and pitfalls

  • The key is the whole secret. Keep it in Key Vault or another secret store (Chapter 6), never in source or in the same database as the data. Generate it with GenerateKey() and store it as Base64.
  • Plan key rotation: add a key ID to the header (a second byte, for example), keep old keys for decryption, and re-encrypt rows in the background.
  • NIST guidance limits random 96-bit nonces to about 2^32 messages per key. If you encrypt billions of values, rotate keys long before that.
  • AesGcm.IsSupported is false on a few platforms (some older Linux builds without a suitable OpenSSL, for example). Check it at startup if you deploy beyond Windows.
  • For data that only your own app needs to round-trip, such as cookies or short-lived tokens, the ASP.NET Core Data Protection API (IDataProtector) handles keys and rotation for you. Use AES-GCM directly when the data lives for years or is shared with other systems.
  • SQL Server's Always Encrypted is the other option for column encryption, with keys that never reach the database server. It's more setup but needs no application crypto code.

On .NET Framework

AesGcm does not exist on .NET Framework. On 4.8, use AesCng in CBC mode with a random IV and an HMAC-SHA-256 over IV and ciphertext (encrypt-then-MAC), verified with a constant-time compare before decrypting, or use a vetted library. Keep the same versioned layout so data can move to AES-GCM when the app moves to modern .NET.