Pseudonymising Personal Data Before It Reaches an LLM
Every prompt sent to a hosted LLM leaves your infrastructure. If it carries a customer's name, card number or IBAN, that data now sits with the provider, in its logs and possibly in yours. I recently built and evaluated a pseudonymisation layer for an LLM pipeline: it swaps personal data for tokens before the call and puts the real values back in the answer. This post covers the rules behind it, how the layer works, what it catches and misses, and the problems it cannot solve. All code and examples use invented data.
In short
- Pseudonymised data is still personal data under the GDPR. Masking reduces what a provider, a log or a breach can expose; it does not take the data out of scope.
- Emails, card numbers, IBANs and phones fall to regular expressions with checksums. Names have no pattern and need a NER model or a list of known names.
- On messy invented messages, regexes alone masked 13 per cent of personal data; adding a zero-shot NER model masked 94 per cent, at thousands of times the detection time.
- Text masking does not hide what context reveals, and it misses images, embeddings and logs, so provider terms and data minimisation come first.
The rules that apply
Three frameworks shape this work. The GDPR decides what counts as personal data and what you must do with it. ISO/IEC 27001 turns that into security controls an auditor checks. The PCI DSS sets stricter rules for payment cards. Mapped onto one LLM call, they look like this:
| Source | What it says | What it means here |
|---|---|---|
| GDPR Art. 5(1)(c) | Data must be "adequate, relevant and limited to what is necessary" | Send the model only the text the task needs. The cheapest data to protect is data never sent. |
| GDPR Art. 25 | Data protection by design, through measures "such as pseudonymisation" | Masking belongs in the architecture, not added after an incident. |
| GDPR Art. 32(1)(a) | Security measures include "the pseudonymisation and encryption of personal data" | Tokens for the prompt, encryption for the token table. |
| GDPR Art. 28 | Use "only processors providing sufficient guarantees" | The LLM provider is a processor: a data processing agreement, retention terms and security commitments. |
| GDPR Art. 44 | Transfers outside the EU only under the conditions of Chapter V | Know where the provider processes the prompt. |
| GDPR Art. 35 | An impact assessment for high-risk processing, "in particular using new technologies" | Sending customer documents to an LLM at scale is a likely candidate for one. |
| ISO/IEC 27001:2022, Annex A | 8.11 Data masking, 8.12 Data leakage prevention, 8.24 Use of cryptography, 8.10 Information deletion, 8.15 Logging, 5.34 Privacy and protection of PII | The controls an auditor will ask about for this pipeline. |
| ISO/IEC 27701 and 27018 | A privacy information management system (a stand-alone standard since its 2025 revision); a code of practice for PII in public clouds acting as processors | The privacy management layer above the controls, and a yardstick for cloud providers. |
| PCI DSS 3.4.1 | A card number must be "masked when it is displayed" | Even a restored answer should show only the last digits. |
The key legal point is in Recital 26: pseudonymised data "should be considered to be information on an identifiable natural person". The GDPR still applies, because whoever holds the token table can reverse it. Only anonymous information, which "does not relate to an identified or identifiable natural person", falls outside the regulation.
Choosing a technique
| Technique | The model sees | Reversible | Good for |
|---|---|---|---|
| Redaction | [REDACTED] | No | Logs and exports nobody reads back |
| Masking | **** 6467 | No | Showing a card or account to a person |
| Typed tokens | [PERSON_1], [CARD_1] | Yes, with the token table | LLM calls whose answer must name real values |
| Fake values | "Anna Smith" | Fragile | Training and test data |
| Keyed hashing | 3f9a… | No | Joining records without exposing values |
| Encryption | Ciphertext | Yes, with the key | Storage and transport, not prompts |
For an LLM call, typed tokens are the practical choice. The model still sees that a person asked for a refund on a card, which is usually all it needs, and the application can put the real values back. Fake names read more naturally, but they restore by string matching, which breaks when the model writes "Ms Smith" or the fake name also occurs in the text.
The pipeline
Cleaning removes zero-width characters and look-alike letters that would let a value slip past a pattern. Three detectors run on the cleaned text, and overlapping finds merge into one span. Each value gets a typed token, and the token table is encrypted under a key that stays in the application. After the call, the restore step puts the values back and reports any token the model changed.
Identifiers: patterns and checksums
Emails, card numbers, IBANs and phone numbers have a shape, so regular expressions find them in microseconds. A pattern alone over-masks: any 16-digit order number looks like a card. A checksum removes most of those false hits. Card numbers end in a Luhn check digit, which "tells you whether the payment card number is a possible and valid number", in the PCI Security Standards Council's words, and an IBAN must leave a remainder of 1 modulo 97 under ISO 13616:
def luhn_ok(digits: str) -> bool:
"""Luhn (mod 10) check used by payment card numbers."""
total = 0
for i, ch in enumerate(reversed(digits)):
d = int(ch)
if i % 2 == 1:
d = d * 2 - 9 if d > 4 else d * 2
total += d
return total % 10 == 0
def iban_ok(raw: str) -> bool:
"""ISO 13616 check: move the first four characters to the end, letters to numbers, mod 97 == 1."""
s = re.sub(r"\s", "", raw).upper()
if not 15 <= len(s) <= 34:
return False
rearranged = s[4:] + s[:4]
return int("".join(str(int(c, 36)) for c in rearranged)) % 97 == 1
One random digit string in ten passes the Luhn check by chance, so the checksum cuts false hits by about 90 per cent, not to zero. Patterns also break in predictable ways: a card number split across two lines, a national phone number without a country code, a lower-case IBAN, "maria dot keller at example dot com". Each needs a rule of its own, and some are better left to a model.
Names: lists and models
A name has no fixed shape, so no regex finds one. There are two sources. A list of names the application already knows, such as the account holder or the parties to a contract, is exact and fast but covers only those names. A named-entity recognition (NER) model finds the rest. Open options include Presidio, started at Microsoft and now community-run, which combines NER with pattern recognisers, and GLiNER, "a compact NER model trained to identify any type of entity". GLiNER takes its labels as plain text at inference time, so one model covers people, companies and identifiers:
from gliner import GLiNER
model = GLiNER.from_pretrained("urchade/gliner_multi_pii-v1") # Apache-2.0
labels = ["person", "organization", "email", "phone number", "credit card number", "iban"]
entities = model.predict_entities(text, labels, threshold=0.5)
Presidio's documentation states the limit of every such tool: "there is no guarantee that Presidio will find all sensitive information. Consequently, additional systems and protections should be employed."
What each detector catches
I generated 200 invented customer messages with planted names, companies, emails, card numbers, IBANs and phones, plus decoys: order numbers that fail the Luhn check and product names. A clean set used tidy templates. A messy set used lower case, first names alone, short company names, card numbers broken across lines, national phone formats and obfuscated emails. A mention counts as masked if any mask touches it.
On the clean set, regexes masked every email, card, IBAN and phone, and no name; adding GLiNER masked every planted mention, along with 27 product names and order numbers that were not personal data. The messy set is closer to real text:
| Messy set | Regexes with checksums | Regexes + GLiNER PII |
|---|---|---|
| Mentions masked | 71 of 561 (13 per cent) | 526 of 561 (94 per cent) |
| Masks that hit nothing | 0 of 71 | 32 of 560 |
| Missed | Every name; split cards, obfuscated emails, lower-case IBANs, national phones | Mostly first names written alone |
| Over-masked | Nothing | Product names tagged as companies |
The model's threshold sets the balance between misses and false hits. Lowering it from 0.5 to 0.1 masked 97 per cent of mentions instead of 94, while the share of masks that hit nothing rose from 5.7 to 9.1 per cent:
For privacy, a miss costs more than a false hit, so the threshold should sit lower than the default, as far as the task's quality allows. The coverage came at a price in time:
Invented messages are easier than real documents, so read these numbers as the shape of the trade-off, not as rates to expect. Hand-written hard cases show where the combination struggles and where it copes:
| Input | Result |
|---|---|
| the invoice came from orange and apple, not from next. | "orange and apple" as one company; "next" missed |
| maria keller called again about her account. | "maria keller" masked as a person |
| write to maria dot keller at example dot com | Masked, but as a person and a company, not as an email |
| card 4539 1488 0343, then 6467 on a new line | The model masked the whole number; the regex did not |
| Ms Keller of Granite & Vale Ltd signed for Bluefin. | Person and both companies masked |
Company names are the hardest type. Many are ordinary words, many appear in short forms, and which organisations count as personal data at all is partly a policy question. On real documents I found them the largest source of leaks, ahead of people.
Tokens and the sealed table
Each value gets a token made of its type and a number. Every mention of the same entity must get the same token, short forms included: if "Maria Keller" is [PERSON_1] and a later "Ms Keller" becomes [PERSON_2], the model thinks two people are involved. The table linking tokens to values is the "additional information" that GDPR Article 4(5) requires to be "kept separately", so it is encrypted, and the key stays in the application:
NAME_KINDS = {"PERSON", "COMPANY"}
@dataclass
class Session:
key: bytes = field(default_factory=lambda: AESGCM.generate_key(bit_length=256))
table: dict[str, str] = field(default_factory=dict) # token -> value
index: dict[tuple[str, str], str] = field(default_factory=dict) # (kind, normalised value) -> token
def token_for(self, kind: str, value: str) -> str:
norm = re.sub(r"[\s-]", "", value).lower()
if kind in NAME_KINDS and (kind, norm) not in self.index:
# "Keller" after "Maria Keller": reuse the full name's token, so the model sees one person
for (k, _), token in list(self.index.items()):
if k == kind and value.lower() in self.table[token].lower().split():
self.index[(kind, norm)] = token
break
if (kind, norm) not in self.index:
n = 1 + sum(1 for t in self.table if t.startswith(f"[{kind}_")) # aliases add no table entry
token = f"[{kind}_{n}]"
self.index[(kind, norm)] = token
self.table[token] = value
return self.index[(kind, norm)]
def seal(self) -> bytes:
nonce = os.urandom(12)
return nonce + AESGCM(self.key).encrypt(nonce, json.dumps(self.table).encode(), None)
@staticmethod
def unseal(blob: bytes, key: bytes) -> dict[str, str]:
return json.loads(AESGCM(key).decrypt(blob[:12], blob[12:], None))
AES-GCM also detects tampering: a wrong key or a modified table raises an error instead of returning wrong values.
Restoring the answer
Models do not always copy tokens exactly. They change the case, swap the brackets, drop the underscore, translate the type or invent a token that was never in the prompt. The restore step puts exact tokens back first, then the changed ones it can tie to a real token, and reports everything else instead of guessing:
def show_card(pan: str) -> str:
"""Display form for a card number: last four digits only."""
return "**** " + re.sub(r"\D", "", pan)[-4:]
def restore(answer: str, table: dict[str, str], display: dict[str, Callable[[str], str]] | None = None) -> tuple[str, list[str]]:
"""Exact tokens first; then tokens the model bent ([person_1], (CARD-1), EMAIL 1). Unknown ones are reported."""
report: list[str] = []
display = display or {}
table = {t: display.get(t[1:].rsplit("_", 1)[0], lambda v: v)(v) for t, v in table.items()}
for token, value in table.items():
answer = answer.replace(token, value)
kinds = {t[1:].rsplit("_", 1)[0] for t in table}
def fix(m: re.Match) -> str:
kind, n = m.group(1).upper(), m.group(2)
if kind not in kinds:
return m.group()
token = f"[{kind}_{n}]"
if token in table:
report.append(f"altered {m.group()!r} -> restored")
return table[token]
report.append(f"unknown {m.group()!r} -> left as written")
return m.group()
return BENT.sub(fix, answer), report
Run on an invented message, the round trip looks like this:
checks: True False True
REGEX ONLY
Hi, this is Maria Keller from Northwind Logistics. Please refund card [CARD_1] and send the confirmation to [EMAIL_1] or call [PHONE_1]. Our IBAN is [IBAN_1]. Order 1234 5678 9012 3456 is unrelated. Ms Keller will sign.
REGEX + KNOWN NAMES
Hi, this is [PERSON_1] from [COMPANY_1]. Please refund card [CARD_1] and send the confirmation to [EMAIL_1] or call [PHONE_1]. Our IBAN is [IBAN_1]. Order 1234 5678 9012 3456 is unrelated. Ms [PERSON_1] will sign.
sealed table: 248 bytes
MODEL ANSWER
Refund issued to [CARD_1] for [person_1]; confirmation sent to (EMAIL_1). PERSON 1 can call [PHONE-1]. [PERSON_3] was not in the text.
RESTORED
Refund issued to **** 6467 for Maria Keller; confirmation sent to maria.keller@example.com. Maria Keller can call +44 20 7946 0958. [PERSON_3] was not in the text.
- altered '[person_1]' -> restored
- altered '(EMAIL_1)' -> restored
- altered 'PERSON 1' -> restored
- altered '[PHONE-1]' -> restored
- unknown '[PERSON_3]' -> left as written
wrong key: InvalidTag
The full module, pseudo.py, and the demo script need only the cryptography package.
Three details in that output are deliberate. The card number comes back as its last four digits, which applies the PCI rule at the point of display. The invented [PERSON_3] is left as written and reported. "Ms Keller" became [PERSON_1], not a second person. Some failures stay silent: a model that swaps two valid tokens puts the right names in the wrong places, and a dropped token loses a name. Asking the model to copy tokens exactly helps; checking critical fields against the source helps more.
Problems masking does not solve
Context identifies people. "[PERSON_1], the only female surgeon at the hospital in [LOCATION_1]" hides two words and identifies one person. Sweeney found that 87 per cent of the US population had "characteristics that likely made them unique based only on {5-digit ZIP, gender, date of birth}". LLMs are good at exactly this kind of inference: Staab et al. showed models inferring location, income and sex from Reddit comments with "up to 85% top-1" accuracy, and found that "common mitigations, i.e., text anonymization and model alignment, are currently ineffective" against it. Masking direct identifiers is necessary, but the remaining text can still identify a person.
Sensitive facts have no names. Health, religion, ethnicity and sexual orientation are special categories under GDPR Article 9, and they appear in free text as facts, not entities: "since my diagnosis", "after Friday prayers". A name detector does not see them. If such text reaches a provider, the question is whether it should be sent at all, not how to mask it.
Stable tokens make records linkable. Per-session numbering means [PERSON_1] in one call and [PERSON_1] in the next can be different people, so a provider cannot link them. Stable pseudonyms, such as a keyed hash of the email, keep identities consistent across calls and documents, which helps the task and lets anyone with the outputs link one person's records. Choose per use case, and do not reuse one pseudonym scheme everywhere.
The table is the key. Whoever holds the token table and its key can reverse everything. Keep keys out of logs, errors and job history, and delete the table when the session ends (ISO 27001 A.8.10). Stored outputs stay pseudonymised only while that holds.
Masking can break the task. If the job is to extract amounts from an invoice, masking amounts defeats it. Masking has to be set per use case, and its effect on quality measured.
What masking does not cover
| Exposure | Does text masking help? | Main control |
|---|---|---|
| Prompt text sent to the provider | Yes, for what it detects | Processor terms, zero retention, region |
| Page images and scans | No; masking the text but not the image also confuses the model | Image redaction, or not sending images |
| Embeddings and vector databases | Only if chunks pass through the masking layer | Mask before embedding; access control |
| Application logs and traces | Only if masking happens before logging | Log tokens, never values (A.8.15) |
| Inference from context | Little | Data minimisation; send less text |
| The token table | It is the risk | Encryption, key management, deletion |
That is why contract terms and minimisation come first: they cover every byte, images included. Pseudonymisation limits what a provider, a log or a breach can expose when those are not enough. OWASP's Top 10 for LLM Applications says the same under sensitive information disclosure (LLM02:2025): "Implement tokenization to preprocess and sanitize sensitive information."
Lessons from building one
- Fail loudly without a name detector. A pipeline configured to mask people but missing its NER model or name list masks nothing and looks fine. Make that configuration an error.
- The NER model is the cost. Patterns, tokens and encryption take milliseconds per page; the model takes almost all the time. Load it once at start-up, batch the text and size the hardware for it.
- Measure leaks against an answer key. Label every mention in a sample of real documents, then count, per type, what reaches the model unmasked and how many masks hit nothing.
- Measure task quality too. Run each task in clear, in clear again to measure noise, and masked. A drop larger than the noise needs an explanation before launch.
- Check what is left. A second, more sensitive pass over the masked text before the call catches some misses. Log its findings first, then decide per use case whether to block.
- Use the names you already have. Account holders, contract parties and staff are cheap to mask exactly, and a found name should mask every later mention of it.
Sources
- GDPR Article 4(5): definition of pseudonymisation
- GDPR Recital 26: pseudonymised and anonymous data
- GDPR Article 5: principles, including data minimisation
- GDPR Article 9: special categories of personal data
- GDPR Article 25: data protection by design and by default
- GDPR Article 28: processors
- GDPR Article 35: data protection impact assessment
- GDPR Article 44: transfers to third countries
- GDPR Article 32: security of processing
- ISO/IEC 27001:2022
- ISO/IEC 27701 and its 2025 revision
- ISO/IEC 27018
- Sweeney, Simple Demographics Often Identify People Uniquely (2000)
- Staab et al., Beyond Memorization: Violating Privacy via Inference with Large Language Models
- EDPB Guidelines 01/2025 on pseudonymisation
- PCI SSC FAQ 1071: displaying the full card number
- PCI SSC FAQ 1146: masking and truncation
- PCI SSC FAQ 1137: validating card numbers with the Luhn formula
- IBAN check digits (ISO 13616)
- Presidio documentation
- GLiNER multi PII model card
- Zaratiana et al., GLiNER: Generalist Model for Named Entity Recognition
- OWASP LLM02:2025 Sensitive Information Disclosure