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

📚 Interview question

Your .NET system stores customers' names, dates of birth, addresses, driver's licence numbers and Medicare numbers. How do you handle this personal information securely? Cover data classification, minimisation, encryption at rest and in transit, masking, data residency in Australia, and retention.

PII handling in a .NET and Azure system: classifying data, collecting less, TDE plus Always Encrypted or application-level encryption for identifiers, masking and redaction, access logging, keeping data in Australia East/Southeast, and retention and deletion under APP 11.

Mid-Level Security Intermediate always-encrypted data-protection data-residency pii privacy-act security

🎯 Key points

  • Classify data (public, internal, personal, sensitive, high-risk government identifiers) and tag it in the schema with SQL sensitivity classification
  • Minimise: don't collect what you don't need; verify a licence via DVS and store only the result, a reference or last digits
  • In transit: TLS 1.2 minimum, TLS 1.3 preferred, Encrypt=True to SQL; at rest: TDE is a baseline that protects data files and backups but is transparent to anyone who can query (SQL injection, over-privileged users)
  • Field-level protection for identifiers: Always Encrypted (deterministic for equality lookups, randomised otherwise, secure enclaves for richer queries) or app-level AES-GCM with Key Vault keys, plus HMAC for lookups
  • Access control: role- or attribute-based policies so only roles that need identifiers can reveal them, with reason capture and audit; purpose-built DTOs and masking everywhere else; redaction in logs
  • Residency: Azure Australia East/Southeast for data, backups, logs and AI services; check third parties (APP 8 cross-border disclosure)
  • Retention: APP 11.2 requires destroying or de-identifying personal information no longer needed; automate deletion jobs
  • Breach readiness: identifiers drive the NDB scheme's serious-harm test, so audit access and keep logs that let you assess a suspected breach within 30 days

⏱ 30-second answer

I start with classification: which fields are personal information and which are high-risk identifiers like driver's licence and Medicare numbers. Then minimisation: if we only need to verify a licence, we keep the verification result and a reference, not the number. Everything is encrypted in transit (TLS 1.2 minimum, 1.3 preferred, Encrypt=True) and at rest with TDE, but TDE is transparent to anyone who can query, so high-risk identifiers also get field-level encryption with Always Encrypted or AES-GCM keyed from Key Vault, plus an HMAC for lookups. Only roles that need identifiers can reveal them, with a reason and an audit record; APIs otherwise return masked DTOs, and logs are redacted. Data, backups and logs stay in Australia East/Southeast, and a retention job deletes or de-identifies what we no longer need (APP 11.2). Identifiers are what turn a breach into a notifiable one under the NDB scheme, so that's where protection goes. The trade-off: field-level encryption limits querying and adds key management, so I use it for the few fields whose breach causes the most harm.

🗣 Full answer (senior)

How I would answer this in an interview

"The first question I ask is: do we need to hold this at all? Breaches of Australian identity documents - the Optus and Medibank incidents - showed that the most harmful data is often data the company didn't need to keep. So I classify every field: ordinary personal information like name and email, sensitive information under the Privacy Act like health data, and high-risk government identifiers like driver's licence, passport and Medicare numbers. Then I minimise. If the business needs to verify identity, we call the Document Verification Service, store the result, the verification date and maybe the last few digits, and discard the full number.

For what we keep, encryption is layered. TLS everywhere, including Encrypt=True to Azure SQL. Transparent Data Encryption is on by default in Azure SQL, but it only protects the data files and backups: anyone who can query the database, including a SQL injection, sees plaintext. So the identifiers get field-level protection: Always Encrypted, where the client driver encrypts and the column master key lives in Key Vault, or application-level AES-GCM in a value converter. Either way I add a keyed hash column so we can find a record by licence number without decrypting the table.

Then exposure: APIs return DTOs with masked values like •••• 4821, only a support role with a recorded reason can reveal the full value, every reveal is audited, and logs go through redaction. Data residency means the database, backups, Blob storage, Log Analytics and any AI services sit in Australia East or Southeast, and I check where third-party processors store data, because APP 8 makes us accountable for overseas disclosure. The mistake I see is 'we have TDE, so we're encrypted'. The senior position is that the safest PII is the PII you deleted, so I build the retention job on day one."


Classification and handling

