📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Show how you would encrypt and decrypt sensitive values in .NET with AesGcm. Explain the key and nonce sizes, why reusing a nonce with the same key is catastrophic, what authenticated encryption gives you over AES-CBC, and how you would store the output.

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.

Mid-Level Coding Intermediate aes-gcm cryptography dotnet encryption key-management security

🎯 Key points

  • AesGcm: 32-byte key (AES-256), 12-byte nonce, 16-byte tag; use the tagSizeInBytes constructor (.NET 8+)
  • Every nonce must be unique per key: a single reuse leaks the XOR of the two plaintexts and lets attackers recover the GHASH key and forge tags
  • Random nonces keep the chance of an accidental collision negligible only up to about 2^32 encryptions per key (NIST SP 800-38D), so rotate keys before that
  • High-volume or distributed systems: per-instance key or nonce prefix, persisted counters, or AES-GCM-SIV
  • AEAD rejects tampered data (AuthenticationTagMismatchException); unauthenticated CBC lets attackers modify ciphertext and use padding errors as an oracle to decrypt it
  • Associated data binds ciphertext to context (record id, tenant) without encrypting it
  • Store version + key id + nonce + tag + ciphertext together; keys from Key Vault, never hard-coded
  • Prefer Data Protection or Always Encrypted unless you need raw control

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"For encrypting a field like a tax file number or a bank account in .NET, I reach for AesGcm when 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 with RandomNumberGenerator.Fill for 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."


Parameters

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

GCM vs CBC

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

When to use something else

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

Production example

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.

🔍 What the interviewer is checking

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

  • Correct sizes and the tagSizeInBytes constructor
  • Explains nonce reuse consequences concretely (keystream reuse, forgery)
  • Stores key id, nonce, tag and ciphertext together; uses associated data
  • Suggests Data Protection, Always Encrypted or envelope encryption where appropriate

Red flags

  • Hard-coded keys or IVs
  • CBC without a MAC, or ECB
  • Thinks the nonce must be secret, or ignores integrity

📚 Learn in depth

1. How GCM works

            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))
  • Encryption is CTR mode: a keystream XORed with the plaintext, so ciphertext length equals plaintext length.
  • Authentication is GHASH, a polynomial MAC over GF(2^128) keyed with H, plus an encrypted counter block.

2. Why nonce reuse breaks everything

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.

3. Random vs counter nonces

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.

4. Inside .NET

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.

5. A storage format that survives rotation

| 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.

6. Envelope encryption

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.

Try it yourself

  1. Encrypt two messages with the same key and nonce, XOR the ciphertexts and compare with the XOR of the plaintexts.
  2. Flip one bit of the ciphertext and observe AuthenticationTagMismatchException.
  3. Encrypt with associated data "customer-1", decrypt with "customer-2", and watch it fail.
  4. Benchmark AesGcm on 1 KB payloads with BenchmarkDotNet on Windows and in a Linux container.
  5. Implement the versioned format above and write a test that decrypts data written with an older key id.

💻 Code

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");

⚠ Common mistakes

  • Mistake: Using a fixed nonce, or a counter nonce that resets on restart or is shared across instances. Why it is wrong: nonce reuse leaks plaintext XORs and allows tag forgery. Instead: a fresh random 12-byte nonce per call stored with the ciphertext, or a per-instance prefix plus a persisted counter in high-volume systems.
  • Mistake: Hard-coding the key or keeping it in appsettings.json. Why it is wrong: anyone with the repo or config has every record. Instead: Key Vault or envelope encryption with a key id.
  • Mistake: Using 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.
  • Mistake: Catching 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.
  • Mistake: Turning a password or passphrase into a key with a single SHA-256. Why it is wrong: a fast hash of a low-entropy password is brute-forceable. Instead: generate random keys with RandomNumberGenerator; if a key must come from a password, use Rfc2898DeriveBytes.Pbkdf2 (or Argon2id/scrypt) with a random salt and a high iteration count.
  • Mistake: Omitting a key id from the payload. Why it is wrong: rotation then needs a big-bang re-encryption. Instead: version and key id in a header.
  • Mistake: Using the obsolete new AesGcm(key) constructor. Why it is wrong: it produces SYSLIB0053 warnings and leaves the tag size implicit. Instead: new AesGcm(key, tagSizeInBytes: 16).

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says the key comes from Azure Key Vault. Why: Checks how they load and refresh secrets from Key Vault with managed identity.
    How to answer

    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.

  2. When: Candidate mentions that ASP.NET Core Data Protection already encrypts cookies. Why: Checks understanding of what Data Protection protects in cookie authentication.
    How to answer

    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.

    • Flags: HttpOnly (JavaScript can't read it), Secure (HTTPS only), SameSite=Lax by default (not sent on most cross-site requests).
    • Expiry: 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.
    • Keys: every instance must share the Data Protection key ring, or cookies issued by one server can't be read by another.

    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.

🛠 Real-world problems: how you handle them

Nonce reuse after a container restart
Situation
A [payments reconciliation service] encrypted bank account numbers with AES-GCM using a counter nonce held in memory. It ran on [three pods in AKS] and processed [about 2 million] records a day.
Signals
A security review noticed duplicate nonce prefixes when sampling stored ciphertexts; no customer impact had been reported.
Investigation
Queried the table for duplicate nonce values per key id (`GROUP BY SUBSTRING(Payload, 6, 12) HAVING COUNT(*) > 1`) and found [thousands] of collisions; traced them to every pod starting its counter at zero after restarts; checked access logs to see whether ciphertexts had left the system.
Resolution
Switched immediately to random 12-byte nonces from `RandomNumberGenerator`; generated a new key, re-encrypted all records with a background job keyed by the key id header; retired the old key in Key Vault.
Prevention
A unit test asserting nonces are unique over 1 million encryptions; a nightly query alerting on duplicate nonces per key; a metric of encryptions per key with an alert at 2^30; a code-review checklist item for any custom crypto.

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.

↩ Usually asked after

More in Cryptography

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me