Covers symmetric authenticated encryption with System.Security.Cryptography.AesGcm: 256-bit keys, 96-bit nonces, 128-bit tags, the consequences of nonce reuse, associated data, the stored payload format and when to use Data Protection or Key Vault instead.
AesGcm is .NET's authenticated encryption API: AES in Galois/Counter Mode gives confidentiality and integrity in one step. You need a 256-bit key, a 12-byte nonce that is unique per encryption under that key, and you get a 16-byte tag; decryption throws AuthenticationTagMismatchException if anything was changed. Store keyId | nonce | ciphertext | tag together.
The one rule you can't break: never reuse a nonce with the same key. GCM is a stream cipher underneath, so reuse leaks the XOR of the two plaintexts and exposes the authentication key, letting an attacker forge messages. Use random nonces and rotate keys well before about 2^32 messages. Compared with AES-CBC, GCM has no padding oracle and no separate MAC to get wrong. For most app needs, ASP.NET Core Data Protection or SQL Always Encrypted wraps this for you.
"For encrypting a field like a tax file number or a bank account in .NET, I reach for
AesGcmwhen I genuinely need raw control, and Data Protection when I don't. AES-GCM is an AEAD, authenticated encryption with associated data: AES in counter mode produces the ciphertext, and GHASH produces a 16-byte tag over the ciphertext and any associated data. So I get confidentiality and tamper detection together.The parameters are fixed in practice: a 32-byte key for AES-256, a 12-byte nonce, and a 16-byte tag. Since .NET 8 I construct it as
new AesGcm(key, tagSizeInBytes: 16)because the old constructor is obsolete. I generate the nonce withRandomNumberGenerator.Fillfor every single encryption, and I put a key id, the nonce, the ciphertext and the tag into one blob. I also pass associated data, such as the customer id, so a ciphertext copied from one row to another fails to decrypt.The thing that matters most is the nonce. Counter mode XORs a keystream with the plaintext, and the keystream depends only on key plus nonce. Reuse a nonce and an attacker XORs two ciphertexts to get the XOR of two plaintexts, and worse, they can recover the GHASH key and forge valid tags. With random 96-bit nonces the collision risk stays acceptable up to around 2^32 encryptions per key, so high-volume systems rotate keys or use a counter-based nonce.
The mistake I see is people building AES-CBC with PKCS7 padding and no MAC, which invites padding-oracle attacks, or hard-coding the key in appsettings.json. So: AEAD, a unique nonce, keys from Key Vault with an id for rotation, and if Data Protection already does the job, use that."
| Item | Size | Source | Notes |
|---|---|---|---|
| Key | 32 bytes (AES-256) | Key Vault secret or unwrapped DEK | 16 and 24 are allowed; use 32 |
| Nonce | 12 bytes | RandomNumberGenerator.Fill |
Unique per key, not secret |
| Tag | 16 bytes | Output of Encrypt | Don't truncate below 16 |
| Associated data | Any | Record id, tenant id, version | Authenticated, not encrypted |
| AES-GCM | AES-CBC + HMAC | AES-CBC alone | |
|---|---|---|---|
| Integrity | Built in | If you do encrypt-then-MAC correctly | None |
| Padding oracle | Not applicable | Avoided if MAC is checked first | Vulnerable |
| Parallelisable | Yes | Decrypt only | Decrypt only |
| Misuse risk | Nonce reuse is catastrophic | Getting the MAC order wrong | High |
| Need | Better tool |
|---|---|
| Encrypt cookies, tokens, short-lived payloads in the app | ASP.NET Core Data Protection (IDataProtector) |
| Encrypt a SQL column so even DBAs can't read it | Always Encrypted (with secure enclaves if you need to query) |
| Encrypt large files or blobs | Envelope encryption: a per-file DEK wrapped by a Key Vault key |
| Very high message counts per key | AES-GCM-SIV (nonce-misuse resistant, not in the BCL) or key rotation |
We encrypted [Medicare numbers] in a [claims service] with AES-GCM using per-tenant data keys wrapped by a Key Vault RSA key. Encrypt plus decrypt cost about [2 microseconds] per value and added [under 1%] to request CPU; the key id prefix let us rotate keys with a background re-encryption job and no downtime.
Checks whether the candidate can use authenticated encryption correctly in .NET and understands the nonce and key-management rules that make it safe.
Green flags
tagSizeInBytes constructorRed flags
nonce || counter=2, 3, 4 ...
|
AES_k(block) -> keystream
|
plaintext -------- XOR -------> ciphertext
|
associated data ---> GHASH_H(AAD, ciphertext, lengths) XOR AES_k(nonce||1) -> tag
(H = AES_k(0^128))
Same key and nonce means the same keystream: C1 XOR C2 = P1 XOR P2. With any known plaintext (JSON field names are very guessable) the attacker reads the other message. Two tags under the same nonce also give equations from which H can be solved, after which they forge tags for arbitrary ciphertext. That is why nonce uniqueness is a hard requirement, not a recommendation.
A random 96-bit nonce collides with probability about n97. NIST SP 800-38D caps random-nonce use at 2-32. Options at higher volume: a deterministic counter persisted safely (hard in distributed systems), per-record derived keys, or frequent rotation.
AesGcm delegates to the OS: BCrypt (CNG) on Windows, OpenSSL on Linux, and on macOS it requires the platform to support it (AesGcm.IsSupported). The API is span-based and allocation-free; tag size is validated against AesGcm.TagByteSizes. AesCcm and ChaCha20Poly1305 are the siblings; ChaCha20-Poly1305 is faster on CPUs without AES-NI.
| version(1) | keyId(4) | nonce(12) | tag(16) | ciphertext(n) |
The key id says which key to use on decrypt, so new writes can use key 7 while old rows still decrypt with key 6 until a re-encryption job finishes.
Generate a random data encryption key (DEK) per record set, encrypt the data locally with AES-GCM, and have Key Vault wrap the DEK with a key-encryption key (WrapKey). Store the wrapped DEK. Key Vault never sees the data, and rotating the KEK only rewraps small DEKs.
AuthenticationTagMismatchException.AesGcm on 1 KB payloads with BenchmarkDotNet on Windows and in a Linux container.A small field encryptor with a versioned format, random nonces and associated data. Keys come from a provider (Key Vault in production).
using System.Buffers.Binary;
using System.Security.Cryptography;
using System.Text;
namespace Claims.Security;
public interface IKeyProvider
{
(int KeyId, byte[] Key) Current { get; }
byte[] Get(int keyId);
}
public sealed class FieldEncryptor(IKeyProvider keys)
{
private const byte Version = 1;
private const int NonceSize = 12, TagSize = 16, Header = 1 + 4 + NonceSize + TagSize;
public byte[] Encrypt(string plaintext, string context)
{
var (keyId, key) = keys.Current;
byte[] plain = Encoding.UTF8.GetBytes(plaintext);
byte[] output = new byte[Header + plain.Length];
Span<byte> o = output;
o[0] = Version;
BinaryPrimitives.WriteInt32BigEndian(o[1..5], keyId);
Span<byte> nonce = o.Slice(5, NonceSize);
Span<byte> tag = o.Slice(5 + NonceSize, TagSize);
Span<byte> cipher = o[Header..];
RandomNumberGenerator.Fill(nonce); // fresh for EVERY call: never reuse with the same key
using var aes = new AesGcm(key, TagSize);
aes.Encrypt(nonce, plain, cipher, tag, associatedData: Encoding.UTF8.GetBytes(context));
return output;
}
public string Decrypt(byte[] payload, string context)
{
ReadOnlySpan<byte> p = payload;
if (p.Length < Header || p[0] != Version) throw new CryptographicException("Unknown format.");
int keyId = BinaryPrimitives.ReadInt32BigEndian(p[1..5]);
byte[] plain = new byte[p.Length - Header];
using var aes = new AesGcm(keys.Get(keyId), TagSize);
// Throws AuthenticationTagMismatchException if the data, tag or context changed.
aes.Decrypt(p.Slice(5, NonceSize), p[Header..], p.Slice(5 + NonceSize, TagSize), plain,
associatedData: Encoding.UTF8.GetBytes(context));
return Encoding.UTF8.GetString(plain);
}
}
// Usage: bind the ciphertext to the row so it can't be swapped between customers.
byte[] blob = encryptor.Encrypt("2123 45670 1", context: $"customer:{customerId}:medicare");
Aes.Create() with CBC and no MAC. Why it is wrong: without integrity an attacker can flip ciphertext bits and, if the app reveals padding errors (different status codes or timing), decrypt data byte by byte through a padding oracle. Instead: AesGcm, or encrypt-then-MAC with the MAC checked before decryption if CBC is mandated.AuthenticationTagMismatchException and returning partial data or a default. Why it is wrong: tampered data must be rejected. Instead: let decryption fail, log a security event without the payload, and return a generic error.RandomNumberGenerator; if a key must come from a password, use Rfc2898DeriveBytes.Pbkdf2 (or Argon2id/scrypt) with a random salt and a high iteration count.new AesGcm(key) constructor. Why it is wrong: it produces SYSLIB0053 warnings and leaves the tag size implicit. Instead: new AesGcm(key, tagSizeInBytes: 16).Raw AesGcm is a sharp tool; the senior answer is usually one level up. Data Protection already does authenticated encryption, key rotation and key-ring storage for app-generated payloads. Always Encrypted keeps plaintext away from the database and DBAs. Raw AES-GCM fits when you need a portable format, envelope encryption or interop with another platform.
| Option | When it fits | Cost | When not |
|---|---|---|---|
| Data Protection | Tokens, cookies, short-lived app payloads | None, built in | Long-term archival data, cross-platform readers |
| Always Encrypted | Column-level secrecy from DBAs | Query limits, driver config | Columns you need to search by range |
| Raw AesGcm + Key Vault KEK | Field or file encryption with your own format | Key management code | When a managed option already fits |
| Azure Storage / TDE encryption at rest | Disk and backup theft | Free, on by default | Insider or app-level threats |
Measure: count encryptions per key (to stay under the nonce limit), track decrypt failures as a security signal, and test rotation in staging before you need it.
I'd inventory and classify every setting first: secrets, environment-specific values, shared values, and which must change live. Secrets go to Key Vault. Non-secret settings and feature flags go to Azure App Configuration with a label per environment, and secrets are referenced from there through Key Vault references. The app authenticates with its managed identity using least-privilege roles, and where possible secrets disappear entirely through passwordless Entra ID auth to SQL, Storage and Service Bus.
For refresh, use a sentinel key with a refresh interval and a secret refresh interval, and read live values through IOptionsMonitor. Rotation uses overlapping versions, so old and new both work during the window. Add start-up timeouts and replicas, and keep ValidateOnStart.
The trade-off: central, audited, rotatable configuration, in exchange for a network dependency at start-up that you must design for.
After a successful login the app calls HttpContext.SignInAsync: the cookie handler serialises the ClaimsPrincipal into an authentication ticket, encrypts and signs it with Data Protection, and sends it as a cookie. On each request the handler decrypts the cookie and rebuilds HttpContext.User, with no database call.
HttpOnly (JavaScript can't read it), Secure (HTTPS only), SameSite=Lax by default (not sent on most cross-site requests).ExpireTimeSpan (default 14 days) with sliding expiration that reissues the cookie once half the window has passed; IsPersistent decides whether it survives closing the browser.The trade-off: a self-contained cookie is fast and stateless, but you can't revoke it without extra checks or a server-side ticket store.
How to tell it (STAR)
**S:** At [company] our [reconciliation service] encrypted bank account numbers with AES-GCM, but the nonce was an in-memory counter. **T:** A review found duplicate nonces, and I had to assess the exposure and fix it without downtime. **A:** I quantified the collisions with a SQL query, confirmed no ciphertext had left our boundary, switched to random nonces, created a new key and ran a re-encryption job that used the key id in our payload header so old and new records coexisted. I added a nonce-uniqueness test and an alert on duplicates. **R:** All [about 40 million] records were re-encrypted in [two nights] with zero downtime, and the alert has stayed at [0] since.
Last updated 23 Nov 2026.