Class Examples Handling
Public Product names, published prices No restriction
Internal Order ids, internal notes Authenticated access
Personal Name, email, phone, address, DOB Access control, TLS, TDE, masking in logs, retention
Sensitive (Privacy Act definition) Health, racial origin, biometrics Consent to collect, field-level encryption, restricted roles
High-risk identifiers Licence, passport, Medicare, TFN Avoid storing; else field-level encryption, keyed hash for lookup, reveal-with-reason, short retention

Encryption layers

Layer Protects against Doesn't protect against
TLS 1.2/1.3 Network eavesdropping Anything at either end
TDE (service-managed or customer-managed key) Stolen disks, backup files Anyone who can run queries
Always Encrypted DBAs, SQL injection reading the column, database admins of the platform The app itself, if compromised; limited querying
App-level AES-GCM Same as Always Encrypted; portable to other stores Querying beyond equality via a keyed hash

Production example

For [an insurance onboarding API], we replaced stored licence numbers with Document Verification Service results plus the last 3 digits, and encrypted the remaining [~1.2 million] Medicare numbers with Always Encrypted and an HMAC lookup column. A later incident where a reporting user's credentials were phished exposed [names and suburbs] but no identifiers, which the privacy officer assessed as [not likely to cause serious harm]. Insert latency rose by [~3 ms] per record.

🔍 What the interviewer is checking

Checks whether the candidate treats PII handling as a design discipline (classify, minimise, protect, retain) with Australian obligations in mind, not just "encrypt it".

Green flags

  • Starts with classification and minimisation.
  • Knows TDE's limits and when to use Always Encrypted or app-level encryption.
  • Uses keyed hashes for lookups and DTOs with masking.
  • Mentions residency including logs and third parties, and APP 8.
  • Builds retention and deletion.

Red flags

  • "We use HTTPS and TDE, so it's encrypted."
  • Stores full identifiers without questioning the need.
  • Plain SHA-256 for identifier lookups.

📚 Learn in depth

1. Why identifiers are the crown jewels

A name and email enable spam. A licence or Medicare number plus DOB and address enables identity fraud and can cost the person a replacement licence card. That difference drives the NDB scheme's "serious harm" test, regulators' expectations, and the cost of a breach (replacement documents, credit monitoring, class actions, and after the 2024 amendments, a statutory tort for serious invasions of privacy and higher OAIC penalties).

2. Minimisation patterns

Need Instead of storing Store
Verify identity Full licence number DVS result, verification id, date, last 3-4 digits
Match returning customer Full identifier Keyed hash (HMAC-SHA256 with a Key Vault key)
Age check Full DOB IsOver18 and the date it was checked, or birth year
Analytics Identifiable events Pseudonymous id, aggregated or de-identified data
Payments Card numbers Payment provider token (keeps you out of PCI DSS scope)

3. Always Encrypted internals

  .NET app (Microsoft.Data.SqlClient, Column Encryption Setting=Enabled)
     |  1. reads column metadata: CEK (encrypted) + CMK path (Key Vault)
     |  2. unwraps CEK with Key Vault (app identity needs unwrapKey)
     |  3. encrypts parameter values client-side (AEAD_AES_256_CBC_HMAC_SHA_256)
     v
  Azure SQL  <- only ever sees ciphertext for the column
  • Deterministic encryption allows equality lookups, joins and grouping but leaks equality patterns (same plaintext -> same ciphertext). Randomised is stronger but not queryable.
  • Secure enclaves (VBS enclaves in Azure SQL) allow range comparisons, LIKE and in-place encryption of existing data inside a trusted enclave.
  • EF Core works with Always Encrypted through the connection string; queries must be parameterised and column types must match exactly.
  • Costs: key unwrap on first use (cached), larger columns, limited operators, and tooling like SSMS needs the key to show values.

4. App-level encryption with a value converter

An alternative when you need portability (Cosmos DB, Blob) or control. Use AesGcm with a data key wrapped by a Key Vault key (envelope encryption), store keyId | nonce | ciphertext | tag, and add a separate HMAC column for lookups. Rotation means re-wrapping data keys, or re-encrypting rows in the background by key id.

