TL;DR: Tokenization and field-level encryption (FLE) both protect sensitive fields, but they fail differently. Tokenization swaps a value for a surrogate that has no mathematical link to it, and the real value lives in one vault you can lock down and audit. FLE keeps the value in your own schema, encrypted under keys you manage, so it travels well but widens the key-management surface. Pick tokenization when many systems only need a stable reference and a few need the real value. Pick FLE when the ciphertext has to live inside the record and move with it. Under GDPR, neither makes data anonymous.

Why this decision is harder than it looks

Teams usually reach this choice after an audit finding, a customer security questionnaire, or a data-residency conversation. Someone says "we should encrypt PII," and an hour later two camps have formed. One wants a token service. The other wants column-level encryption in the application layer.

Both camps are right about something. The mistake is treating them as interchangeable. They put the trust boundary in different places, they produce different failure modes, and regulators read them differently. This article gives you a way to choose, with working code for both patterns, a trade-off table, and a checklist you can take into a design review.

It assumes you already encrypt at rest at the disk or database level. That is table stakes. It protects against stolen disks and snapshots, not against a compromised application, an over-privileged analyst, or a SQL injection that reads data through the normal path.

Definitions that hold up in a design review

Field-level encryption encrypts individual values (an email, a national ID, a card number) in the application before they reach the database. The database stores ciphertext. Whoever holds the key can decrypt; whoever does not, cannot, even with full database access.

Tokenization replaces a sensitive value with a surrogate, the token. The PCI Security Standards Council's tokenization guidelines describe it as replacing the primary account number (PAN) with a "surrogate value called a token" and note that tokens "should have no value if compromised or stolen" (PCI SSC, PCI DSS Tokenization Guidelines, v2.0, August 2011). The mapping from token to value lives in a vault.

A caveat from the same document matters for design: where a token is just a reversible encryption of the value, "the resultant token is an encrypted PAN." That is FLE with a different label, and it gets none of the scope benefits people assume tokenization brings.

Two further terms come up constantly:

  • Format-preserving encryption (FPE) encrypts a value into ciphertext with the same format, such as a 16-digit number into another 16-digit number. NIST SP 800-38G specifies the FF1 and FF3 methods.
  • Pseudonymisation is the GDPR term (Article 4(5)) for processing personal data so that it can no longer be attributed to a person without additional information kept separately. Both approaches can implement it.

How the two patterns work

mermaid
flowchart LR
  subgraph FLE["Field-level encryption"]
    A1[App] -->|encrypt with DEK| D1[(DB: ciphertext in row)]
    A1 -->|wrap/unwrap DEK| K1[KMS / HSM]
  end
  subgraph TOK["Tokenization"]
    A2[App / services] -->|tokenize| T[Token service]
    T --> V[(Vault: token -> encrypted value)]
    A2 -->|stores token only| D2[(DB: token in row)]
    T -->|keys| K2[KMS / HSM]
  end

In FLE the application does the cryptography. Typically it uses envelope encryption: a data key encrypts the field, and a wrapping key held in a KMS or HSM encrypts the data key. The AWS Encryption SDK documentation states the practice plainly: "The practice of using a wrapping key to encrypt data keys is known as envelope encryption" (AWS Encryption SDK concepts). Most cloud KMS products follow the same model.

In tokenization the application calls a token service. The service generates a token, stores the mapping in a vault, and returns the token. Downstream systems keep the token. Only callers authorised to detokenize ever see the original value.

Working code: field-level encryption with context binding

The snippet below uses AES-256-GCM from Python's cryptography package. Two details are easy to miss. First, the nonce must be unique per encryption under a given key, so it is generated randomly per call. Second, the associated data (AAD) binds each ciphertext to its table, column and row. Without that binding, an attacker with write access to the database can copy an encrypted value from one row to another and the application will decrypt it happily.

python
import hashlib, hmac, os, json, base64
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

def encrypt_field(dek: bytes, value: str, *, table: str, column: str, row_id: str) -> str:
    aad = json.dumps({"t": table, "c": column, "r": row_id}, sort_keys=True).encode()
    nonce = os.urandom(12)                      # never reuse a nonce under the same key
    ct = AESGCM(dek).encrypt(nonce, value.encode(), aad)
    return base64.b64encode(nonce + ct).decode()

