How to Mask Credit Card Numbers in PostgreSQL Test Data (PCI-Friendly Staging)

Payment tables are the riskiest part of a production database to copy into staging. A users table leaks names and emails; a payments table can leak card numbers (PANs), IBANs and billing addresses. This guide shows how to mask credit card numbers and other payment data in PostgreSQL before the data reaches dev, staging or CI, with a dump that still restores cleanly and keeps joins intact.

Why live card numbers must not reach staging

PCI DSS v4.0.1 requirement 6.5.5 says live PANs are not used in pre-production environments, except where those environments are inside the cardholder data environment (CDE) and protected under every applicable PCI DSS requirement. In practice almost no team wants its staging server in PCI scope, so the realistic answer is: replace every PAN before the data leaves production. The guidance also puts the burden on you to confirm that the PANs left in test data are not live (summary of requirement 6.5.5).

Two more points that matter for test data:

  • Card verification codes (CVV/CVC) should never be in your database after authorization. If you find one in a column, that is a production problem to fix, not something to mask.
  • Testing on clean data does not make you compliant. The PCI SSC's own FAQ notes that an assessment cannot be completed by testing only pre-production environments with test data (PCI SSC FAQ 1333). Masking is about keeping staging out of scope, not about passing an audit.

This article is engineering guidance, not legal or compliance advice. Check your obligations with your QSA or compliance team.

What "good" masked payment data looks like

  • Same shape: a 16-digit number that passes the Luhn check, so form validation and card-type detection in your app still work.
  • Deterministic: the same real card always maps to the same fake card. If one card was used by three accounts in production, the fake card is shared by the same three accounts in staging, so fraud and deduplication logic still has something real to test.
  • Irreversible: nobody with the dump can get the original number back.
  • Consistent across tables: a PAN that appears in payments and in refunds becomes the same fake value in both.

Step 1: Install the free CLI

Cloud-DB-Anonymizer CLI is free and MIT-licensed (source on GitHub). It needs Python 3.10+ and PostgreSQL 12+, plus pg_dump on your PATH if you want the schema included in the dump.

git clone https://github.com/fadadyounes-pixel/cloud-db-anonymizer.git
cd cloud-db-anonymizer
pip install -r requirements.txt
export ANON_SALT="$(openssl rand -hex 32)"   # keep this secret, store it in your secret manager

Every fake value is seeded from HMAC-SHA256 of the original value and your salt. Without the salt, the mapping cannot be rebuilt. Use the same salt for every run if you want fakes to stay stable from one nightly dump to the next.

Step 2: Preview what a card number becomes

python main.py preview 4111111111111111 --strategy credit_card
# 4111111111111111  →  4578478530487281   (credit_card)   (example; depends on your salt)

python main.py preview DE89370400440532013000 --strategy iban
python main.py preview pm_1Q2w3E4r5T --strategy hash

Run the same command twice and you get the same output. The credit_card strategy produces a 16-digit Visa-style number with a valid Luhn check digit, written as plain digits with no spaces or dashes. Run python main.py strategies to see all 20 strategies with sample output.

Step 3: Write rules for your payment tables

Here is a rules.json for a typical schema with customers, payments and saved payment methods:

{
  "schema": "public",
  "locale": "en_US",
  "include_unlisted_tables": true,
  "exclude_tables": ["card_vault_audit"],
  "tables": {
    "customers": {
      "columns": {
        "email": "email",
        "full_name": "name",
        "phone": "phone"
      }
    },
    "payments": {
      "columns": {
        "card_number": "credit_card",
        "cardholder_name": "name",
        "billing_street": "address",
        "billing_city": "city",
        "billing_zip": "postcode",
        "iban": "iban",
        "payer_ip": "ip"
      }
    },
    "payment_methods": {
      "columns": {
        "card_number": "credit_card",
        "card_last4": "null",
        "provider_token": "hash"
      }
    },
    "refunds": {
      "columns": { "card_number": "credit_card", "note": "redact" }
    }
  }
}

