Every week, somewhere in a Spanish bank or insurer, a well-intentioned assistant receives a prompt like this:
Summarise the complaint from customer 12345678Z regarding the direct debit to ES91 2100 0418 4502 0005 1332, and draft a reply.
The model does not need the DNI or the IBAN to summarise the complaint. The provider certainly does not need them. Yet they leave the network, are processed under the provider's terms, and possibly end up in a log nobody in your organisation controls.
Removing them before the call is the most effective data-protection control you can put in front of a model. It is also easy to do badly. This article covers how to detect European identifiers reliably, how to decide between masking and blocking, and, just as important, what masking does not achieve in GDPR terms. The examples come from the detection engine we built for the Axium gateway, but the patterns apply to any implementation.
Why a regular expression is not enough
The first version of every PII filter is a list of regular expressions. It fails in both directions at once.
It over-matches, because European identifiers are short strings of digits and letters that look like many other things. Eight digits and a letter is a DNI, and also an invoice reference, a product code, a tracking number. A regular expression for a 12-digit Spanish social security number matches a fair share of every phone and account number in your corpus.
And it under-matches, because real text is messy. People write 12.345.678-Z, 12345678 Z, X-1234567-L. Documents pasted from PDFs carry non-breaking spaces and typographic dashes. A pattern written against a clean test string misses half of production.
The fix is not a cleverer regular expression. It is a pipeline with three stages, each of which removes a different kind of error.
The three-stage pattern: shape, checksum, context
Stage 1: shape
A deliberately tolerant pattern finds candidates. Tolerant about separators: dots, hyphens, spaces, non-breaking spaces and typographic dashes are all accepted inside an identifier. Strict about one thing: a line break is never a separator, because a number at the end of one line and a letter at the start of the next are almost never one identifier.
Each pattern carries a base score that reflects how specific its shape is. An unspaced DNI (12345678Z) is a fairly specific shape, base 0.5. The same with spaces is far more ambiguous, base 0.3, and only matches with an uppercase letter, so pagó 12345678 a Juan is not mistaken for an identifier. A Spanish passport number (three letters and six digits) has a shape so common that its base score is 0.05: on its own it will never be reported.
Stage 2: checksum
Most European identifiers carry a check digit. This is the single most valuable signal available, because it is the difference between "looks like a DNI" and "is a valid DNI". When the checksum validates, the detection is confirmed and its score becomes 1.
| Identifier | Structure | Check |
|---|---|---|
| DNI / NIF (persons) | 8 digits + letter | Number mod 23, mapped to TRWAGMYFPDXBNJZSQVHLCKE. 12345678 → remainder 14 → Z. |
| NIE (foreign nationals) | X, Y or Z + 7 digits + letter | Replace X/Y/Z with 0/1/2, then the same mod 23. |
| NIF (legal entities, formerly CIF) | Entity-type letter + 7 digits + control | Weighted digit sum; the control is a digit or a letter depending on the entity type. |
| IBAN | ES + 2 check digits + 20 digits (24 chars) | ISO 13616: rearrange, convert letters to numbers, mod 97 must equal 1. |
| CCC (domestic account) | 4 bank + 4 branch + 2 control + 10 account | Two mod-11 control digits with weights 1, 2, 4, 8, 5, 10, 9, 7, 3, 6. |
| NSS (social security) | 2 province + 8 digits + 2 check | Common implementation: mod 97 over province and number. |
| Payment card | 13 to 19 digits | Luhn. |
The official algorithm for the DNI and NIE letter is published by the Ministerio del Interior. For a mod-23 check letter, the chance that a random 8-digit number paired with a random letter validates is about 1 in 23. For IBAN's mod 97, about 1 in 97. Those odds are what turn a noisy pattern into a precise one.
One design decision here is less obvious: a failed checksum should not discard the candidate. People mistype identifiers. A customer who writes their DNI with the wrong letter has still disclosed their DNI. So a failed checksum leaves the candidate at its base score, where the third stage can still rescue it.
Stage 3: context
Words around the candidate are the last signal. "DNI", "NIF", "documento nacional de identidad", "identificación" near an 8-digit-plus-letter candidate make it far more likely to be what it looks like. In our engine a context word within 40 characters on either side adds 0.35 to the score, and anything that ends below 0.4 is dropped.
Put together, the stages produce behaviour that is easy to reason about:
| Input | Shape | Checksum | Context | Result |
|---|---|---|---|---|
cliente 12345678Z |
DNI, 0.5 | valid → 1.0 | — | detected |
DNI 12345678A (typo) |
DNI, 0.5 | invalid, stays 0.5 | "DNI" +0.35 | detected (0.85) |
importe 12.345.678 euros |
no letter | — | — | not a DNI |
tel 600 123 456 |
no match | — | — | not an identifier |
pasaporte ABC123456 |
passport, 0.05 | none | "pasaporte" +0.35 | 0.40, detected |
ref ABC123456 |
passport, 0.05 | none | none | dropped |
When two detections overlap, one wins: the highest score, then the longest span. This prevents a single IBAN from also being reported as an embedded account number and a string of digits.
The most common false positive is a date
In practice, the noisiest category is not an identifier at all. Dates are personal data in some contexts (a date of birth) and noise in most others (a due date, a timestamp). Most deployments are better served by excluding dates from masking explicitly than by letting every timestamp turn into a placeholder. Decide it per application.
Mask, block or keep
Detection tells you what is in the prompt. Policy decides what happens to it. There are three sensible actions, and the right one depends on the identifier and on the use case.
Mask replaces the value with a typed placeholder before the request leaves:
Summarise the complaint from customer
<ES_NIF>regarding the direct debit to<IBAN_CODE>, and draft a reply.
The model still knows that there was a DNI and an IBAN, which is usually all it needs to produce a sensible summary. This is the right default for identifiers that are incidental to the task.
Block refuses the whole request. Use it where the presence of the data means the request should not be happening: card numbers in a support assistant, health data in a general-purpose tool. Blocking is also the right action when masking would destroy the task, because a model asked to "check whether this IBAN is valid" cannot do anything useful with <IBAN_CODE>, and that call should not go to an external model at all.
Keep lets an identifier through deliberately. It exists so the choice is explicit and logged rather than accidental: an internal assistant whose job is to reason about company tax identifiers might keep legal-entity NIFs while masking everything about natural persons.
A policy should be readable by someone who is not an engineer. Ours is a JSON document attached to each application:
"dlp_prompt": {
"enabled": true,
"options": {
"countries": ["ES", "GLOBAL"],
"except": ["DATE_TIME"],
"policy": {
"default": "mask",
"kinds": { "BANK_ACCOUNT": "block" },
"entities": { "ES_CIF": "keep" }
}
}
}
Precedence runs from most to least specific: an entity rule overrides a kind rule, which overrides the default. A single block anywhere in the prompt refuses the whole request, and the refusal is returned to the client as a permission error, so the calling application can tell the user why.
Placeholders without numbers, on purpose
Our placeholders are not numbered. Two different DNIs in one prompt both become <ES_NIF>. A numbered scheme (<ES_NIF_1>, <ES_NIF_2>) lets the model keep two people apart, and paired with a stored mapping it lets you put the real values back into the response.
We chose not to keep that mapping. A mapping table from placeholders to real identifiers is itself a store of personal data, linked to every prompt, that has to be secured, retained and eventually deleted. Not having one means there is nothing to leak. The cost is that the model cannot distinguish two masked individuals, and responses cannot be automatically re-personalised. For summarisation, classification and drafting, the dominant enterprise use cases, that cost is low. If your use case needs re-identification, make it a deliberate design with its own security review, not a side effect of the masking layer.
Where in the request to apply it
Detection has to run on the text the model will read, and only on that text. A modern request body is a nested structure of messages, content parts, tool definitions, images and file data. Scanning every string is wrong in both directions: it misses nothing, but it corrupts base64-encoded files and URLs when a random substring happens to validate as an identifier.
The approach that works is to extract the model-visible text (system instructions and user input parts), detect on that, and then replace each detected value across the text fields of the body, longest first, while skipping fields that carry encoded data. Two further ordering rules matter:
- Mask before caching. If the gateway caches responses, the cache key must be computed on the masked body. Otherwise a cache becomes a lookup table keyed by personal data.
- Mask before logging. If request content is logged at all, log the masked version. And the trace of the masking itself should record entity types and counts, never values. A log that says "masked 2 × ES_NIF, 1 × IBAN_CODE" is evidence. A log that contains the values it masked is the leak.
Files are a different problem
Prompts are increasingly accompanied by documents. The same engine can scan the text of a PDF, page by page, but two honest limits apply. A scanned PDF without a text layer has no text to scan unless you add OCR. And a PDF cannot be safely rewritten to remove values in place, because the visual layer and the text layer are separate. For files, the realistic actions are therefore report or block, not mask. Treat a document upload as the higher-risk path, and default to blocking where a document type routinely carries identifiers.
What masking does not do
This is where most vendor material stops, and where the legal questions start.
Masking identifiers is not anonymisation. Our engine, like most rule-based detectors, finds structured identifiers: national IDs, account numbers, cards, emails, IP addresses. It does not detect names, postal addresses or free-text descriptions of people. "The 54-year-old branch manager in Teruel who complained twice in March" contains no identifier and may still identify one person. An empty detection result means "nothing the engine knows how to look for", not "no personal data".
For you, masked data is still personal data. The EDPB's draft guidelines on pseudonymisation are explicit that pseudonymised data remains personal data for the controller who can link it back. You hold the original prompt; your processing remains within the GDPR.
For the provider, it may not be, and that is the point. In EDPS v SRB (C-413/23 P), decided in September 2025, the Court of Justice held that identifiability must be assessed from the recipient's perspective: data that a recipient has no reasonable means to re-identify may not be personal data for that recipient. A prompt from which the identifiers have been removed, sent to a provider that holds no key to restore them, is much closer to that position than the original. That does not remove your obligations as controller, including transparency about recipients, but it materially changes the risk of the transfer. The EDPB's draft guidelines on anonymisation, consulted on in 2026, add that anonymity is relative and must be reassessed over time, which is one more reason to treat masking as one layer, not the whole answer.
Detection must fail visibly. Any detection engine can fail: malformed input, an unexpected encoding, a timeout. Decide in advance whether a request whose scan failed goes through unmasked or is refused, and make the outcome visible in the trace either way. For applications where the policy says certain data must never leave, refusing is the only consistent choice.
A checklist
- Detect with shape, checksum and context; never with shape alone.
- Accept real-world separators; never treat a line break as one.
- Do not discard a candidate because its checksum fails; let context decide.
- Default to masking incidental identifiers; block where their presence means the request should not happen.
- Exclude dates unless dates of birth are the concern.
- Apply masking to model-visible text only, before cache and before logs.
- Record what was masked as types and counts, never values.
- Treat documents as a separate, higher-risk path.
- Document that masking identifiers is not anonymisation, and what else is in place for names and free text.
The AI gateway overview explains why this control belongs in a gateway rather than in each application, and DORA and AI covers how the resulting evidence fits a financial-sector audit. If you want to see the detection running on your own documents, book a demo.