Skip to content
Stribog

Compliance

All writing

PCI DSS and the PAN: Masking, Truncation, Hashing, Tokens

PCI DSS masks the PAN on screen, then demands truncation, keyed hashes, tokens or encryption at rest. What each option costs, built self-hosted.

By 13 min read

Advice on the PCI DSS PAN usually stops at a list: mask, truncate, hash, tokenise, encrypt. The list is correct and nearly useless, because the five treatments live in two requirements and answer different questions. This article maps each treatment to an engineering decision, then builds them on infrastructure you own.

The PAN is the element that drags systems into scope

PCI DSS v4.0.1 is explicit about where scope starts: "The primary account number (PAN) is the defining factor for cardholder data." Name, expiry and service code only become account data alongside a PAN. So every storage decision here is a scope decision, and the audit-scope argument begins and ends with where the PAN lives.

Sensitive authentication data is harsher. Requirement 3.3.1: "SAD is not stored after authorization, even if encrypted," and all SAD received "is rendered unrecoverable upon completion of the authorization process." Two limits apply. Issuers and companies that support issuing services, where there is a legitimate and documented business need, are not required to meet it. For everyone else, the guidance allows SAD in non-persistent memory briefly after authorization, under conditions including a legitimate business need and removal as soon as the purpose is complete; "It is not permissible to store SAD in persistent memory."

That leaves the PAN, and requirement 3 asks two questions about it: what is shown (3.4) and what is stored (3.5).

Masking is a display control, not a storage control

Requirement 3.4.1: "PAN is masked when displayed (the BIN and last four digits are the maximum number of digits to be displayed), such that only personnel with a legitimate business need can see more than the BIN and last four digits of the PAN." PCI SSC FAQ 1492 adds what the exception needs: a documented business justification that explains why the person or role needs more digits, approved by management and available for an assessor to review.

The guidance is blunt: "Masking is not synonymous with truncation and these terms cannot be used interchangeably." Masking conceals digits during display or printing "even when the entire PAN is stored on a system". Truncation removes digits so they cannot be retrieved within the system. Masked PAN can be unmasked; there is no "un-truncation" without recreating the PAN from another source. Truncating one column achieves little if another system holds the full PAN.

A support console rendering •••• 1111 over a cleartext cards.pan column passes 3.4.1 and fails 3.5.1. The mask does nothing for the database file, the replica, the dump or the slow-query log.

Requirement 3.4.2 extends display control to remote access: technical controls prevent copy and relocation of PAN for all personnel using remote-access technologies, except those with documented, explicit authorization and a legitimate, defined business need. It became required after 31 March 2025.

  • Mask server-side; a mask applied in browser JavaScript has already shipped the full PAN.
  • Make unmasking a separate endpoint bound to a role with an approved justification.
  • Log the unmask event, never the value: 3.5.1 covers audit logs too.

Four ways to render a stored PAN unreadable

Requirement 3.5.1: "PAN is rendered unreadable anywhere it is stored" using one-way hashes based on strong cryptography of the entire PAN; truncation, where "hashing cannot be used to replace the truncated segment of PAN"; index tokens; or strong cryptography with associated key-management processes and procedures. "Anywhere" is literal: the requirement covers databases and flat files, and also backup, audit, exception and troubleshooting logs.

  • Keyed hash (3.5.1, 3.5.1.1). Not recoverable. Supports equality lookup, which is its whole point: "have we seen this card before?" Requires a key under 3.6 and 3.7. FAQ 1089: a hash transferred to a separate environment is no longer cardholder data there, but the system that hashed it and still stores it stays in scope; if you need the PAN back, hashing is not an option.
  • Truncation. Not recoverable, needs no key, supports only partial matching. FAQ 1117: systems holding only truncated PANs may be out of scope if adequately segmented and holding no other cardholder or authentication data, but the system performing truncation and connected systems stay in scope.
  • Index token. Appendix G: "A random value from a table of random values that corresponds to a given PAN." Recoverable through the table, which holds PANs and is therefore cardholder data itself.
  • Strong cryptography. Recoverable by whoever holds the key, with the full 3.6/3.7 key-management burden. The standard is blunt that "encryption alone is generally insufficient to render the cardholder data out of scope", and systems performing encryption, decryption or key management are in scope.

