Database Protecting Sensitive Data
What you will learn
- Which data is sensitive
- Why to collect less
- How to store passwords with a salted hash
- Masking and other protections
1. What is sensitive?
Some data causes harm if it leaks: passwords, ID numbers, health records, payment details, addresses, private messages. Some laws and rules apply to such data, and they differ by country, so check the rules that apply to you. This lesson covers technical habits that help in any case.
2. Collect and keep less
The safest data is data you do not have. Before adding a column, ask whether you need it, how long you need it, and who must see it. Delete data when it is no longer needed.
3. Passwords: never plain text
If the database leaks and passwords are plain text, every account is open (and people reuse passwords elsewhere). Instead store a hash: the result of a one-way function. To check a login, hash what the user typed and compare. Two details matter:
- A salt: a random value added to each password, so two users with the same password get different hashes.
- A slow hash made for passwords, so guessing is expensive. Python's
hashlibhaspbkdf2_hmacandscryptfor this, but they are missing from the browser version of Python used by the Try it box. So the examples below use a small teaching function that repeats SHA-256 many times to show the idea. Do not use it in a real project: usepbkdf2_hmac,scryptor, better, your web framework's password tools.
import hashlib, os, hmac
def slow_hash(password, salt, rounds=100_000):
# teaching toy: repeat SHA-256 so each guess costs 100,000 hashes
h = salt + password.encode()
for _ in range(rounds):
h = hashlib.sha256(h).digest()
return h
pw = "correct horse"
salt = os.urandom(16)
h = slow_hash(pw, salt)
print(len(salt), len(h))
16 32
You store the salt and the hash (16 and 32 bytes here), never the password. To check a login:
def check(p, salt, stored):
return hmac.compare_digest(slow_hash(p, salt), stored)
print(check("correct horse", salt, h), check("wrong", salt, h))
True False
hmac.compare_digest compares without leaking, through timing, how much matched. Another user with the same password gets a different salt and so a different hash:
salt2 = os.urandom(16)
h2 = slow_hash(pw, salt2)
print("same password, different hash:", h != h2)
same password, different hash: True
In real projects, prefer the password tools of your web framework, which handle these details for you. A plain fast hash such as SHA-256 on its own is not suitable for passwords.
4. Masking, encryption and access
Masking shows only part of a value where the full value is not needed:
def mask(email):
n, d = email.split("@")
return n[0] + "***@" + d
print(mask("rina@example.com"))
r***@example.com
Masking in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). A query can mask values itself, and a view can make the masked form the only one a report ever sees. Reset data removes the view.
CREATE VIEW masked_customers AS
SELECT customer_id,
substr(email, 1, 1) || '***@' || substr(email, instr(email, '@') + 1) AS email,
COALESCE(substr(phone, 1, 3) || ' ***', 'no phone') AS phone
FROM customers;
SELECT * FROM masked_customers ORDER BY customer_id LIMIT 4;
customer_id email phone
----------- ---------------- --------
1 v***@example.com +35 ***
2 w***@example.com no phone
3 d***@example.com +58 ***
4 n***@example.com +48 ***
(4 rows)
CREATE VIEW masked_customers AS
SELECT customer_id,
substr(full_name, 1, 1) || '***' AS full_name,
substr(birth_date, 1, 4) || '-**-**' AS birth_date
FROM customers;
SELECT * FROM masked_customers ORDER BY customer_id LIMIT 4;
customer_id full_name birth_date
----------- --------- ----------
1 C*** 1956-**-**
2 R*** 1990-**-**
3 G*** 1961-**-**
4 M*** 1977-**-**
(4 rows)
CREATE VIEW masked_students AS
SELECT student_id,
substr(email, 1, 1) || '***@' || substr(email, instr(email, '@') + 1) AS email,
substr(guardian_name, 1, 1) || '***' AS guardian_name
FROM students;
SELECT * FROM masked_students ORDER BY student_id LIMIT 4;
student_id email guardian_name
---------- -------------------- -------------
1 v***@student.example A***
2 e***@student.example N***
3 c***@student.example M***
4 q***@student.example F***
(4 rows)
The first character (or the year) is kept so a person can still recognise a row, and the rest is hidden.
5. Encryption: in transit and at rest
Encryption scrambles data so that only someone with the key can read it. Two places matter:
- In transit: data travelling between the program and the database server over a network. Server databases can be set up to use an encrypted connection (usually TLS); the setting and the certificates are product-specific, so follow your product's documentation. A database on the same machine as the program (like SQLite here) has no network hop.
- At rest: data stored on disk, including backups. Options are encrypting the whole disk or volume, encrypting backup files, or a database feature. The standard SQLite library does not encrypt its files by itself; encryption for SQLite needs a separate extension (SQLite's own documentation names a licensed one, SEE), so for SQLite the practical choice is disk or backup encryption.
Encryption protects against a stolen disk or backup. It does not protect against a user who is allowed in, or against SQL injection (lesson 8.5), because the database decrypts data for anyone who is allowed to ask. And the key must be stored somewhere other than next to the data; otherwise the lock and the key are in the same drawer.
6. Other habits
- Encrypt connections between the program and the database, and encrypt backups and disks that hold private data.
- Limit access (lesson 8.4) and keep passwords and keys out of code and out of version control.
- Keep software updated.
- Keep logs without secrets: do not write passwords or full card numbers to log files.
Worked example: a signup form
A made-up club collects name, e-mail, phone and a password.
| Field | Decision |
|---|---|
| Name, e-mail | needed; show masked in admin lists |
| Phone | not needed for the club: remove the column |
| Password | salted slow hash only |
| Backups | encrypted, with the key stored elsewhere |
Common mistakes
- Storing passwords in plain text or with a fast hash and no salt.
- Inventing your own scheme instead of a standard tool.
- Collecting data "just in case".
- Leaving secrets in code, logs or backups anyone can read.
Key takeaways
- Collect and keep less.
- Store passwords as salted, slow hashes, never as text.
- Mask what you display; encrypt connections and backups.
- Limit access, and keep secrets out of code and logs.
Practice
1. Why not store passwords as plain text?
Show answer
A leak would give attackers every password, which people often reuse elsewhere.
2. What does a salt do?
Show answer
It is a random value added per password, so equal passwords get different hashes and precomputed tables do not work.
3. Why use a slow hash for passwords?
Show answer
It makes each guess costly for someone trying many guesses.
4. What did mask("rina@example.com") return?
Show answer
r***@example.com.
5. Name two places where secrets often leak by mistake.
Show answer
For example code in version control, log files and unencrypted backups.
6. A company encrypts its database disk and says "so SQL injection cannot leak our data". What is wrong with that claim?
Show answer
Disk encryption protects a stolen disk or backup. A running database decrypts data for any query it is allowed to run, so an injected query still reads the data. Parameterised queries and least privilege (lessons 8.4 and 8.5) are what stop injection.