Written with AI assistance.
I tested every code sample on PostgreSQL 16 and Python 3 and checked the legal text against the official MeitY PDFs. Last updated 30 November 2026.
Data masking replaces real personal data...
Data masking replaces real personal data with realistic fake values, so developers and testers can work with data that behaves like production without seeing real people's details. For test and staging databases, the safest pattern is static masking: transform the data once, before it ever reaches the lower environment, and make the transformation deterministic so joins between tables still work.
If your systems hold personal data of people in India, this is now a legal point as well as good practice. Rule 6(1)(a) of the DPDP Rules, 2025 lists "encryption, obfuscation, masking or the use of virtual tokens mapped to that personal data" among the minimum security safeguards. The DPDP Act comes into full force on 13 May 2027.
Why is a staging database a personal data risk?
A common refresh job restores last night's production backup into staging. From that moment the same customer records sit in an environment with:
- wider access: contractors, QA, support engineers, sometimes the whole engineering team,
- weaker controls: shared credentials, debug logging, fewer alerts,
- longer life: old copies that nobody deletes. Under Section 8(5) of the DPDP Act, a Data Fiduciary must protect personal data "in its possession or under its control" with reasonable security safeguards. A staging copy is still in its possession. Section 8(7) also requires erasure once the purpose is served, and a forgotten test dump is rarely covered by any retention rule.
What are the main data masking techniques?
| Technique | What It Does | Keeps Joins? | Reversible? | Good For |
|---|---|---|---|---|
| Substitution | Swaps real entries for realistic fake ones in the same format | Only if deterministic | No | Names, emails, phone numbers |
| Deterministic pseudonymisation (keyed hash) | Produces the same output every time for a given input and secret key | Yes | Not without the key | IDs and emails used to join tables |
| Shuffling | Mixes values across rows within a column | No | No | Aggregate-level analysis |
| Generalisation | Lowers precision (such as birth date to year or PIN code to district) | Yes | No | Dates and geographic locations |
| Nulling or redaction | Clears out or blacks out sensitive values | n/a | No | Free-text notes and documents |
| Tokenisation | Replaces data with a reference token stored in a vault | Yes | Yes, via the vault | Production payment flows (not test data) |
| Synthetic data | Creates fresh records with no tie to actual individuals | Designed in | No | New features and load testing |
Static vs dynamic masking: static masking changes the stored copy, which is what test and staging need. Dynamic masking hides values at query time while the real data stays in the table, for example SQL Server's Dynamic Data Masking. Dynamic masking protects a reporting screen. It does not protect a database that developers can query directly.
Is data masking reversible? It should not be, for test data. Use one-way methods, and keep any key outside the test environment. If someone who holds the key can still link a masked record back to a person, treat that copy as personal data and protect it accordingly.
How do you mask personal data in a PostgreSQL database?
The example below uses a keyed hash (HMAC from the pgcrypto extension) so that the same email produces the same masked email in every table. That keeps orders.customer_email joined to customers.email after masking.
Run it inside an isolated masking step, before the data is copied to staging. Running it on staging itself means real data sits there until the job finishes.
CREATE EXTENSION IF NOT EXISTS pgcrypto; -- Deterministic pseudonym: same input and key give the same output in every table CREATE OR REPLACE FUNCTION mask_token(kind text, val text, key text) RETURNS text LANGUAGE sql IMMUTABLE AS $$ SELECT encode(hmac(kind || ':' || lower(trim(val)), key, 'sha256'), 'hex') $$; BEGIN; SET LOCAL app.mask_key = 'replace-with-a-secret-from-your-vault'; UPDATE customers SET full_name = 'Customer ' || left(mask_token('name', full_name, current_setting('app.mask_key')), 8), email = 'user_' || left(mask_token('email', email, current_setting('app.mask_key')), 12) || '@example.invalid', mobile = '5' || lpad((('x' || left(mask_token('mobile', mobile, current_setting('app.mask_key')), 15))::bit(60)::bigint % 1000000000)::text, 9, '0'), pan = 'XXX' || substr(pan, 4, 1) || 'X' || lpad((('x' || left(mask_token('pan', pan, current_setting('app.mask_key')), 15))::bit(60)::bigint % 10000)::text, 4, '0') || 'Z', dob = make_date(extract(year FROM dob)::int, 1, 1); -- keep the year for age logic only UPDATE orders SET customer_email = 'user_' || left(mask_token('email', customer_email, current_setting('app.mask_key')), 12) || '@example.invalid'; COMMIT; Output on two sample rows: id | full_name | email | mobile | pan | dob ----+-------------------+-----------------------------------+------------+------------+------------ 1 | Customer 4d7c699b | user_a4dd56c0fd95@example.invalid | 5836217977 | XXXPX8805Z | 1988-01-01 2 | Customer 3a783f6f | user_1f85e04488ca@example.invalid | 5464073131 | XXXPX4179Z | 1992-01-01 The join from orders to customers on email still returns both orders. A few design choices are worth copying:
@example.invalid emails can never deliver to a real inbox, so a test job that sends mail cannot reach a customer.
The masked PAN keeps a valid shape (5 letters, 4 digits, 1 letter) and keeps the 4th character, which shows the holder type (P for an individual, C for a company). Format checks keep working, and the XXX prefix makes it obvious the value is fake.
The masked mobile starts with 5. Indian mobile numbers start with 6, 7, 8 or 9, so a masked number can never reach a real phone.
Date of birth keeps only the year, which is usually enough for age rules.
The key comes from a secret store, set per transaction with SET LOCAL, and is never written to the staging database.
How do you mask Indian identifiers in Python?
The same idea works in a Python pipeline, for example when you export CSV fixtures for automated tests:
import hmac, hashlib, os, re KEY = os.environ.get("MASK_KEY", "rotate-me-per-refresh").encode() def _digits(kind: str, value: str, n: int) -> str: # Same input + same key = same output, so joins across tables still work d = hmac.new(KEY, f"{kind}:{value}".encode(), hashlib.sha256).digest() return "".join(str(b % 10) for b in d[:n]) def mask_pan(pan: str) -> str: # Keep the PAN shape and the 4th character (holder type: P = individual, # C = company). The XXX prefix marks the value as fake. pan = pan.upper() return f"XXX{pan[3]}X{_digits('pan', pan, 4)}Z" def mask_aadhaar(number: str) -> str: # Real Aadhaar numbers never start with 0 or 1, so a leading 1 is always fake return "1" + _digits("aadhaar", re.sub(r"\D", "", number), 11) def mask_mobile(mobile: str) -> str: # Indian mobile numbers start with 6 to 9, so a leading 5 is always fake return "5" + _digits("mobile", re.sub(r"\D", "", mobile)[-10:], 9) def mask_email(email: str) -> str: d = hmac.new(KEY, f"email:{email.strip().lower()}".encode(), hashlib.sha256).hexdigest()[:12] return f"user_{d}@example.invalid" The same "impossible prefix" idea applies to Aadhaar. Real Aadhaar numbers never start with 0 or 1, so every masked number here starts with 1. If your test code validates the Aadhaar checksum, add a test-only flag that accepts the masked range, and make sure production validators reject it.
How do you check that nothing slipped through?
Masking jobs break quietly when someone adds a column. Add a scan that fails the pipeline if anything that looks like a real identifier is left:
import csv, re, sys PATTERNS = { "pan": re.compile(r"\b(?!XXX)[A-Z]{3}[PCHFATBLJG][A-Z][0-9]{4}[A-Z]\b"), "aadhaar": re.compile(r"\b[2-9][0-9]{3}\s?[0-9]{4}\s?[0-9]{4}\b"), "mobile": re.compile(r"(?<!\d)(?:\+91[\s-]?)?[6-9][0-9]{4}[\s-]?[0-9]{5}(?!\d)"), "email": re.compile(r"[\w.+-]+@(?!example\.invalid)[\w-]+\.[\w.]+"), } def scan(path): hits = 0 with open(path, newline="", encoding="utf-8") as f: for line_no, row in enumerate(csv.reader(f), start=1): for cell in row: for kind, rx in PATTERNS.items(): if rx.search(cell): hits += 1 print(f"{path}:{line_no}: possible unmasked {kind}") return hits if __name__ == "__main__": total = sum(scan(p) for p in sys.argv[1:]) sys.exit(1 if total else 0) The patterns ignore the masked forms (XXX PANs, Aadhaar numbers starting with 1, mobiles starting with 5, @example.invalid emails), so masked data passes and real-looking data fails. On my test files, a real-data CSV produced 8 findings and exit code 1; the masked CSV produced none and exit code 0. Run it in CI against every exported fixture and every staging dump.
What else do the DPDP Rules expect around test environments?
Masking covers Rule 6(1)(a). The rest of Rule 6 applies to the lower environments too:
- 6(1)(b) access control: staging access by role, reviewed regularly.
- 6(1)(c) logging and monitoring of who accessed personal data, if any remains.
- 6(1)(e) one-year retention of those logs.
- 6(1)(f) contracts with Data Processors: if an outside QA or development vendor uses your test data, the contract should require safeguards.
If a staging copy holding real data is exposed, it is a personal data breach like any other. I wrote up the 72-hour reporting steps in a DPDP breach notification runbook.
Which data masking tools are available?
You do not need a commercial product to start. Open source and built-in options include the PostgreSQL Anonymizer extension, pgcrypto (used above), SQL Server Dynamic Data Masking (dynamic only), and the masking features in cloud data warehouses such as Snowflake. Commercial test data management tools add discovery of sensitive columns, referential integrity across many databases, and scheduling. The right choice depends on how many databases you have and how often they refresh.
Limitations and trade-offs
- Deterministic masking can leak patterns. If one customer has 500 orders, the masked ID still has 500 orders. For most tests that is fine; for analytics on sensitive groups, add generalisation or synthetic data.
- Free text is the hardest part. Support tickets, notes and uploaded documents can hold names and numbers anywhere. Null them, or run them through a separate redaction step.
- Rotate the key per refresh if you do not need masked IDs to stay stable across refreshes. That breaks any link between old and new copies.
- This is engineering guidance, not legal advice. Check your own obligations against the Act and the Rules.