def decrypt_field(dek: bytes, blob: str, *, table: str, column: str, row_id: str) -> str:
    raw = base64.b64decode(blob)
    aad = json.dumps({"t": table, "c": column, "r": row_id}, sort_keys=True).encode()
    return AESGCM(dek).decrypt(raw[:12], raw[12:], aad).decode()

def blind_index(index_key: bytes, value: str) -> str:
    norm = value.strip().lower()
    return hmac.new(index_key, norm.encode(), hashlib.sha256).hexdigest()

We ran this with the cryptography library: a round trip returns the original value, decrypting the same blob under a different row_id raises InvalidTag, and blind_index returns the same value for differently formatted inputs of the same email.

The blind_index function addresses the first thing teams hit with FLE: you can no longer query by equality. A keyed HMAC of the normalised value, stored in a separate indexed column, lets you look up a record by email without decrypting every row. Use a different key from the encryption key. Be aware of what it leaks: equal plaintexts produce equal indexes, so frequency analysis is possible on low-cardinality fields. Do not blind-index a field with a handful of possible values.

In production the dek would not be a bare byte string in your process. It would be fetched, wrapped under a KMS key, and cached for a bounded time. The pattern above is the inner layer only.

Working code: a minimal token vault

This sketch shows the core idea. The token is random, so there is nothing to reverse. The vault stores the encrypted value plus a keyed fingerprint so that the same input yields the same token (useful for joins and deduplication). If you do not need that property, drop the fingerprint and issue a fresh token every time.

python
import secrets, sqlite3

class TokenVault:
    def __init__(self, path=":memory:"):
        self.db = sqlite3.connect(path)
        self.db.execute("CREATE TABLE IF NOT EXISTS vault(token TEXT PRIMARY KEY, value_ct BLOB NOT NULL, fp TEXT UNIQUE NOT NULL)")
    def tokenize(self, value: str, encrypt, fingerprint) -> str:
        fp = fingerprint(value)                     # keyed HMAC => same input, same token
        row = self.db.execute("SELECT token FROM vault WHERE fp=?", (fp,)).fetchone()
        if row: return row[0]
        token = "tok_" + secrets.token_urlsafe(16)  # random: no mathematical link to value
        self.db.execute("INSERT INTO vault VALUES(?,?,?)", (token, encrypt(value), fp))
        self.db.commit()
        return token
    def detokenize(self, token: str, decrypt) -> str:
        row = self.db.execute("SELECT value_ct FROM vault WHERE token=?", (token,)).fetchone()
        if not row: raise KeyError("unknown token")
        return decrypt(row[0])

We tested it with a stand-in encrypt/decrypt pair: tokenizing the same value twice returns the same token, and detokenizing returns the original. It is a teaching sketch, not a service. A real one adds authentication of callers, per-caller detokenize policy, rate limiting, audit logging of every detokenize call, concurrency control around the check-then-insert, and a vault that is replicated and backed up.

Notice what the vault is: a database of every sensitive value you have, protected by whatever you build around it. The PCI guidance says as much: "the data vault often presents the most attractive target for attackers." Tokenization does not eliminate your high-value target. It concentrates it into one place that is smaller and easier to defend.

The compliance angle, read carefully

PCI DSS

Tokenization is popular in payments because it can shrink the set of systems that touch card data. The same supplement is explicit about the conditions. "All elements of the tokenization system... are considered part of the cardholder data environment (CDE) and are therefore in scope." Systems that hold only tokens can fall out of scope, but only if PAN recovery "must not be computationally feasible through knowledge of only the token" and the PAN "cannot be retrieved even if the token and the systems it resides on are compromised."

Two practical consequences:

  1. Your token service and vault stay in scope. You have moved the problem, not removed it.
  2. A reversible-encryption "token" does not meet the out-of-scope test above, because anyone who obtains the key can recover the PAN.

