Sub topic 12
Tokenization, encryption, and PCI DSS scope
This chapter assumes you have read the earlier chapters on the payment actors, the idempotent API, and the payment state machine. You should also be comfortable with TLS, symmetric encryption, and short Python snippets. The goal is to decide where card numbers may exist in your system, and to keep that place as small as possible.
Why scope is the main design lever
PCI DSS (Payment Card Industry Data Security Standard) is a set of security requirements for any system that stores, processes, or transmits cardholder data. Every system component that touches that data, or sits on the same network without isolation, is "in scope". Each in-scope component must meet the standard's requirements and be assessed.
Two kinds of data matter:
- Cardholder data includes the PAN (primary account number, the long card number), the cardholder name, the expiry date, and the service code. You may store the PAN only if it is rendered unreadable.
- Sensitive authentication data includes the CVV/CVC, full magnetic-stripe data, and PINs. You must never store it after authorization, even encrypted.
Compliance cost grows with the number of in-scope systems. The cheapest control is therefore to keep PANs out of most of your system. Your API servers, databases, queues, logs, and analytics pipelines should never see one.
Tokenization
A token is a random surrogate value that stands in for a PAN. A token vault holds the mapping from token to PAN. Only the vault can reverse a token. Everything else works with tokens.
A good token has these properties:
- It is generated randomly, not derived from the PAN by encryption or hashing. Then a leaked token reveals nothing, even to an attacker with heavy compute.
- It is scoped to one merchant. A token stolen from merchant A is useless at merchant B.
- It can safely carry a few display fields, such as the last four digits and the card brand.
You will meet two kinds of token. A PSP or vault token is issued by your PSP or your own vault and works only with that provider. A network token is issued by the card network (for example Visa or Mastercard). It is usable only with a particular merchant or device and can be updated when the physical card is replaced. Network tokens can improve approval rates, but they add provisioning and lifecycle work.
Keeping the PAN off your servers
The most effective design never lets the PAN reach your backend. The browser or mobile app sends the card details directly to the PSP or a vault you operate in a separate environment. It does this with a hosted payment page, an iframe, or SDK-provided input fields. The vault returns a token, and your backend creates payments from that token.
With a fully outsourced page, a merchant can usually qualify for the shortest self-assessment questionnaire (SAQ A). If your own page hosts the card form, or your server handles the PAN even briefly, you move to a longer questionnaire such as SAQ A-EP or SAQ D. Your acquirer or a Qualified Security Assessor (QSA) decides which applies, so confirm it with them.
If you are the PSP, you operate the vault, and the vault is the most heavily scoped system you have. Keep it small, isolated on its own network segment, and reachable through a narrow internal API.
Encrypting what you must store
Inside the vault, encrypt every PAN at rest. A common design is envelope encryption:
- A data encryption key (DEK) encrypts the PAN.
- A key encryption key (KEK) held in a KMS or HSM encrypts the DEK.
- You store the encrypted DEK next to the ciphertext.
This lets you rotate the KEK without re-encrypting every record. It also keeps the master key out of application memory. Use TLS for every hop that carries a PAN, and restrict access to the decrypt operation by service identity.
The following sketch shows the vault's core behavior. It uses the cryptography package (pip install cryptography) and a single in-process key, so it is a teaching model, not a production vault.
import secrets
from cryptography.fernet import Fernet
class TokenVault:
def __init__(self, key: bytes):
self._fernet = Fernet(key)
self._store = {} # token -> encrypted PAN
def tokenize(self, pan: str) -> dict:
digits = pan.replace(" ", "")
if not digits.isdigit() or not 12 <= len(digits) <= 19:
raise ValueError("invalid card number")
token = "tok_" + secrets.token_urlsafe(16) # random, not derived from the PAN
self._store[token] = self._fernet.encrypt(digits.encode())
return {"token": token, "last4": digits[-4:]}
def detokenize(self, token: str) -> str:
# In production, only the PSP-connector service may call this.
return self._fernet.decrypt(self._store[token]).decode()
vault = TokenVault(Fernet.generate_key())
result = vault.tokenize("4242 4242 4242 4242")
print(result)
assert vault.detokenize(result["token"]) == "4242424242424242"Common errors
Most PCI problems come from accidental copies of the PAN, not from a broken vault. Check these places:
| Leak point | Why it happens | Fix |
|---|---|---|
| Application logs | Request bodies are logged for debugging | Redact fields by name and pattern, and avoid logging bodies on card endpoints |
| Error trackers and APM traces | Exceptions capture request payloads | Scrub before sending, or exclude the card endpoint |
| Idempotency store | The saved request is replayed on duplicates | Store the token, not the card fields |
| `request_hash` column | An unsalted hash of a PAN is easy to brute-force | Hash the token and amount, never the PAN |
| Support tools and exports | Screenshots, CSVs, and tickets hold card numbers | Show only the last four digits, and block free-text card entry |
| Test and staging data | Production data is copied down | Use provider test cards only |
Decision criteria
Choose the narrowest option that meets your business needs:
- Use PSP-hosted fields when you are a merchant and want the smallest scope. You give up some control over the checkout experience and tie yourself to that PSP's tokens.
- Run your own vault when you are a PSP, or when you route across several PSPs and need portable tokens. The vault can detokenize and forward the PAN to whichever PSP you choose. You accept full PCI scope for that component.
- Add network tokens when approval rates and card-update handling justify the extra integration.
Whichever you pick, keep the other chapters' guarantees intact. Payment records reference the token, the ledger records amounts only, and webhook payloads never include a PAN.
Exercise
A teammate proposes adding the full card number to each saved idempotency request body so duplicate requests can be replayed exactly. Why is this a PCI problem, and what should be stored instead?
Show answer
The idempotency store would then hold PANs, which brings that database, its backups, and everything that can read it into PCI scope. Store the token returned by the vault, along with the amount, currency, and merchant. If the hash of the request is needed, compute it over the token and those fields, not over the card number.
Exercise
Why should a token be randomly generated rather than computed as a hash or encryption of the PAN?
Show answer
A card number has a small search space, because the issuer prefix and check digit narrow the candidates. An attacker can hash every possible PAN and match a leaked token. A random token has no mathematical link to the PAN, so only the vault's mapping can reverse it.