FAQ 1091 sets the first six and last four digits as the starting baseline to retain, considering the business need. Where more digits are genuinely necessary, the maximum for a 16-digit PAN (Discover, JCB, Mastercard, UnionPay, Visa) is "first 8, any other 4" with at least four digits removed; for a 15-digit American Express PAN at least five digits are removed and the maximum is "first 6, last 4"; Discover PANs shorter than 15 digits may retain at most "first 6, any other 4". Treat first-8 as a ceiling you justify, not a format you default to.

The same FAQ warns that "access to different truncation formats of the same PAN greatly increases the ability to reconstruct full PAN". Two correct truncations in different shapes can together disclose most of the number.

Two requirements, five treatments. Masking answers the display question; the storage question splits on whether the PAN must ever come back.

The correlation trap: truncated and hashed copies of the same PAN

Requirement 3.5.1 carries an easily missed sub-clause: if hashed and truncated versions of the same PAN, or different truncation formats of the same PAN, are present in an environment, "additional controls are in place such that the different versions cannot be correlated to reconstruct the original PAN." The guidance explains why: "It is a relatively trivial effort for a malicious individual to reconstruct original PAN data if they have access to both the truncated and hashed versions of a PAN."

Take a 16-digit PAN stored as first six and last four, next to an unkeyed hash of the full number. Six digits are unknown, so there are at most 10^6 candidates. The last digit is a Luhn check digit and it is visible; for any choice of five middle digits, exactly one value of the sixth satisfies the check, so 10^5 candidates remain. A salt stored beside the hash does not shrink that work; only a secret the attacker does not hold changes it.

FAQ 1308: "The simplest solution is not to store both hashed and truncated PANs." If both must be retained, it lists examples only: strong, unique, secret salts; separate, segmented storage with distinct access controls; no cross-references or database links between values; real-time monitoring for correlation attempts. It then names the control that removes the search: keyed cryptographic hashes under 3.5.1.1, "a valid additional control to prevent correlation."

Read those together carefully: salts appear among example controls, but a salted, unkeyed SHA-256 no longer qualifies as the hash itself. Requirement 3.5.1.1 says hashes used to render PAN unreadable "are keyed cryptographic hashes of the entire PAN" with key management under 3.6 and 3.7; it became required after 31 March 2025. FAQ 1492: "All hashes generated after 31 March 2025 must be keyed." FAQ 1573: not retroactive to previously hashed PANs, but every hashing process after that date must comply. Appendix G names HMAC, CMAC and GMAC with an effective strength of at least 128 bits as appropriate algorithms.

A self-hosted build: Postgres for data, OpenBao Transit for keys

In this reference design, OpenBao's Transit engine holds keys and performs cryptography; per its docs it "doesn't store the data sent to the secrets engine" and the caller stores the ciphertext. Postgres stores ciphertext, a keyed hash and a random token. Transit is not a tokenisation product: the index token is a random UUID in a table the operator runs, matching the Appendix G definition.

pan-enc is an aes256-gcm96 key for the recoverable copy; pan-idx is a dedicated hmac key for the lookup index. For an hmac-type key, the key itself is the HMAC key, and key_size (in bytes) must be set explicitly: the API field defaults to 0 and HMAC keys must be 32 to 512 bytes, so creation without it fails.

bash
#!/usr/bin/env bash
set -euo pipefail

bao secrets enable transit

bao write -f transit/keys/pan-enc type=aes256-gcm96

# key_size is in bytes; the API default (0) fails for hmac keys.
bao write transit/keys/pan-idx type=hmac key_size=32

bao policy write pan-tokenizer - <<'HCL'
path "transit/encrypt/pan-enc" { capabilities = ["update"] }
path "transit/hmac/pan-idx"    { capabilities = ["update"] }
HCL

bao policy write pan-detokenizer - <<'HCL'
path "transit/decrypt/pan-enc" { capabilities = ["update"] }
HCL