The supplement dates from 2011 and states that it does not replace the PCI DSS requirements. We did not check whether a newer PCI SSC tokenization publication supersedes it, so confirm the current guidance, and the version of PCI DSS you are assessed against, with your QSA before relying on a scope reduction.

GDPR and UK GDPR

On 16 January 2025 the European Data Protection Board adopted Guidelines 01/2025 on Pseudonymisation for public consultation (consultation ran 17 January to 14 March 2025; we found only the consultation version) (EDPB). The guidance states that pseudonymised data "is to be considered information on an identifiable natural person, and is therefore personal," and becomes anonymous only if the conditions for anonymity are met.

For engineers in Germany, the UK and the wider EU this means a token for a customer's national ID is still personal data while anyone can link it back, including the party running the vault. Tokenization and FLE are good safeguards under Article 32 and good ways to limit who can see data. They do not take a dataset out of GDPR. Treat claims otherwise, from vendors or colleagues, with suspicion.

Both approaches also interact with erasure. With a vault, deleting the mapping can make downstream token references meaningless, which is a clean erasure story if no other copy of the value exists. With FLE, "crypto-shredding" (destroying a per-subject key) achieves a similar result but requires you to have designed per-subject or per-tenant keys up front. Confirm with your legal advisers that either meets your obligations; neither guarantees it.

US considerations

In the US, requirements are sector- and state-specific (HIPAA, GLBA, state privacy laws, PCI DSS for card data). Treatment of encryption and tokenization differs by statute, so check with counsel for your sector rather than assuming either pattern satisfies a given law.

Format-preserving encryption: a third option with sharp edges

FPE appeals when a legacy system expects a 16-digit field and cannot be changed. NIST SP 800-38G defines FF1 and FF3. The 2019 initial public draft of Revision 1 (comment period closed, and we did not find a final version on the page) updates FF1 and FF3-1 "in order to address potential vulnerabilities when the domain size is too small." It reduces the tweak to 56 bits for FF3, renamed FF3-1, and raises the minimum domain size to one million, where the original had required at least one hundred and recommended one million (NIST CSRC).

The lesson for design: FPE over a small domain (a 4-digit PIN, a 2-letter state code, a short numeric ID) is weak by construction. If you choose FPE, check the domain size against the current NIST text for the revision you are following, and use a vetted library rather than your own implementation of these modes.

Trade-off table

DimensionTokenization (random tokens + vault)Field-level encryption
Where the real value livesOne vaultEvery row, as ciphertext
Downstream systemsHold tokens onlyHold ciphertext; need key access to use it
Main target for attackersVault and token serviceKey hierarchy (KMS/HSM) and application servers
Query supportEquality via token; no range queries on the valueNeeds blind indexes; ranges generally need extra schemes
LatencyNetwork call per tokenize/detokenizeLocal crypto plus key fetch (cacheable)
Availability riskToken service outage blocks detokenizeKMS outage blocks decrypt of uncached keys
Data portabilityTokens are meaningless outside your vaultCiphertext moves with the record (exports, replicas, backups)
ErasureDelete mappingDelete key (needs per-subject key design)
AnalyticsJoin on stable tokens without seeing valuesJoins need deterministic encryption or blind indexes
Compliance framingCan reduce PCI scope if designed to the criteriaDoes not by itself reduce PCI scope
Operational burdenRun a high-availability, audited serviceRun key rotation, versioning and re-encryption

Decision framework

Walk these questions in order.

  1. Do most systems only need a stable reference to the value? If your CRM, data warehouse and support tools just need to identify a customer or match a record, tokens fit well. If most systems must read the real value, tokenization turns into a detokenize call on every request and you have built a bottleneck.
  2. Must the sensitive value travel with the record? Multi-region replicas, offline exports, partner files and mobile clients favour FLE, because a token is meaningless without a call back to your vault.
  3. Are you trying to reduce compliance scope? If it is PCI scope, tokenization is the more natural route, subject to the criteria above. If it is general breach exposure, either helps; the deciding factor is who holds the keys.
  4. Do you need to search or sort on the value? FLE needs blind indexes and accepts limits. Tokenization gives you equality matching on tokens only if you use deterministic issuance.
  5. Can you run a tier-0 service? A token vault must be as available and as well-guarded as your primary database. If your team cannot staff that, a managed token service or FLE with a cloud KMS may be the more honest choice.
  6. Do you need erasure on request? Decide up front how deletion will work: vault entry removal or per-subject key destruction.

