PCI DSS PAN Masking: Protecting Cardholder Data in Databases
A technical guide to PCI DSS Requirement 3 — how to mask, truncate, and tokenize Primary Account Numbers (PAN) to protect cardholder data and avoid costly non-compliance penalties.
Related Tool
Use the Enterprise Database Dump Anonymizer to apply what you learn in this guide.
On this page
- What Is a PAN and Why Does It Need Protection?
- PCI DSS Requirement 3 — Protect Stored Account Data
- Requirement 3.4.1 — Rendering PAN Unreadable
- Method 1 — Truncation
- Method 2 — Strong One-Way Hashing
- Method 3 — Index Tokens
- Method 4 — Strong Cryptography
- Choosing Between Truncation and Tokenization
- PAN in Unexpected Places
- Application Logs
- Database Audit Tables
- Backup Files and Exports
- Development and Test Databases
- Scanning Databases for Unprotected PANs
- PCI DSS v4.0 Changes (Effective March 2025)
- Frequently Asked Questions
- Find and Mask PANs in Your Databases — Free
What Is a PAN and Why Does It Need Protection?
A Primary Account Number (PAN) is the 13–19 digit number embossed on a payment card — the number your systems process when a customer makes a purchase. Under PCI DSS (Payment Card Industry Data Security Standard), the PAN is the most sensitive piece of cardholder data and is the primary focus of Requirement 3.
The consequences of exposing unmasked PANs in databases are severe:
- Fines of $5,000–$100,000 per month from card brands until compliance is achieved
- Forced termination of card processing privileges
- Liability for fraudulent transactions from exposed cards
- Mandatory forensic investigation and audits after any breach
In 2023, the average cost of a data breach involving payment card data was $5.17 million (Ponemon Institute). Most of this cost is attributable to regulatory penalties and card brand fines, not incident response.
PCI DSS Requirement 3 — Protect Stored Account Data
PCI DSS v4.0 Requirement 3 covers the protection of stored account data. The key sub-requirements related to PANs are:
| Requirement | Rule |
|---|---|
| 3.3.1 | SAD (Sensitive Authentication Data) must not be stored after authorisation |
| 3.4.1 | PAN must be rendered unreadable anywhere it is stored |
| 3.5.1 | PAN must be protected with strong cryptography (key management required) |
Sensitive Authentication Data (SAD) — which must never be stored post-authorisation — includes:
- Full magnetic stripe data
- CVV/CVC/CAV (3–4 digit security code)
- PIN blocks
These are distinct from the PAN itself, which may be stored but must be protected.
Requirement 3.4.1 — Rendering PAN Unreadable
The standard provides four acceptable methods for rendering stored PANs unreadable:
Method 1 — Truncation
Remove portions of the PAN so that only part of it is stored. PCI DSS allows display of:
- Maximum first 6 digits (BIN — Bank Identification Number)
- Maximum last 4 digits
- Together: no more than the first 6 and last 4 digits may be visible
Full PAN: 4532 1234 5678 9012
Truncated (PCI): 4532 12** **** 9012 ← BIN (6) + last 4 digits
Truncated PANs are permanently irreversible — the original cannot be recovered. This is appropriate for:
- Customer-facing UIs (showing the card on file)
- Receipts and order confirmations
- Database storage where the full PAN is never needed after authorisation
-- Store only the truncated version
UPDATE payment_methods SET
pan_display = LEFT(pan_full, 6) || '******' || RIGHT(pan_full, 4),
pan_full = NULL; -- Delete the full PAN from the database
Method 2 — Strong One-Way Hashing
Hash the entire PAN using a strong cryptographic hash function with a salt. This is irreversible.
-- Hash the PAN with a secret salt (store salt in key management system)
UPDATE payments SET
pan_hash = encode(sha256(('your-secret-salt-' || pan_full)::bytea), 'hex'),
pan_full = NULL;
Important: PCI DSS requires hashing of the full PAN, not a truncated version. Hashing of truncated PANs is not compliant because the search space of missing digits is small enough for brute-force attacks.
The hash is useful for:
- Detecting duplicate card usage across transactions
- Fraud detection (matching a hash across systems without storing the PAN)
Method 3 — Index Tokens
Replace the PAN with a token generated by a tokenisation system. The token has no mathematical relationship to the PAN.
Full PAN: 4532 1234 5678 9012
Token: 7829 4051 2938 0174 ← random, stored in token vault
The token vault maps each token to its PAN. It must be:
- Stored in a separate, highly secured environment
- Protected by strong access controls (separate credentials from application)
- Encrypted at rest
- Subject to its own PCI DSS compliance scope
Compliance descoping benefit: Systems that only ever see tokens — never actual PANs — may be descoped from PCI DSS compliance for those components. This dramatically reduces the scope and cost of annual PCI assessments.
Method 4 — Strong Cryptography
Encrypt the PAN using a strong cipher with proper key management. PCI DSS requires:
- AES-256 (preferred) or 3DES (legacy acceptable)
- Separate key storage from encrypted data
- Key rotation procedures
- Dual control for key management (no single person should have access to both the key and the data)
-- Example: column-level encryption using pgcrypto (PostgreSQL)
-- The encryption key MUST be stored outside the database
-- Store encrypted PAN
UPDATE payments SET
pan_encrypted = pgp_sym_encrypt(pan_full, current_setting('app.pan_encryption_key')),
pan_full = NULL;
-- Retrieve for authorised processing
SELECT pgp_sym_decrypt(pan_encrypted, current_setting('app.pan_encryption_key')) AS pan
FROM payments
WHERE id = $1;
Choosing Between Truncation and Tokenization
| Factor | Truncation | Tokenization |
|---|---|---|
| Reversibility | Irreversible | Reversible (with vault) |
| Original PAN needed? | Never recovered | Can be recovered |
| PCI scope reduction | Partial | Full descoping possible |
| Infrastructure required | None | Token vault required |
| Best for | Display, receipts, storage | Full payment processing flows |
Rule of thumb:
- If you never need the full PAN after the initial authorisation → use truncation
- If your downstream systems (refunds, recurring billing) need the full PAN → use tokenization and ensure only the payment processor holds the token vault
PAN in Unexpected Places
One of the most common PCI DSS findings is PAN appearing in locations beyond the primary payment tables:
Application Logs
Payment processing errors often log request parameters — including PAN. Ensure your logging framework masks or excludes PAN fields:
// Example: mask PAN in logs before writing
function maskPAN(pan) {
return pan.slice(0, 6) + '*'.repeat(pan.length - 10) + pan.slice(-4);
}
logger.error('Payment failed', {
pan: maskPAN(request.pan), // Never log raw PAN
amount: request.amount
});
Database Audit Tables
Audit triggers that log row_to_json(NEW) will capture PAN values in the audit table. Use column-level exclusion:
-- Audit trigger that excludes sensitive columns
CREATE OR REPLACE FUNCTION audit_payment_changes()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO audit_logs (table_name, operation, record_id, changed_at)
VALUES (TG_TABLE_NAME, TG_OP, NEW.id, NOW());
-- Do NOT log full row JSON for payment tables
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
Backup Files and Exports
Unencrypted database backups containing PANs are in scope for PCI DSS. All backup media must be encrypted and stored securely. Regular exports (CSV, JSON) for analytics must be masked or tokenized before leaving the production environment.
Development and Test Databases
Developers frequently copy production databases to development environments. Any development or test database containing real PANs is in scope for PCI DSS. This dramatically increases your compliance burden.
Solution: Run a PII/PAN scanner against all non-production databases and mask all discovered PANs. This removes them from compliance scope entirely.
Scanning Databases for Unprotected PANs
Before you can protect PANs, you need to find them. The Luhn algorithm check is the gold standard for identifying card numbers in a database:
// Luhn algorithm — validates a potential PAN
function luhn(cardNumber) {
const digits = cardNumber.replace(/\D/g, '');
let sum = 0;
let isEven = false;
for (let i = digits.length - 1; i >= 0; i--) {
let digit = parseInt(digits[i]);
if (isEven) {
digit *= 2;
if (digit > 9) digit -= 9;
}
sum += digit;
isEven = !isEven;
}
return sum % 10 === 0;
}
A PAN scanner examines database columns, samples values, applies Luhn validation, and flags any columns containing valid card numbers — even those stored in text or notes fields.
PCI DSS v4.0 Changes (Effective March 2025)
PCI DSS v4.0, which became the only active standard in March 2025, introduced changes relevant to PAN storage:
- Requirement 3.3.1 now explicitly prohibits storage of full SAD by all entities, not just issuers (closing a previous exemption gap)
- Requirement 12.3.2 introduced a new Targeted Risk Analysis (TRA) approach — organisations can justify some controls based on documented risk assessment rather than prescriptive implementation
- Requirement 6.4.1 — all public-facing web applications must be protected by a WAF or automated technical solution (relevant for payment forms)
Frequently Asked Questions
Q: Can we store the CVV/CVC for recurring billing? A: No. Under PCI DSS Requirement 3.3.1, CVV/CVC (SAD) must never be stored after authorisation, even for recurring billing. Recurring billing must use tokens from a compliant payment processor, not stored card security codes.
Q: Does tokenization remove us from PCI DSS scope entirely? A: Tokenization can significantly reduce scope but typically does not eliminate it entirely. The initial card capture and the token vault remain in scope. However, systems that only process tokens may be descoped from many Requirement 3 controls.
Q: How do we find PANs in our databases? A: Use a PCI-aware PII scanner that applies Luhn algorithm validation to potential card number patterns across all database columns — including text and notes fields where PANs sometimes appear accidentally.
Q: Is a 16-digit number that fails the Luhn check in scope?
A: Unlikely — failing the Luhn check suggests it's not a valid card number. However, if the column name or context suggests it should be a PAN (e.g., card_number column), it warrants investigation regardless of Luhn validity.
Find and Mask PANs in Your Databases — Free
The Database Anonymizer Tool includes PCI DSS scanning mode with Luhn algorithm validation. Inspect your SQL or CSV dataset to discover all locations where unprotected PANs are stored, then apply one-click truncation or masking rules. All processing runs in your browser — no card data leaves your device.