5. Masking and least exposure

  • API layer: DTOs expose LicenceLast4, never the entity. Reveal endpoints require a specific policy, a reason, and write an audit row.
  • Database: dynamic data masking for support tooling (convenience only), row-level security for tenancy.
  • Logs and telemetry: Microsoft.Extensions.Compliance.Redaction with data classification attributes, HTTP logging that excludes bodies, Application Insights telemetry processors that scrub query strings.
  • Non-production: no production PII in test environments; generate synthetic data or use masked copies.

6. Data residency and cross-border disclosure

  • Put databases, storage, backups (geo-redundant pairs Australia East <-> Australia Southeast stay in Australia), Log Analytics workspaces, Azure OpenAI deployments and Front Door/WAF logs in Australian regions.
  • Check what leaves: Application Insights in an Australian region, email and SMS providers, support tools, error trackers, AI APIs.
  • APP 8: before disclosing to an overseas recipient you must take reasonable steps to ensure they don't breach the APPs, and you remain accountable. Government contracts (and the Hosting Certification Framework) often require Australian hosting by certified providers.

7. Retention and deletion

  • APP 11.2: take reasonable steps to destroy or de-identify personal information you no longer need for any permitted purpose, unless a law requires you to keep it.
  • Define retention per class (e.g. verification artefacts 90 days, closed accounts 7 years for AML/CTF records) and implement it as a scheduled job (BackgroundService or Azure Function) with logging.
  • Remember backups, data warehouses, log retention and Blob soft delete; deletion isn't done until all copies age out.

8. Access auditing

Record who viewed or revealed sensitive fields, from where, and why. SQL auditing for direct access; application audit events for reveals. These records are what let you scope a breach quickly.

Try it yourself

  1. Run SQL Server's data discovery and classification on a sample database and add ADD SENSITIVITY CLASSIFICATION labels to identifier columns.
  2. Encrypt one column with Always Encrypted (deterministic) using a Key Vault CMK, then query it from a .NET app with Column Encryption Setting=Enabled.
  3. Write an EF Core value converter with AesGcm and an HMAC lookup column; benchmark inserts with and without it.
  4. Add [PrivateData]-style classification attributes and redaction to a log message containing a licence number.
  5. List every Azure resource and third-party service that receives your app's data and its region.

💻 Code

Vulnerable: the entity goes straight to the client, the full identifier is stored and logged:

// GET /customers/42 returns everything, including the full licence and Medicare number.
app.MapGet("/customers/{id:int}", async (int id, AppDb db, ILogger<Program> log, CancellationToken ct) =>
{
    var c = await db.Customers.FindAsync([id], ct);
    log.LogInformation("Loaded customer {@Customer}", c); // PII and identifiers into App Insights
    return c;                                              // entity serialised to any authenticated caller
});

Exploit in one line: any authenticated user (or anyone with log access) reads licenceNumber and medicareNumber for every customer they can enumerate.

Fixed: minimised storage, encrypted identifier with a keyed-hash lookup, masked DTO, audited reveal:

namespace Onboarding;

public sealed class Customer
{
    public int Id { get; set; }
    public required string FullName { get; set; }
    public required string MedicareCipher { get; set; }   // AES-GCM envelope: keyId|nonce|ct|tag
    public required byte[] MedicareLookup { get; set; }   // HMAC-SHA256(medicare) with a Key Vault key
    public required string MedicareLast4 { get; set; }
    public string? LicenceVerificationId { get; set; }    // DVS result; full licence number never stored
    public DateOnly? VerifiedOn { get; set; }
}

public sealed record CustomerDto(int Id, string FullName, string Medicare, bool LicenceVerified);

public static class CustomerEndpoints
{
    public static void Map(WebApplication app)
    {
        app.MapGet("/customers/{id:int}", async (int id, AppDb db, CancellationToken ct) =>
            await db.Customers
                .Where(c => c.Id == id)
                .Select(c => new CustomerDto(c.Id, c.FullName, "•••• " + c.MedicareLast4,
                                             c.LicenceVerificationId != null))
                .SingleOrDefaultAsync(ct) is { } dto ? Results.Ok(dto) : Results.NotFound())
           .RequireAuthorization("CustomerRead");

        // Revealing the full value needs a stronger policy, a reason, and leaves an audit trail.
        app.MapPost("/customers/{id:int}/medicare/reveal", async (
                int id, RevealRequest req, AppDb db, IFieldProtector protector,
                IAuditLog audit, HttpContext http, CancellationToken ct) =>
            {
                var c = await db.Customers.FindAsync([id], ct);
                if (c is null) return Results.NotFound();
                await audit.WriteAsync(new("medicare.reveal", id, http.User.FindFirst("oid")!.Value, req.Reason), ct);
                return Results.Ok(new { medicare = await protector.UnprotectAsync(c.MedicareCipher, ct) });
            })
           .RequireAuthorization("SensitiveReveal");
    }
}