Many mature systems use both: FLE for the data inside the vault, and tokens everywhere else. That is not redundancy. The vault's own contents still need protection, and the PCI supplement's point that the vault is the attractive target is the reason to encrypt them under keys held outside it.

Common mistakes

  • Calling reversible encryption "tokenization." If the token can be computed back to the value with a key, it is encryption, with encryption's compliance profile.
  • Using ECB or a fixed nonce. Identical plaintexts then produce identical ciphertext, or worse, nonce reuse under AES-GCM breaks confidentiality and authenticity. Generate nonces correctly or use a library that does.
  • Skipping associated data. Without binding ciphertext to its row and column, ciphertext can be swapped between records undetected.
  • Using one key for everything. Separate keys for encryption, blind indexes and different data classes limit blast radius.
  • Logging the plaintext. Tokenizing the database while the request logs still contain the raw value undoes the work. Check logs, traces, error reports and analytics events.
  • Forgetting backups and replicas. Old ciphertext under retired keys must still be decryptable, or deliberately destroyed. Plan key versioning before the first rotation.
  • Blind-indexing low-cardinality fields. Equal values yield equal indexes, so a handful of categories is trivially inferred.
  • Assuming either approach means "anonymous." See the EDPB statement above.
  • No audit trail on detokenize or decrypt. The question after an incident is who read what and when. Build that answer in from the start.
  • Rolling your own FPE or crypto. Use maintained libraries and check them against the standard you cite.

Implementation checklist

  • [ ] Classify fields: which values are sensitive, who needs the real value, and which systems only need a reference.
  • [ ] Choose the pattern per data class, not once for the whole company.
  • [ ] Keep keys in a KMS or HSM; never in code, config repositories or container images.
  • [ ] Use envelope encryption with versioned keys and a tested rotation procedure.
  • [ ] Bind ciphertext to context (table, column, row or tenant) through authenticated associated data.
  • [ ] Use separate keys for encryption and for blind indexes.
  • [ ] If tokenizing, issue random tokens, authenticate every caller, and enforce per-caller detokenize permissions.
  • [ ] Log every detokenize and decrypt event to an append-only store, with alerting on unusual volume.
  • [ ] Scrub plaintext from logs, traces, error payloads and analytics pipelines.
  • [ ] Decide and document the erasure mechanism (mapping deletion or key destruction).
  • [ ] Load-test the vault or KMS path, and define behaviour when it is unavailable.
  • [ ] Confirm the scope and anonymity assumptions in writing with your QSA, DPO or counsel.
  • [ ] Rehearse a key-compromise runbook: who rotates what, and in what order.

Where Syslabs fits

We build and review systems where this decision shows up: payment flows, customer and patient records, and integration layers that move sensitive fields between systems. In practice the useful work is rarely choosing an algorithm. It is mapping where each sensitive value is read, deciding who actually needs it, and designing the key hierarchy and audit trail so the choice survives contact with real traffic. If you are weighing these options for a specific platform, our security and identity engineering, cloud infrastructure and API integration teams can review your data flows with you.

Book a conversation

If you want a second pair of eyes on a tokenization or field-level encryption design, book a meeting with the Syslabs team.

References

  • PCI Security Standards Council. PCI DSS Tokenization Guidelines, Information Supplement v2.0 (August 2011). https://listings.pcisecuritystandards.org/documents/TokenizationGuidelinesInfo_Supplement.pdf
  • European Data Protection Board. Guidelines 01/2025 on Pseudonymisation (adopted 16 January 2025, consultation version). https://www.edpb.europa.eu/our-work-tools/documents/public-consultations/2025/guidelines-012025-pseudonymisation_en
  • NIST. SP 800-38G Rev. 1 (Initial Public Draft), February 2019. https://csrc.nist.gov/pubs/sp/800/38/g/r1/ipd
  • AWS. Concepts in the AWS Encryption SDK. https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html