# Never assigned to an application.
bao policy write pan-key-ops - <<'HCL'
path "transit/keys/pan-enc/rotate" { capabilities = ["update"] }
path "transit/keys/pan-idx/rotate" { capabilities = ["update"] }
path "transit/keys/pan-enc/config" { capabilities = ["update"] }
path "transit/rewrap/pan-enc"      { capabilities = ["update"] }
HCL

# Both take base64 input; both return vault:v<version>:<base64>.
PAN_B64=$(printf '%s' 4111111111111111 | base64)
bao write transit/hmac/pan-idx input="$PAN_B64"
bao write transit/encrypt/pan-enc plaintext="$PAN_B64"
transit-setup.sh: one-time Transit setup and three separated policies. 4111111111111111 is a public test number, not a real card.

The vault table stores ciphertext and HMAC, each carrying its key version in the vault:vN: prefix, plus a random token and the last four digits. It deliberately omits the BIN, but that does not escape 3.5.1's coexistence clause: last four beside a hash is still a truncated version beside a hashed one. The additional control relied on is the one the standard and FAQ 1308 name, a keyed hash under 3.5.1.1. The 10^5 search above applies only to an unkeyed hash; with HMAC, an attacker without the Transit key has nothing to search against.

sql
CREATE TABLE pan_vault (
    token            uuid        PRIMARY KEY DEFAULT gen_random_uuid(),
    pan_ct           text        NOT NULL CHECK (pan_ct LIKE 'vault:v%'),
    pan_hmac         text        NOT NULL UNIQUE CHECK (pan_hmac LIKE 'vault:v%'),
    hmac_key_version integer     NOT NULL CHECK (hmac_key_version > 0),
    last4            char(4)     NOT NULL CHECK (last4 ~ '^[0-9]{4}$'),
    created_at       timestamptz NOT NULL DEFAULT now()
);

CREATE VIEW card_display WITH (security_barrier = true) AS
    SELECT token, '•••• ' || last4 AS display
    FROM pan_vault;

CREATE ROLE app_reader NOLOGIN;
CREATE ROLE pan_ingest NOLOGIN;
CREATE ROLE pan_detok  NOLOGIN;

REVOKE ALL ON pan_vault FROM PUBLIC;
REVOKE ALL ON card_display FROM PUBLIC;

GRANT SELECT ON card_display TO app_reader;

GRANT SELECT (token, pan_hmac) ON pan_vault TO pan_ingest;
GRANT INSERT (pan_ct, pan_hmac, hmac_key_version, last4) ON pan_vault TO pan_ingest;
GRANT UPDATE (pan_hmac) ON pan_vault TO pan_ingest;

GRANT SELECT (token, pan_ct) ON pan_vault TO pan_detok;
pan_vault.sql: the token vault, a masked view and column-level grants. PostgreSQL 13+ (gen_random_uuid is built in).

Ingest strips the number to digits, sends it base64-encoded to both endpoints, and upserts on the HMAC so a card always maps to one token.

python
import base64
import json
import os
import urllib.request

import psycopg

BAO_ADDR = os.environ["BAO_ADDR"]
BAO_TOKEN = os.environ["BAO_TOKEN"]


def _transit(path: str, payload: dict) -> dict:
    req = urllib.request.Request(
        f"{BAO_ADDR}/v1/transit/{path}",
        data=json.dumps(payload).encode(),
        headers={"X-Vault-Token": BAO_TOKEN, "Content-Type": "application/json"},
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=5) as resp:
        return json.load(resp)["data"]


def _key_version(value: str) -> int:
    prefix, version, _ = value.split(":", 2)
    if prefix != "vault" or not version.startswith("v"):
        raise ValueError("unexpected Transit output format")
    return int(version[1:])