public sealed record RevealRequest([property: System.ComponentModel.DataAnnotations.Required] string Reason);
public interface IFieldProtector { Task<string> UnprotectAsync(string cipher, CancellationToken ct); }
public interface IAuditLog { Task WriteAsync(AuditEvent e, CancellationToken ct); }
public sealed record AuditEvent(string Action, int CustomerId, string UserOid, string Reason);

Tag the columns so classification shows up in SQL auditing and Defender for SQL:

ADD SENSITIVITY CLASSIFICATION TO dbo.Customers.MedicareCipher
    WITH (LABEL = 'Highly Confidential', INFORMATION_TYPE = 'National ID', RANK = CRITICAL);
ADD SENSITIVITY CLASSIFICATION TO dbo.Customers.FullName
    WITH (LABEL = 'Confidential', INFORMATION_TYPE = 'Name', RANK = MEDIUM);

⚠ Common mistakes

  • Mistake: Saying "the database is encrypted" because TDE is on. Why it is wrong: TDE decrypts transparently for every query, so SQL injection, over-privileged users and reporting tools see plaintext. Instead: Use TDE as a baseline and add field-level encryption for high-risk identifiers.
  • Mistake: Storing full government identifiers "in case we need them". Why it is wrong: APP 3 limits collection to what's reasonably necessary, APP 11.2 requires deletion when no longer needed, and they dominate breach harm. Instead: Store verification results, last digits or keyed hashes.
  • Mistake: Returning EF Core entities from APIs. Why it is wrong: Every new column, including sensitive ones, is automatically exposed. Instead: Project to purpose-built DTOs with masked values.
  • Mistake: Using plain SHA-256 of an identifier as a lookup key. Why it is wrong: Identifiers have a small, structured space, so an attacker can brute-force every possible value offline. Instead: Use HMAC with a secret key held in Key Vault.
  • Mistake: Logging request bodies or whole objects with {@Customer}. Why it is wrong: PII spreads into log stores with wider access and longer retention. Instead: Log ids only and apply redaction.
  • Mistake: Copying production data into test environments. Why it is wrong: Test environments have weaker controls and more people with access, and it's still a disclosure. Instead: Synthetic or properly de-identified data.
  • Mistake: Assuming Australian hosting covers everything. Why it is wrong: Telemetry, email providers, support tools and AI APIs may process data overseas, triggering APP 8. Instead: Inventory every processor and region.
  • Mistake: Having a retention policy but no deletion job. Why it is wrong: The policy is ignored in practice and old data accumulates for years. Instead: Automate deletion or de-identification and monitor that it runs.

🏛 Senior insight: trade-offs

The order of controls matters: don't collect, then don't keep, then don't expose, then encrypt. Engineers tend to jump to encryption because it's a technical problem, but the biggest risk reduction usually comes from deleting fields and adding a retention job. Field-level encryption is worth its cost for a handful of high-risk identifiers; applying it to every column makes the system slow, unqueryable and hard to operate, and teams then disable it.

App-level encryption moves key management into your team: you own key wrapping, rotation by key id, re-encryption jobs, and making sure the key-access identity isn't the same one an attacker gets with a SQL injection. If the team can't operate that reliably, Always Encrypted with a Key Vault column master key is the safer choice. Access to reveal identifiers should be a policy, not a UI flag: a role or attribute-based rule ("support agent assigned to this case") enforced in a handler, with the reason and user written to an audit log.

This connects directly to the NDB scheme: when assessing a suspected breach, the questions are what information was exposed, how sensitive, and whether serious harm is likely. Ciphertext without key access, masked values and deleted records shrink the answer. Measure exposure: records of each class held, who and what can read them, retention age, and reveals per week.

