← All posts

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:

Five stages of an LLM call with the rules that apply to each: data minimisation and DPIA before the call, pseudonymisation and data masking while detecting, separate encrypted and deleted token tables, processor terms and transfers at the provider, and display masking and logging for the answer Before the call Collect only what the task needs GDPR Art. 5(1)(c) GDPR Art. 35, DPIA ISO 27001 A.5.12 Detect and mask Find and replace personal data GDPR Art. 25, 32 ISO 27001 A.8.11 ISO 27001 A.8.12 Token table Kept separately, encrypted, deleted GDPR Art. 4(5) ISO 27001 A.8.24 ISO 27001 A.8.10 LLM provider Processor terms, region, retention GDPR Art. 28 GDPR Art. 44 ISO/IEC 27018 Answer and logs Restore, display, log without values PCI DSS 3.4.1 ISO 27001 A.8.15 OWASP LLM02
Figure 1. Where the GDPR, ISO/IEC 27001 Annex A and the PCI DSS touch one LLM call.
SourceWhat it saysWhat 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. 25Data 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. 28Use "only processors providing sufficient guarantees"The LLM provider is a processor: a data processing agreement, retention terms and security commitments.
GDPR Art. 44Transfers outside the EU only under the conditions of Chapter VKnow where the provider processes the prompt.
GDPR Art. 35An 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 A8.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 PIIThe controls an auditor will ask about for this pipeline.
ISO/IEC 27701 and 27018A privacy information management system (a stand-alone standard since its 2025 revision); a code of practice for PII in public clouds acting as processorsThe privacy management layer above the controls, and a yardstick for cloud providers.
PCI DSS 3.4.1A 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.

A line from identified to anonymous: raw text, pseudonymised text, text with quasi-identifiers left, aggregated data; the GDPR applies to the first three identified anonymous Raw text Maria Keller, card 4539… Pseudonymised [PERSON_1], [CARD_1] Quasi-identifiers left job, town, dates, events Aggregated counts, no individuals personal data: the GDPR applies, whoever holds the key may be anonymous
Figure 2. Pseudonymisation moves data along the line but not out of the GDPR. Only data that no longer relates to an identifiable person is anonymous.

Choosing a technique

TechniqueThe model seesReversibleGood for
Redaction[REDACTED]NoLogs and exports nobody reads back
Masking**** 6467NoShowing a card or account to a person
Typed tokens[PERSON_1], [CARD_1]Yes, with the token tableLLM calls whose answer must name real values
Fake values"Anna Smith"FragileTraining and test data
Keyed hashing3f9a…NoJoining records without exposing values
EncryptionCiphertextYes, with the keyStorage 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

Pipeline: text is cleaned, three detectors (patterns, known names, NER) find values, which are merged, tokenised and sealed; the LLM sees only tokens; the answer is restored and anomalies reported Text as received Clean odd characters Patterns regex + checksum Known names exact lists NER model people, companies Merge, tokenise, seal [PERSON_1], AES-GCM table LLM call sees only tokens Restore and report exact, bent, unknown tokens Answer real values
Figure 3. A pseudonymisation layer around one LLM call. Only the LLM call leaves the application, and it carries tokens, not values.

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:

Grouped bars of mentions masked on messy invented messages: regexes alone versus regexes plus GLiNER, for cards, emails, IBANs, phones, companies and people Share of planted mentions masked, messy invented messages (%) Regexes with checksums Regexes + GLiNER PII 0 25 50 75 100 52 100 Cards n = 63 48 100 Emails n = 60 22 100 IBANs n = 40 0 100 Phones n = 37 0 96 Companies n = 132 0 87 People n = 229
Figure 4. Share of planted mentions masked on 200 messy invented messages. Regexes alone mask no names; GLiNER closes most gaps and misses mainly first names written alone.
Messy setRegexes with checksumsRegexes + GLiNER PII
Mentions masked71 of 561 (13 per cent)526 of 561 (94 per cent)
Masks that hit nothing0 of 7132 of 560
MissedEvery name; split cards, obfuscated emails, lower-case IBANs, national phonesMostly first names written alone
Over-maskedNothingProduct 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:

Two line charts against the GLiNER threshold from 0.1 to 0.9: mentions masked falls from 97 to 79 per cent, names masked from 96 to 78 per cent; false hits fall from 9.1 to 2.5 per cent of masks Mentions masked (%) 70 80 90 100 0.1 0.3 0.5 0.7 0.9 detection threshold False hits, share of masks (%) 0 2 4 6 8 10 0.1 0.3 0.5 0.7 0.9 detection threshold all types names only
Figure 5. GLiNER threshold against coverage and false hits on the messy invented set, with regexes always on.

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:

Median time per message: regexes about 0.01 ms, regexes plus GLiNER about 55 ms Median time per message on a laptop CPU (ms, log scale) 0.01 0.1 1 10 100 1000 Regexes with checksums 0.01 ms Regexes + GLiNER PII 54.65 ms
Figure 6. Median detection time per message on the clean invented set, laptop CPU, model loaded and warm. Log scale.

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:

InputResult
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 comMasked, but as a person and a company, not as an email
card 4539 1488 0343, then 6467 on a new lineThe 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

ExposureDoes text masking help?Main control
Prompt text sent to the providerYes, for what it detectsProcessor terms, zero retention, region
Page images and scansNo; masking the text but not the image also confuses the modelImage redaction, or not sending images
Embeddings and vector databasesOnly if chunks pass through the masking layerMask before embedding; access control
Application logs and tracesOnly if masking happens before loggingLog tokens, never values (A.8.15)
Inference from contextLittleData minimisation; send less text
The token tableIt is the riskEncryption, 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