def tokenise(conn: psycopg.Connection, raw: str) -> str:
    pan = "".join(ch for ch in raw if ch.isdigit())
    b64 = base64.b64encode(pan.encode()).decode()
    digest = _transit("hmac/pan-idx", {"input": b64})["hmac"]
    ciphertext = _transit("encrypt/pan-enc", {"plaintext": b64})["ciphertext"]
    with conn.cursor() as cur:
        cur.execute(
            """
            INSERT INTO pan_vault (pan_ct, pan_hmac, hmac_key_version, last4)
            VALUES (%s, %s, %s, %s)
            ON CONFLICT (pan_hmac) DO UPDATE SET pan_hmac = EXCLUDED.pan_hmac
            RETURNING token
            """,
            (ciphertext, digest, _key_version(digest), pan[-4:]),
        )
        row = cur.fetchone()
    conn.commit()
    return str(row[0])
tokenise.py: tokenise on ingest. Standard library for Transit, psycopg 3 for Postgres; runs with the pan-tokenizer policy and the pan_ingest role.
The reference build. The key-storage gate under 3.6.1.2 is drawn open on purpose: closing it is a deployment decision, not a property of the default install.

This build does not, by itself, meet 3.6.1.2, which requires keys protecting stored account data to be held at all times encrypted under a separately stored key-encrypting key at least as strong, within a secure cryptographic device such as an HSM, or as at least two full-length components or shares. A default OpenBao install keeps Transit keys inside its barrier; Shamir unseal and auto-unseal protect that barrier and are not one of those forms. Closing the gate is an operator decision, most directly a seal backed by a secure cryptographic device, argued as the SCD form.

Failure modes an operator actually meets

HMAC rotation breaks lookups. OpenBao's API docs say each Transit key version has an independent HMAC secret, and the HMAC endpoint uses the latest version unless key_version is set. The consequence follows: rotate pan-idx and the same PAN produces a different digest, so the unique index stops matching returning cards and the upsert quietly creates a second token. Pin key_version on lookups until the index is rebuilt by decrypting and re-HMACing every row inside the CDE; that is why hmac_key_version is a column.

bash
# excerpt: batch iteration over pan_vault is elided
set -euo pipefail

# Encryption key: rotate, rewrap in batches, retire old versions.
bao write -f transit/keys/pan-enc/rotate
#   for each batch of (token, pan_ct):
#     new_ct=$(bao write -field=ciphertext transit/rewrap/pan-enc ciphertext="$pan_ct")
#     UPDATE pan_vault SET pan_ct = new_ct WHERE token = token
#   only after every row is rewrapped, or old PANs are lost:
#     bao write transit/keys/pan-enc/config min_decryption_version=2

# Valid only because pan-idx was created with key_size=32.
# New HMACs differ; rotate only with the rebuild ready:
#   bao write -f transit/keys/pan-idx/rotate
#   for each row, inside the CDE:
#     pan = decrypt(pan_ct)
#     UPDATE pan_vault SET pan_hmac = hmac(pan), hmac_key_version = new
#   lookups pin key_version=<old> until done
Rotation runbook, excerpt: the database batch loops are elided and shown as comments.

Convergent encryption used as an index. Transit supports convergent encryption, "where the same plaintext creates the same ciphertext", and it requires derived=true. It leaks equality by design, a PAN is a small plaintext, and OpenBao's docs note that the older version 2 algorithm was open to offline plaintext confirmation for small plaintexts; version 3 is current, but equality leakage remains. Keep lookup and recovery on separate keys.

pgcrypto inside the database. pgcrypto offers hmac(data, key, type), and its own documentation states the limitation: all functions run inside the database server, so "all the data and passwords move between pgcrypto and client applications in clear text"; you must trust both system and database administrator, or "do crypto inside client application." Because hmac() runs on the server, its key argument is visible there too.

Disk encryption standing in for 3.5.1. Requirement 3.5.1.2, now required, allows disk- or partition-level encryption as the means of rendering PAN unreadable only on removable media, or on non-removable media when the PAN is also protected by another 3.5.1 mechanism. It applies to any encryption that provides clear-text PAN automatically when a system runs. LUKS is good hygiene, not the control.

The PAN in the logs. Body-capturing request loggers, stack traces and dead-letter queues are all storage under 3.5.1. Redact at the edge and grep log sinks for Luhn-valid digit runs. Backups that outlive the data follow the logic of destroying keys rather than chasing copies.

