Mask and tokenize data in a database
With Python's built-in SQLite, store fake customer data, give support staff a masked view, and replace card numbers with tokens held in a separate vault table.
Environment
Python 3 on your own computer (the sqlite3 module is built in).
Before you start
- Read Obfuscation (p.78), Database Encryption (p.72) and Data Protection (p.428).
You will
- Create a masked view
- Implement simple tokenization
- Compare masking, tokenization and encryption
Steps
-
1
In Python:
import sqlite3, secrets; db = sqlite3.connect('shop.db'). -
2
Create a table and add fake rows:
db.execute('CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, phone TEXT, card TEXT)'), then insert three made-up customers (use the test card number 4111111111111111). -
3
Create a masked view for support staff:
db.execute("CREATE VIEW support_view AS SELECT id, name, substr(phone,1,3) || '-xxx-xxxx' AS phone, '**** **** **** ' || substr(card,-4) AS card FROM customers")and query it. -
4
Tokenize: create
vault(token TEXT PRIMARY KEY, card TEXT). For each customer, generatetoken = secrets.token_hex(8), store(token, card)in the vault, and replace the card column with the token. -
5
Show that the customers table no longer holds card numbers, and that an authorized lookup in the vault gets them back.
-
6
Write a table comparing masking, tokenization and encryption: reversible? keys needed? where the real data lives?
Check your understanding
- ?Why is tokenization often used for card data in scope for compliance?
- ?Is masking reversible for the person viewing the masked data?
- ?What becomes the most important asset to protect once you tokenize?