Handling PII and Card Data
Last Updated: 2026-12-01 Status: Complete
Handling PII and card data well means deciding, per data element, whether you need it at all, where it may live, how it is protected and when it goes away. This page turns that into an architecture: a classification table, a scope-reduction design in which the PAN never reaches your servers, field-level encryption, masking, safe logging, KYC document storage and a retention schedule that reconciles deletion requests with financial-record duties. PCI basics are taught in PCI DSS; here we focus on what you build.
Scope and retention decisions are not engineering choices alone. Confirm cardholder-data scope with your QSA, retention and deletion obligations with legal counsel, and the overall design with your security leadership. This page is educational and is not legal or compliance advice.
Values below follow PCI DSS v4.0.1 — all future-dated requirements mandatory since 31 March 2025 and are tracked on Key Numbers. Re-check them before relying on them.
Quick Reference
| Rule | Detail |
|---|---|
| SAD after authorization | Never stored, even encrypted (Req 3.3.1) |
| PAN display | Show at most the BIN and last four digits, except to people with a documented business need to see more |
| PAN truncation | 16-digit PANs: at most the first eight and any other four digits; 15-digit American Express: first six and last four |
| PAN in transit | Strong cryptography over open, public networks (Req 4.2.1); use TLS 1.2 or higher |
| Lookup and dedupe | Keyed hash or blind index, never an unkeyed hash (Req 3.5.1.1) |
| Logs | Allowlist fields; never PAN, SAD, SSN or bank numbers |
| Best scope strategy | Do not receive the PAN at all |
How Should You Classify Data?
| Class | Examples | May be stored? | Where it may live |
|---|---|---|---|
| CHD | PAN, cardholder name, expiry date, service code | Only with a business need. PAN rendered unreadable wherever stored (Req 3.5.1); other CHD elements stored with the PAN are protected under your data-security policy and your QSA's guidance | Token vault or processor vault in the segmented CDE; prefer not at all |
| SAD | Full track data, card verification code, PIN or PIN block | Never after authorization (Req 3.3.1); issuers have a separate allowance (3.3.3) | Memory during authorization only, never logs or databases |
| PII | SSN or TIN, date of birth, government ID images, bank account and routing numbers, contact details | Yes, when needed for KYC, payouts or law | Encrypted at field or object level, access-controlled, audited |
| Business-confidential | Pricing, reserve terms, risk scores, underwriting notes | Yes | Normal production stores with RBAC and audit |
| Public or low risk | Merchant display name, statement descriptor | Yes | Anywhere appropriate |
Bank account numbers are not CHD, but they are PII and payout-critical. Treat them with the same rigor: encrypted, masked on display, never logged.
How Do You Reduce Scope So the PAN Never Reaches You?
The cheapest PAN to protect is the one you never see. Tokenize at the edge: the browser or mobile app sends card data directly to a processor-hosted field, iframe or SDK, which returns a token. Your servers handle only the token.
Where Does the Token Live? Four Options
| Option | How it works | Trade-off |
|---|---|---|
| Processor tokens | The processor stores the PAN and gives you a token usable only with that processor | Least scope, but lock-in: moving processors means migrating cards |
| Third-party vault | An independent vault provider holds the PAN and forwards it to processors | Portability across processors; one more vendor and contract |
| Your own vault | You run the token vault in a segmented CDE | Full control and portability, full PCI burden (vault and every component that can detokenize are in scope) |
| Network tokens | Scheme-issued tokens with cryptograms, domain-restricted | Better approval outcomes and lifecycle updates; see Network Tokens |
These are not mutually exclusive. A mature platform often stores a processor or vault token plus a network token and a minimal masked display record. Background on tokenization and what stays in scope: Tokenization and Scope Management.
Per PCI SSC tokenization guidance, components that can access the vault or retrieve the PAN are in scope; systems holding only tokens and unable to retrieve the PAN may be out of scope. The QSA decides, so design a narrow detokenization service with its own network segment, its own identity, an allowlist of callers and an audit event for every call.
If you do run your own vault, put the detokenization service behind network segmentation, require MFA for administrative access (MFA for all non-console access into the cardholder data environment by any user, not only administrators (Req. 8.4.1 covers administrative access), mandatory since 31 March 2025), and see Access Control for Payment APIs.
How Should You Encrypt Sensitive Fields?
Database-level disk encryption protects stolen disks, not a SQL injection or an over-privileged analyst. For high-risk fields (bank numbers, SSN or TIN, and any vaulted PAN) add field-level encryption using envelope encryption.
- A master key lives in a KMS or HSM and never leaves it.
- For each record (or tenant) the service obtains a data encryption key (DEK), encrypted under the master key.
- The service encrypts the field with the DEK, then stores the ciphertext and the wrapped DEK together.
- To read, the service asks the KMS to unwrap the DEK, decrypts the field, and discards the DEK.
AWS and Google Cloud both document this pattern (see References). Key points:
- Rotation. Rotate the master key on schedule; the wrapped DEKs are re-wrapped without re-encrypting every field. Rotate DEKs by re-encrypting on write or in a background job. PCI DSS 3.6 and 3.7 cover key management.
- Per-tenant keys are an option: they limit blast radius, enable tenant-level deletion by destroying the key, and cost more in key management and KMS calls. Decide per risk tier.
- Bind ciphertext to context. Use authenticated encryption (AES-GCM) with the tenant and field name as associated data so ciphertext cannot be moved between rows.
- Transit. Require TLS 1.2 or higher for every hop; Requirement 4.2.1 requires strong cryptography for PAN over open, public networks, and internal TLS is good practice for everything else.
@Injectable()
export class FieldCipher {
constructor(@Inject(KMS_CLIENT) private readonly kms: KmsClient) {}
async encrypt(plaintext: string, tenantId: string, field: string): Promise<EncryptedField> {
const { plaintextKey, wrappedKey, keyId } = await this.kms.generateDataKey(tenantId);
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', plaintextKey, iv);
cipher.setAAD(Buffer.from(`${tenantId}:${field}`));
const ct = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
plaintextKey.fill(0); // best effort: do not keep the DEK in memory
return { ct, iv, tag: cipher.getAuthTag(), wrappedKey, keyId };
}
// decrypt(): kms.unwrap(wrappedKey) -> createDecipheriv -> setAAD -> setAuthTag -> final()
}
The FieldCipher class takes only values the caller already must handle. It does not log inputs, and it is the single place cryptography lives, so audits and rotation touch one component.
How Do You Mask, Truncate and Look Up Sensitive Values?
Masking and Truncation
- Display: Show at most the BIN and last four digits, except to people with a documented business need to see more. For a customer-facing UI, last four and brand are usually enough. A masked display value looks like
411111******1111and is not a usable card. - Storage by truncation: 16-digit PANs: at most the first eight and any other four digits; 15-digit American Express: first six and last four.
- Never store several truncation formats of one PAN. A first-six-last-four value plus a first-eight value for the same card can be combined to reconstruct more digits.
- Do not combine a keyed hash and a truncated or masked form of the same PAN without a plan. Requirement 3.5.1 expects controls that prevent the two from being correlated to recover the PAN. Raise any such design with your QSA before building it.
- Mask bank accounts to the last four digits in UIs, emails and exports.
Lookup and Deduplication Without Storing the Raw Value
You often need "have we seen this bank account before?" (fraud, duplicate sub-merchant detection) or "is this the same card?" without decrypting everything. Use a keyed hash, also called a blind index.
function blindIndex(normalizedValue: string, indexKey: Buffer): string {
return createHmac('sha256', indexKey).update(normalizedValue).digest('hex');
}
// normalize first: strip spaces and dashes; for bank accounts hash routing + account together.
// indexKey: a dedicated secret in the KMS, not the encryption key. Rotate by re-indexing.
Requirement 3.5.1.1 requires hashes used to render PAN unreadable to be keyed cryptographic hashes. A plain SHA-256 of a PAN or a bank account is trivially brute-forced because the input space is small. Store the index in a separate column, restrict who can query it, and remember an equality index reveals which records share a value. If a keyed hash of a PAN would sit alongside a truncated or masked copy of that PAN, Requirement 3.5.1 expects controls preventing correlation, so confirm the combination with your QSA first.
How Do You Keep Sensitive Data Out of Logs?
Logs are the most common accidental store of PAN and PII. Rules:
- Never log PAN, SAD, SSNs or bank account numbers, at any level, in any environment that touches real data.
- Structured logging with an allowlist. Log named fields you have approved, not whole request objects. A denylist of "bad" field names always misses one.
- Redact at the serialization boundary (logger transport, HTTP client wrappers, ORM query logging), so a developer cannot accidentally pass a full object.
- ISO 8583: DE 2, 14, 35, 45 and 52 carry cardholder data or SAD and must never be logged. See ISO 8583 for the full rule and the field allowlist.
- Scrub third parties. Configure error trackers, APM, product analytics and session-replay tools to drop request bodies and form fields, and test it with synthetic data.
- Free-text fields (support notes, descriptions) can contain a customer-typed card number. Scan and block them on input.
const ALLOWED_LOG_FIELDS = new Set(['paymentId', 'tenantId', 'amount', 'currency', 'status', 'responseCode', 'traceId']);
export function toLogSafe(obj: Record<string, unknown>): Record<string, unknown> {
return Object.fromEntries(Object.entries(obj).filter(([k]) => ALLOWED_LOG_FIELDS.has(k)));
}
For the audit side of this, see Audit Trails: audit events use reference ids and masked diffs for the same reason.
How Should You Store KYC and KYB Documents?
Government ID images, proof of address and business registration documents are the most sensitive PII you hold at rest. See KYC and KYB for what you collect and why.
| Concern | Design |
|---|---|
| Storage | Encrypted object storage; per-tenant or per-document keys via envelope encryption; private buckets with no public access |
| Versioning | Keep versions; a re-uploaded document is a new object linked to the same requirement, never an overwrite |
| Malware | Scan on upload and quarantine until clean; restrict file types and sizes |
| Access | Short-lived presigned URLs issued by your API after an authorization check; no permanent links; no direct bucket access for staff |
| Audit | One audit event per view or download (see Audit Trails) |
| Verification providers | Prefer storing the provider's reference id, the verification result, the timestamp and the checks performed, rather than your own copy of the raw document, when your obligations allow |
| Retention | By document type and legal basis (see schedule below), with a retention date set on upload |
Metadata (document type, status, reference to the object, verification result, expires_at) lives in your database. The image lives in object storage. Neither contains the other's secrets.
Deletion vs Retention: What Can You Delete?
Privacy law and financial regulation pull in opposite directions. Under GDPR (Regulation (EU) 2016/679), data minimization (Art. 5(1)(c)) and storage limitation (Art. 5(1)(e)) mean you should not collect or keep more than you need. The right to erasure (Art. 17) is not absolute: Art. 17(3)(b) excludes processing necessary to comply with a legal obligation under Union or Member State law (whether a duty you inherit by contract from a U.S. sponsor bank qualifies is a question for counsel), and Art. 17(3)(e) excludes processing needed for the establishment, exercise or defense of legal claims. US state privacy laws vary; ask counsel which apply.
Pseudonymization (Art. 4(5)) reduces risk, but Recital 26 says pseudonymized data is still personal data. Replacing a name with an id is not deletion.
Retention Schedule Template
| Record | Retention basis |
|---|---|
| Records subject to the Bank Secrecy Act: general records run from creation; bank CIP identifying information runs from account closure | Five years (31 CFR 1010.430(d)); bank CIP identifying information five years after the account is closed (31 CFR 1020.220(a)(3)(ii)) |
| ACH authorization records | Two years from the termination or revocation of the authorization |
| Audit logs on CDE systems | At least 12 months of audit log history, with the most recent three months immediately available for analysis |
| Transaction records, sub-merchant agreements, dispute evidence | Per sponsor bank agreement and network rules; confirm with legal |
| Support tickets and marketing contact data | Your privacy policy; typically short |
| SAD | Not retained after authorization |
The BSA applies to banks and other covered financial institutions. A PayFac that is not a bank usually inherits equivalent duties through its sponsor bank agreement, so check that agreement. Implement the schedule as data (a table of record type, trigger event, duration, legal basis, owner) that a retention job reads, not as scattered constants.
Crypto-Shredding
When data is encrypted with a per-subject or per-tenant key, destroying the key makes the ciphertext unrecoverable everywhere it was copied, including replicas and backups. It is a useful deletion technique when you cannot reliably find every copy. Limits: it only works if the key was truly isolated to the data being deleted; you must destroy the key and every wrapped copy; and it does not erase unencrypted copies in logs, exports or analytics. Use it only for data you are permitted to delete.
Walkthrough: A Sub-Merchant Asks to Be Deleted
- Verify the requester is authorized to speak for the sub-merchant, and log the request.
- Check holds. Open disputes, reserves, negative balance, a legal hold or an investigation block deletion of the related records.
- Classify each record against the schedule: regulated identification records and payment records stay until their retention period ends; marketing data, unused documents and optional profile data can go now.
- Restrict processing. For retained data, flag the account as closed-retained, remove it from marketing and analytics, and limit access to compliance and finance roles.
- Delete or shred what is eligible: remove rows, delete document objects and their versions, destroy per-tenant keys where the tenant's data is fully eligible.
- Keep the ledger and audit references intact. They hold ids and amounts, not personal values.
- Schedule the rest. Set a deletion date on retained records so the retention job removes them when the period expires.
- Respond to the requester explaining what was deleted and what was kept and why. Have legal approve the wording.
Who Should See Production Data?
Developers and support staff should not browse production PII by default. Use masked views, synthetic data in lower environments, just-in-time approved access with expiry and session logging for incidents, and audit every sensitive read. The mechanics are in Access Control for Payment APIs.
Common Mistakes
- Receiving the PAN on your servers "just to forward it" and discovering you are in full scope
- Hashing PANs or bank accounts with unkeyed SHA-256 for dedupe
- Keeping two truncated forms of the same PAN
- Logging whole request bodies in an exception handler
- Copying production data to staging for testing
- Treating pseudonymized data as anonymous
- Storing KYC images in a bucket with long-lived public URLs
- Writing a deletion job without a retention schedule or legal-hold check
Related Topics
- Audit Trails: references and masked diffs for sensitive events
- Access Control for Payment APIs: who may call the detokenization service and view documents
- Entity Model: where bank accounts, principals and users live in the data model
- Tokenization and Scope Management: PCI foundations
- Network Tokens: scheme tokens and lifecycle
- Check your understanding: Security Quiz
References
- PCI DSS v4.0.1 and supporting documents: PCI Security Standards Council (Requirements 3, 4, 7, 8)
- Information Supplement: PCI DSS Tokenization Guidelines: PCI SSC, August 2011
- Tokenization Product Security Guidelines: Irreversible and Reversible Tokens: PCI SSC, April 2015
- PCI SSC FAQ 1091: acceptable formats for truncation of primary account numbers: PCI SSC
- Regulation (EU) 2016/679 (GDPR): European Union, 2016
- eCFR: 31 CFR 1010.430: U.S. Government
- AWS KMS cryptography essentials: Amazon Web Services documentation (vendor)
- Envelope encryption: Google Cloud documentation (vendor)