What the assessor is shown, and what leaving costs

Evidence for 3.5.1 is an inventory of every store holding PAN in any form, including backups and logs, with its treatment. For 3.5.1.1 it is the key definition (type=hmac, its size, the policy that may use it) and the documented key-management procedure for it. For 3.6.1.2 the assessor asks which of the three forms the key arrangement is. The applicability notes help: keys in a key management system that employs SCDs are acceptable; a key split into two parts is not. As drawn, the reference build does not yet answer that; the seal configuration does.

Owning the key manager and vault has a scope price: both sit in the CDE with ingest and the detokeniser, and should be segmented with enforced default-deny policy rather than a diagram. PCI SSC's 2011 Tokenization Guidelines, written against PCI DSS 2.0, say the data vault "often presents the most attractive target for attackers"; its 2015 Tokenization Product Security Guidelines treat a token as reversible if de-tokenisation is technically possible, whatever the producer intends. FAQ 1117 leaves the scope of format-preserving tokenised values to an assessor's view of the specific implementation, while the systems doing tokenisation and key management stay in scope; the SAQ eligibility question turns on the same facts.

The exit ramp is the reason to build it this way. Tokens in your own table survive a change of key manager, processor or cloud. Transit's rewrap re-encrypts under the latest key version without returning plaintext, min_decryption_version retires old versions, and exportable, once set, cannot be disabled, so leave it off until a migration needs it. The proprietary equivalent, Vault's Transform engine (format-preserving encryption, masking, tokenisation), requires Vault Enterprise with the ADP-Transform module. Compare the trade-offs between OpenBao and Vault.

The long game: store less PAN

The durable ordering: do not store the PAN. If you need to recognise a returning card, store a keyed hash. If you genuinely need the number back, encrypt it in one place, behind one key manager, and hand everything else a token. Treat every additional format of the same PAN, a second truncation shape, an old unkeyed hash, a debug export, as a liability that compounds, because correlation is what turns two acceptable copies into one recovered number.

Built on Postgres and OpenBao, the design is inspectable down to the policy file, has no licence gate on the core path, and leaves the tokens in your hands when the stack changes. The assessor's questions do not get easier; they get answerable by the people who own the system.

§FAQ/Common questions

Frequently asked

What is the difference between PAN masking and truncation in PCI DSS?

Masking (requirement 3.4.1) hides digits when the PAN is displayed, even when the full PAN is stored; at most the BIN and last four may be shown without a documented business need. Truncation (3.5.1) removes digits from storage so they cannot be retrieved within the system. Masking satisfies no storage requirement.

Can I store an unkeyed SHA-256 hash of the PAN?

Not as a new practice. Requirement 3.5.1.1 has been required since 31 March 2025: hashes used to render PAN unreadable must be keyed cryptographic hashes of the entire PAN with key management under 3.6 and 3.7. FAQ 1573 says previously hashed PANs are not affected retroactively.

Why is storing truncated and hashed versions of the same PAN a problem?

With the BIN and last four visible, the unknown middle digits leave a small candidate space that an attacker can hash and compare against an unkeyed digest. Requirement 3.5.1 requires controls preventing correlation; FAQ 1308 says the simplest fix is not storing both, and keyed hashing is a valid additional control.

Does disk encryption satisfy PCI DSS requirement 3.5.1?

Only on removable media. On non-removable media, requirement 3.5.1.2 allows disk- or partition-level encryption only if the PAN is also rendered unreadable by another 3.5.1 mechanism, because such encryption provides clear-text PAN automatically while the system runs.

pci dss panpci dss pan masking vs truncationpci dss requirement 3.5.1 render pan unreadablepci dss keyed cryptographic hash 3.5.1.1pan truncation formats first 8 last 4hashed and truncated pan correlation

Executive Briefing

Thirty minutes to clarify your infrastructure risk

Walk us through your vendor footprint and regulatory constraints. We will tell you honestly where sovereignty creates leverage — and where it does not. No pitch deck. No obligation.