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.
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.
"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=Trueto 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."
| 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 |
| 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 |
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.
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
Red flags
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).
| 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) |
.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
LIKE and in-place encryption of existing data inside a trusted enclave.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.
LicenceLast4, never the entity. Reveal endpoints require a specific policy, a reason, and write an audit row.Microsoft.Extensions.Compliance.Redaction with data classification attributes, HTTP logging that excludes bodies, Application Insights telemetry processors that scrub query strings.BackgroundService or Azure Function) with logging.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.
ADD SENSITIVITY CLASSIFICATION labels to identifier columns.Column Encryption Setting=Enabled.AesGcm and an HMAC lookup column; benchmark inserts with and without it.[PrivateData]-style classification attributes and redaction to a log message containing a licence number.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);
{@Customer}. Why it is wrong: PII spreads into log stores with wider access and longer retention. Instead: Log ids only and apply redaction.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 |
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.
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.
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.
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].
Last updated 23 Nov 2026.