Technique When it fits Cost When not to
Minimisation / tokenisation Identifiers you only need to verify or match Product conversations, DVS or payment vault integration When law requires retaining the value
Always Encrypted SQL Server columns needing protection from DBAs and injection Limited operators, driver config, key access Columns needing full-text or range search without enclaves
App-level AES-GCM + HMAC Portable across stores, fine-grained key control Your own crypto code, rotation jobs When the team can't own key management safely
Dynamic data masking Support screens and ad-hoc reporting convenience Low As a security boundary

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions logging or telemetry. Why: Checks the candidate keeps PII out of logs with redaction and retention rules.
    How to answer

    Treat logs as a data store that attackers and too many staff can read. Never log secrets (passwords, tokens, Authorization headers, connection strings, card numbers) and keep personal information out: log identifiers like CustomerId, not names, emails or request bodies.

    Enforce it in code rather than by memory: Microsoft.Extensions.Compliance.Redaction lets you classify fields with attributes, map classifications to redactors (erase, or HMAC for a stable pseudonym) with AddRedaction, and apply them to logs with EnableRedaction. Use header allowlists in HTTP logging.

    In Australia, APP 11 requires reasonable steps to protect personal information and APP 11.2 requires destroying or de-identifying it when no longer needed, so retention matters, and a leaked log store can be a notifiable data breach. The trade-off: less detail in logs versus a smaller breach surface.

  2. When: Candidate proposes application-level encryption. Why: Checks the candidate can implement app-level field encryption correctly with AesGcm.
    How to 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.

  3. When: Candidate mentions Key Vault keys for Always Encrypted or AES. Why: Checks key management behind field-level encryption: envelope encryption and rotation.
    How to answer

    Treat keys as long-lived identities with a lifecycle. In Azure Key Vault, a key is non-exportable: you send data to it for wrap/unwrap/sign, while a secret is a value your app downloads (connection strings, API keys). For data encryption use envelope encryption: generate a random data encryption key (DEK) locally, encrypt with AES-GCM, and have a Key Vault key-encryption key (KEK) wrap the DEK; store only the wrapped DEK beside the data.

    Rotation without downtime depends on key ids: every ciphertext records which key version wrapped it, new writes use the newest version, old versions stay enabled for decrypt, and a background job optionally rewraps DEKs before old versions are disabled. Use Premium (HSM-backed) or Managed HSM when regulation or key value demands it. The trade-off is security and auditability versus latency, throttling and operational complexity.

🛠 Real-world problems: how you handle them

Phished reporting account exposes customer data but no identifiers
Situation
[An insurance onboarding platform] holding [~1.2 million] customer records in Azure SQL. A year earlier the team had minimised licence numbers to DVS results and encrypted Medicare numbers with Always Encrypted.
Signals
Microsoft Defender for SQL alert for unusual data extraction by a reporting user from an unfamiliar IP; Entra ID Protection flagged a risky sign-in for the same account.
Investigation
Used SQL auditing in Log Analytics to list every query the account ran in the window and the columns touched. Confirmed the account had no access to the Always Encrypted column master key in Key Vault, so Medicare values returned as ciphertext. Checked Entra sign-in logs to confirm the session origin and the absence of other sign-ins.
Resolution
Immediate: disabled the account, revoked sessions, reset credentials and required phishing-resistant MFA for reporting users. Gave the privacy officer the exact columns and row counts exposed (names and suburbs, no identifiers) for the NDB assessment. Longer term: moved reporting to a de-identified replica.
Prevention
Conditional Access with phishing-resistant MFA for all data-access roles, reporting on a de-identified dataset, SQL sensitivity classification reviewed each quarter, and alerts on bulk reads of classified columns.

How to tell it (STAR)

**S:** We held [about 1.2 million] customer records, including Medicare and licence numbers, in [our onboarding platform]. **T:** I [led] reducing what a breach could expose. **A:** We stopped storing licence numbers, keeping only the verification result, and encrypted Medicare numbers with Always Encrypted, using a keyed hash for lookups and masked DTOs in the API. **R:** When a reporting user was phished a year later, the attacker got [names and suburbs] but only ciphertext for identifiers; the privacy officer assessed it as [not an eligible breach], and the response took [hours rather than weeks].

More in Senior Security Topics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me