Start learning free

LESSON 28 OF 56 · SECURITY: CRYPTOGRAPHY FOR DEVELOPERS

Encrypt a Field You Must Read Back in Python

Practice

The shop stores customers' phone numbers in plain text in shop.db. The routes are staff-only, but the file isn't: anyone who gets a copy of the database, from a backup or a stolen disk, reads every customer's phone number. And if someone changes a digit in the file, support calls the wrong number and never knows.

A hash won't do here: support must read the number back, and a hash can't be turned back. You need encryption: a secret key turns the text into unreadable bytes, and the same key turns them back. AES-GCM (the AESGCM class from the cryptography package) also adds a 16-byte tag, so if a single byte is changed, decrypting raises an error instead of returning a wrong value.

Every encryption also takes a nonce: 12 random bytes, new each time, so the same number never gives the same stored bytes twice. The nonce isn't secret, and you need it again to decrypt, so you keep it with the value. Here is AES-GCM on another value, a delivery note:

box = AESGCM(AESGCM.generate_key(bit_length=256))
nonce = secrets.token_bytes(12)
sealed = box.encrypt(nonce, b"Leave it at the back door", None)
print(box.decrypt(nonce, sealed, None))   # b'Leave it at the back door'

Every request sends the X-Staff-Key header. Customers 1, 2 and 3 get their phones saved (1 and 3 share a number), and the check's hidden routes read shop.db directly and change one byte of customer 2's stored value:

PUT /customers/1/phone  {"phone": "+40 721 555 010"}  →  200  {"id": 1, "message": "Phone saved"}
GET /customers/1                                     →  200  {"id": 1, "name": "Ana Pop", "phone": "+40 721 555 010"}
GET /check/stolen                                    →  200  {"phones": [{"id": 1, "stolen": "(unreadable)"}, …], "same_stored_value": false}
POST /check/change-byte/2                            →  200  {"changed": true}
GET /customers/2                                     →  500  (an HTML error page)
GET /customers/3                                     →  200  {"id": 3, "name": "Chloe Ng", "phone": "+40 721 555 010"}

Your task: write encrypt and decrypt with the cipher aesgcm (already made from PHONE_KEY), keeping a fresh nonce in front of each encrypted value, all as hex. Then encrypt the phone in set_phone before it's saved, and decrypt it in get_customer.


Assignment
Follow the Coding Tutorial to write encrypt and decrypt and use them in the two routes.


Hint
aesgcm.encrypt(nonce, data, None) and aesgcm.decrypt(nonce, data, None) work on bytes: .encode() the text first and .decode() the result. .hex() and bytes.fromhex() turn bytes into text the column can hold, and back.


STEP 1 OF 8
    Ctrl + Enter to check

    Secx Encrypt Field in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free