Notes on each choice:

  • credit_card on every column that holds a full PAN, in every table. Because the mapping is deterministic, the same card stays linked across payments, payment_methods and refunds.
  • card_last4 → null. The tool does not derive "last four digits of the fake card", so a kept last-4 column would not match the fake PAN. Setting it to null (or redact for a text column with a NOT NULL constraint) avoids confusing mismatches. If your app only stores last-4 and never the PAN, you can choose keep; a last-4 alone is not a PAN.
  • provider_token → hash. Payment provider tokens are not PANs, but a real token can still be used against the provider API with the right keys. A 32-character hash keeps uniqueness and joins while making the token useless.
  • iban generates a valid-format IBAN. With the en_US locale the country prefix may differ from the original; if your code validates IBAN country codes, test against that.
  • exclude_tables drops a table completely (schema and data). Use "skip_data": true on a table rule if you want the table structure but no rows.

Step 4: Validate against the live schema

python main.py sanitize \
  --db-url "postgresql://readonly_user:***@prod-replica:5432/shop" \
  --rules rules.json \
  --dry-run

The dry run prints the export plan (each table, estimated rows, which columns are masked) and warns about rules that point at missing tables or columns. Pay attention to one warning in particular: strategy 'credit_card' writes text into a 'bigint' column. Card numbers stored as bigint or numeric are a known trap: leading zeros disappear and the tool writes text values. The fake numbers are all digits, so a numeric column usually still accepts them on restore, but test that once; the safer fix in production is to store PANs (if you must store them) as text.

Step 5: Export the sanitized dump

python main.py sanitize \
  --db-url "$PROD_REPLICA_URL" \
  --rules rules.json \
  --output payments_sanitized.sql.gz

The export runs in one read-only REPEATABLE READ transaction, so every table comes from the same consistent snapshot and nothing is written to the source. The gzip SQL file contains the pg_dump schema, rows inserted in foreign-key order, and sequence and identity values reset to match. JSONB and array columns are carried over as-is unless you assign them a strategy.

Step 6: Restore and check that no real PANs survived

createdb shop_staging
gunzip -c payments_sanitized.sql.gz | psql "postgresql://localhost/shop_staging"

Then check, rather than trust. Two quick checks (run the first on both the production replica and staging):

-- 1. Spot-check: take a few payment ids and compare the last four digits
--    in production and staging. They should not match (beyond the rare 1-in-10,000 coincidence).
SELECT id, right(card_number, 4) AS last4 FROM payments WHERE id IN (101, 202, 303);

-- 2. Look for card-like digit runs in free-text columns you did not mask
SELECT id FROM support_tickets WHERE body ~ '\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}';

The second query is the one that usually finds problems. Customers paste card numbers into support tickets, order notes and chat logs. Masking structured columns does nothing for free text, so either apply redact or text to those columns, or limit them with a table where clause.

Step 7: Automate it

A one-off clean dump goes stale in a week. Add --upload my-bucket (and --endpoint-url for Cloudflare R2, DigitalOcean Spaces or MinIO) to push each dump to one S3-compatible bucket, and run it from cron or CI. The GitHub Actions guide shows a nightly workflow, and the pg_dump anonymization guide covers sharing dumps safely in more detail.

If you need the same job on a schedule with a web dashboard, a rules editor, parallel upload to AWS S3, Cloudflare R2 and DigitalOcean Spaces with retention pruning, and Telegram or Discord alerts when a run fails, that is what the self-hosted Pro Suite adds on top of the free CLI.

Checklist

  • Every full-PAN column, in every table, uses credit_card.
  • Last-4, CVV-like and token columns are null, redact or hash.
  • Free-text columns that might contain pasted card numbers are redacted.
  • ANON_SALT is a long random secret, never committed to git.
  • The dry run shows no "column not found" warnings.
  • A regex scan of the restored staging database finds no card-like numbers in unmasked columns.

More PostgreSQL test-data guides are on the PostgreSQL PII anonymizer page.