Start learning free

LESSON 42 OF 76 · SECURITY: CRYPTOGRAPHY FOR DEVELOPERS

A Hash Is Not Encryption

Practice

A hash like SHA-256 turns any text into a fixed 64-character fingerprint. It has no key and no way back: nobody can decrypt it. But the same input always gives the same hash, so anyone can hash a guess and compare.

The attack: a gift-card PIN has 4 digits, so there are only 10,000 of them. If the shop stored the plain SHA-256 of each PIN, a thief with a copy of the database would hash 0000 to 9999 in a moment, match every card's PIN and spend every balance.

The fix: an HMAC is a hash with a secret key mixed in. The key lives in the server's environment, not in the database, so a stolen copy can't be matched without it:

SECRET = os.environ["DEMO_KEY"].encode()
plain = hashlib.sha256(b"0420").hexdigest()                    # anyone can make this
keyed = hmac.new(SECRET, b"0420", hashlib.sha256).hexdigest()  # only the server can

Staff add cards, customers check a balance with the code and PIN, and the hidden check GET /check/stolen plays the thief: it hashes all 10,000 PINs with plain SHA-256 and looks for each card's stored value.

POST /gift-cards  (staff key)  {"code": "GC-1001", "pin": "4821", "balance": 50}  →  201  {"code": "GC-1001", "balance": 50}
POST /gift-cards/balance  {"code": "GC-1001", "pin": "4821"}  →  200  {"code": "GC-1001", "balance": 50}
POST /gift-cards/balance  {"code": "GC-1001", "pin": "4822"}  →  401  {"error": "Wrong code or PIN"}
POST /gift-cards/balance  {"code": "GC-1003", "pin": "1234"}  →  401  {"error": "Wrong code or PIN"}
GET /check/stolen  →  200  [{"code": "GC-1001", "pin": null}, {"code": "GC-1002", "pin": null}]

Your task: both routes already call pin_hash, which doesn't exist yet. Read PIN_KEY from the environment as bytes, then write pin_hash(pin) to return the HMAC-SHA256 of the PIN with that key, as hex.


Assignment
Follow the Coding Tutorial to store gift-card PINs as an HMAC with a key only the server holds.


Hint
hmac.new(key, message, hashlib.sha256) needs bytes for both the key and the message: call .encode() on text. .hexdigest() gives the 64-character text to store.


STEP 1 OF 3
    Ctrl + Enter to check